<commit_before>/*
Copyright 2020 The Kubernetes 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.
*/

package apiserver

import (
	"context"
	"encoding/json"
	"strings"
	"testing"

	v1 "k8s.io/api/core/v1"
	apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	genericfeatures "k8s.io/apiserver/pkg/features"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	featuregatetesting "k8s.io/component-base/featuregate/testing"
	apiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/test/integration/etcd"
	"k8s.io/kubernetes/test/integration/framework"
	"sigs.k8s.io/yaml"
)

// namespace used for all tests, do not change this
const testNamespace = "statusnamespace"

var statusData = map[schema.GroupVersionResource]string{
	gvr("", "v1", "persistentvolumes"):                                  `{"status": {"message": "hello"}}`,
	gvr("", "v1", "resourcequotas"):                                     `{"status": {"used": {"cpu": "5M"}}}`,
	gvr("", "v1", "services"):                                           `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("extensions", "v1beta1", "ingresses"):                           `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("networking.k8s.io", "v1beta1", "ingresses"):                    `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("networking.k8s.io", "v1", "ingresses"):                         `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("autoscaling", "v1", "horizontalpodautoscalers"):                `{"status": {"currentReplicas": 5}}`,
	gvr("batch", "v1beta1", "cronjobs"):                                 `{"status": {"lastScheduleTime": null}}`,
	gvr("batch", "v2alpha1", "cronjobs"):                                `{"status": {"lastScheduleTime": null}}`,
	gvr("storage.k8s.io", "v1", "volumeattachments"):                    `{"status": {"attached": true}}`,
	gvr("policy", "v1beta1", "poddisruptionbudgets"):                    `{"status": {"currentHealthy": 5}}`,
	gvr("certificates.k8s.io", "v1beta1", "certificatesigningrequests"): `{"status": {"conditions": [{"type": "MyStatus"}]}}`,
	gvr("certificates.k8s.io", "v1", "certificatesigningrequests"):      `{"status": {"conditions": [{"type": "MyStatus", "status": "True"}]}}`,
	gvr("internal.apiserver.k8s.io", "v1alpha1", "storageversions"):     `{"status": {"commonEncodingVersion":"v1","storageVersions":[{"apiServerID":"1","decodableVersions":["v1","v2"],"encodingVersion":"v1"}],"conditions":[{"type":"AllEncodingVersionsEqual","status":"True","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"allEncodingVersionsEqual","message":"all encoding versions are set to v1"}]}}`,
}

const statusDefault = `{"status": {"conditions": [{"type": "MyStatus", "status":"True"}]}}`

func gvr(g, v, r string) schema.GroupVersionResource {
	return schema.GroupVersionResource{Group: g, Version: v, Resource: r}
}

func createMapping(groupVersion string, resource metav1.APIResource) (*meta.RESTMapping, error) {
	gv, err := schema.ParseGroupVersion(groupVersion)
	if err != nil {
		return nil, err
	}
	if len(resource.Group) > 0 || len(resource.Version) > 0 {
		gv = schema.GroupVersion{
			Group:   resource.Group,
			Version: resource.Version,
		}
	}
	gvk := gv.WithKind(resource.Kind)
	gvr := gv.WithResource(strings.TrimSuffix(resource.Name, "/status"))
	scope := meta.RESTScopeRoot
	if resource.Namespaced {
		scope = meta.RESTScopeNamespace
	}
	return &meta.RESTMapping{
		Resource:         gvr,
		GroupVersionKind: gvk,
		Scope:            scope,
	}, nil
}

// TestApplyStatus makes sure that applying the status works for all known types.
func TestApplyStatus(t *testing.T) {
	defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)()
	server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), []string{"--disable-admission-plugins", "ServiceAccount,TaintNodesByCondition"}, framework.SharedEtcd())
	if err != nil {
		t.Fatal(err)
	}
	defer server.TearDownFn()

	client, err := kubernetes.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatal(err)
	}
	dynamicClient, err := dynamic.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatal(err)
	}

	// create CRDs so we can make sure that custom resources do not get lost
	etcd.CreateTestCRDs(t, apiextensionsclientset.NewForConfigOrDie(server.ClientConfig), false, etcd.GetCustomResourceDefinitionData()...)
	if _, err := client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}, metav1.CreateOptions{}); err != nil {
		t.Fatal(err)
	}

	createData := etcd.GetEtcdStorageData()

	// gather resources to test
	_, resourceLists, err := client.Discovery().ServerGroupsAndResources()
	if err != nil {
		t.Fatalf("Failed to get ServerGroupsAndResources with error: %+v", err)
	}

	for _, resourceList := range resourceLists {
		for _, resource := range resourceList.APIResources {
			if !strings.HasSuffix(resource.Name, "/status") {
				continue
			}
			mapping, err := createMapping(resourceList.GroupVersion, resource)
			if err != nil {
				t.Fatal(err)
			}
			t.Run(mapping.Resource.String(), func(t *testing.T) {
				status, ok := statusData[mapping.Resource]
				if !ok {
					status = statusDefault
				}
				newResource, ok := createData[mapping.Resource]
				if !ok {
					t.Fatalf("no test data for %s.  Please add a test for your new type to etcd.GetEtcdStorageData().", mapping.Resource)
				}
				newObj := unstructured.Unstructured{}
				if err := json.Unmarshal([]byte(newResource.Stub), &newObj.Object); err != nil {
					t.Fatal(err)
				}

				namespace := testNamespace
				if mapping.Scope == meta.RESTScopeRoot {
					namespace = ""
				}
				name := newObj.GetName()

				// etcd test stub data doesn't contain apiVersion/kind (!), but apply requires it
				newObj.SetGroupVersionKind(mapping.GroupVersionKind)
				createData, err := json.Marshal(newObj.Object)
				if err != nil {
					t.Fatal(err)
				}

				rsc := dynamicClient.Resource(mapping.Resource).Namespace(namespace)
				// apply to create
				_, err = rsc.Patch(context.TODO(), name, types.ApplyPatchType, []byte(createData), metav1.PatchOptions{FieldManager: "create_test"})
				if err != nil {
					t.Fatal(err)
				}

				statusObj := unstructured.Unstructured{}
				if err := json.Unmarshal([]byte(status), &statusObj.Object); err != nil {
					t.Fatal(err)
				}
				statusObj.SetAPIVersion(mapping.GroupVersionKind.GroupVersion().String())
				statusObj.SetKind(mapping.GroupVersionKind.Kind)
				statusObj.SetName(name)
				statusYAML, err := yaml.Marshal(statusObj.Object)
				if err != nil {
					t.Fatal(err)
				}

				True := true
				obj, err := dynamicClient.
					Resource(mapping.Resource).
					Namespace(namespace).
					Patch(context.TODO(), name, types.ApplyPatchType, statusYAML, metav1.PatchOptions{FieldManager: "apply_status_test", Force: &True}, "status")
				if err != nil {
					t.Fatalf("Failed to apply: %v", err)
				}

				accessor, err := meta.Accessor(obj)
				if err != nil {
					t.Fatalf("Failed to get meta accessor: %v:\n%v", err, obj)
				}

				managedFields := accessor.GetManagedFields()
				if managedFields == nil {
					t.Fatal("Empty managed fields")
				}
				if !findManager(managedFields, "apply_status_test") {
					t.Fatalf("Couldn't find apply_status_test: %v", managedFields)
				}
				if !findManager(managedFields, "create_test") {
					t.Fatalf("Couldn't find create_test: %v", managedFields)
				}

				if err := rsc.Delete(context.TODO(), name, *metav1.NewDeleteOptions(0)); err != nil {
					t.Fatalf("deleting final object failed: %v", err)
				}
			})
		}
	}
}

func findManager(managedFields []metav1.ManagedFieldsEntry, manager string) bool {
	for _, entry := range managedFields {
		if entry.Manager == manager {
			return true
		}
	}
	return false
}
<commit_msg>Drop batch/v2alpha1 leftovers<commit_after>/*
Copyright 2020 The Kubernetes 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.
*/

package apiserver

import (
	"context"
	"encoding/json"
	"strings"
	"testing"

	v1 "k8s.io/api/core/v1"
	apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/types"
	genericfeatures "k8s.io/apiserver/pkg/features"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	featuregatetesting "k8s.io/component-base/featuregate/testing"
	apiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
	"k8s.io/kubernetes/test/integration/etcd"
	"k8s.io/kubernetes/test/integration/framework"
	"sigs.k8s.io/yaml"
)

// namespace used for all tests, do not change this
const testNamespace = "statusnamespace"

var statusData = map[schema.GroupVersionResource]string{
	gvr("", "v1", "persistentvolumes"):                                  `{"status": {"message": "hello"}}`,
	gvr("", "v1", "resourcequotas"):                                     `{"status": {"used": {"cpu": "5M"}}}`,
	gvr("", "v1", "services"):                                           `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("extensions", "v1beta1", "ingresses"):                           `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("networking.k8s.io", "v1beta1", "ingresses"):                    `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("networking.k8s.io", "v1", "ingresses"):                         `{"status": {"loadBalancer": {"ingress": [{"ip": "127.0.0.1"}]}}}`,
	gvr("autoscaling", "v1", "horizontalpodautoscalers"):                `{"status": {"currentReplicas": 5}}`,
	gvr("batch", "v1beta1", "cronjobs"):                                 `{"status": {"lastScheduleTime": null}}`,
	gvr("storage.k8s.io", "v1", "volumeattachments"):                    `{"status": {"attached": true}}`,
	gvr("policy", "v1beta1", "poddisruptionbudgets"):                    `{"status": {"currentHealthy": 5}}`,
	gvr("certificates.k8s.io", "v1beta1", "certificatesigningrequests"): `{"status": {"conditions": [{"type": "MyStatus"}]}}`,
	gvr("certificates.k8s.io", "v1", "certificatesigningrequests"):      `{"status": {"conditions": [{"type": "MyStatus", "status": "True"}]}}`,
	gvr("internal.apiserver.k8s.io", "v1alpha1", "storageversions"):     `{"status": {"commonEncodingVersion":"v1","storageVersions":[{"apiServerID":"1","decodableVersions":["v1","v2"],"encodingVersion":"v1"}],"conditions":[{"type":"AllEncodingVersionsEqual","status":"True","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"allEncodingVersionsEqual","message":"all encoding versions are set to v1"}]}}`,
}

const statusDefault = `{"status": {"conditions": [{"type": "MyStatus", "status":"True"}]}}`

func gvr(g, v, r string) schema.GroupVersionResource {
	return schema.GroupVersionResource{Group: g, Version: v, Resource: r}
}

func createMapping(groupVersion string, resource metav1.APIResource) (*meta.RESTMapping, error) {
	gv, err := schema.ParseGroupVersion(groupVersion)
	if err != nil {
		return nil, err
	}
	if len(resource.Group) > 0 || len(resource.Version) > 0 {
		gv = schema.GroupVersion{
			Group:   resource.Group,
			Version: resource.Version,
		}
	}
	gvk := gv.WithKind(resource.Kind)
	gvr := gv.WithResource(strings.TrimSuffix(resource.Name, "/status"))
	scope := meta.RESTScopeRoot
	if resource.Namespaced {
		scope = meta.RESTScopeNamespace
	}
	return &meta.RESTMapping{
		Resource:         gvr,
		GroupVersionKind: gvk,
		Scope:            scope,
	}, nil
}

// TestApplyStatus makes sure that applying the status works for all known types.
func TestApplyStatus(t *testing.T) {
	defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.ServerSideApply, true)()
	server, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), []string{"--disable-admission-plugins", "ServiceAccount,TaintNodesByCondition"}, framework.SharedEtcd())
	if err != nil {
		t.Fatal(err)
	}
	defer server.TearDownFn()

	client, err := kubernetes.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatal(err)
	}
	dynamicClient, err := dynamic.NewForConfig(server.ClientConfig)
	if err != nil {
		t.Fatal(err)
	}

	// create CRDs so we can make sure that custom resources do not get lost
	etcd.CreateTestCRDs(t, apiextensionsclientset.NewForConfigOrDie(server.ClientConfig), false, etcd.GetCustomResourceDefinitionData()...)
	if _, err := client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}, metav1.CreateOptions{}); err != nil {
		t.Fatal(err)
	}

	createData := etcd.GetEtcdStorageData()

	// gather resources to test
	_, resourceLists, err := client.Discovery().ServerGroupsAndResources()
	if err != nil {
		t.Fatalf("Failed to get ServerGroupsAndResources with error: %+v", err)
	}

	for _, resourceList := range resourceLists {
		for _, resource := range resourceList.APIResources {
			if !strings.HasSuffix(resource.Name, "/status") {
				continue
			}
			mapping, err := createMapping(resourceList.GroupVersion, resource)
			if err != nil {
				t.Fatal(err)
			}
			t.Run(mapping.Resource.String(), func(t *testing.T) {
				status, ok := statusData[mapping.Resource]
				if !ok {
					status = statusDefault
				}
				newResource, ok := createData[mapping.Resource]
				if !ok {
					t.Fatalf("no test data for %s.  Please add a test for your new type to etcd.GetEtcdStorageData().", mapping.Resource)
				}
				newObj := unstructured.Unstructured{}
				if err := json.Unmarshal([]byte(newResource.Stub), &newObj.Object); err != nil {
					t.Fatal(err)
				}

				namespace := testNamespace
				if mapping.Scope == meta.RESTScopeRoot {
					namespace = ""
				}
				name := newObj.GetName()

				// etcd test stub data doesn't contain apiVersion/kind (!), but apply requires it
				newObj.SetGroupVersionKind(mapping.GroupVersionKind)
				createData, err := json.Marshal(newObj.Object)
				if err != nil {
					t.Fatal(err)
				}

				rsc := dynamicClient.Resource(mapping.Resource).Namespace(namespace)
				// apply to create
				_, err = rsc.Patch(context.TODO(), name, types.ApplyPatchType, []byte(createData), metav1.PatchOptions{FieldManager: "create_test"})
				if err != nil {
					t.Fatal(err)
				}

				statusObj := unstructured.Unstructured{}
				if err := json.Unmarshal([]byte(status), &statusObj.Object); err != nil {
					t.Fatal(err)
				}
				statusObj.SetAPIVersion(mapping.GroupVersionKind.GroupVersion().String())
				statusObj.SetKind(mapping.GroupVersionKind.Kind)
				statusObj.SetName(name)
				statusYAML, err := yaml.Marshal(statusObj.Object)
				if err != nil {
					t.Fatal(err)
				}

				True := true
				obj, err := dynamicClient.
					Resource(mapping.Resource).
					Namespace(namespace).
					Patch(context.TODO(), name, types.ApplyPatchType, statusYAML, metav1.PatchOptions{FieldManager: "apply_status_test", Force: &True}, "status")
				if err != nil {
					t.Fatalf("Failed to apply: %v", err)
				}

				accessor, err := meta.Accessor(obj)
				if err != nil {
					t.Fatalf("Failed to get meta accessor: %v:\n%v", err, obj)
				}

				managedFields := accessor.GetManagedFields()
				if managedFields == nil {
					t.Fatal("Empty managed fields")
				}
				if !findManager(managedFields, "apply_status_test") {
					t.Fatalf("Couldn't find apply_status_test: %v", managedFields)
				}
				if !findManager(managedFields, "create_test") {
					t.Fatalf("Couldn't find create_test: %v", managedFields)
				}

				if err := rsc.Delete(context.TODO(), name, *metav1.NewDeleteOptions(0)); err != nil {
					t.Fatalf("deleting final object failed: %v", err)
				}
			})
		}
	}
}

func findManager(managedFields []metav1.ManagedFieldsEntry, manager string) bool {
	for _, entry := range managedFields {
		if entry.Manager == manager {
			return true
		}
	}
	return false
}
<|endoftext|>


<commit_before>package sweet

import (
	"io"
	"reflect"
	"runtime/pprof"
	"testing"
)

// Since testing.MainStart can change between versions this file exists to abstract
// that part away so we can support multiple versions at once.

func mainStart(s *S) (*testing.M, error) {
	tests := make([]testing.InternalTest, 0)
	tests = append(tests, testing.InternalTest{
		Name: "Tests",
		F: func(t *testing.T) {
			for _, suite := range s.addedSuites {
				runner := newSuiteRunner(s, suite)
				runner.Run(t)
			}
		},
	})
	benchmarks := make([]testing.InternalBenchmark, 0)
	examples := make([]testing.InternalExample, 0)

	fParams := make([]reflect.Value, 0)
	switch {
	case isV1_8MainStart():
		fParams = append(fParams, reflect.ValueOf(testDeps{}))
		fParams = append(fParams, reflect.ValueOf(tests))
		fParams = append(fParams, reflect.ValueOf(benchmarks))
		fParams = append(fParams, reflect.ValueOf(examples))
	case isV1_7MainStart():
		fParams = append(fParams, reflect.ValueOf(func(pat, str string) (bool, error) {
			return false, nil
		}))
		fParams = append(fParams, reflect.ValueOf(tests))
		fParams = append(fParams, reflect.ValueOf(benchmarks))
		fParams = append(fParams, reflect.ValueOf(examples))
	default:
		return nil, errUnsupportedVersion
	}

	fVal := reflect.ValueOf(testing.MainStart)
	res := fVal.Call(fParams)

	if len(res) != 1 {
		return nil, errUnknownResponse
	}

	mIface := res[0]
	if mIface.Kind() != reflect.Ptr {
		return nil, errUnknownResponse
	}

	mVal, ok := mIface.Interface().(*testing.M)
	if !ok {
		return nil, errUnknownResponse
	}

	return mVal, nil
}

// These functions check the testing.MainStart signatures to see which one matches up.  We only go back
// to 1.7 because that's when the subtest functionality that sweet relies on was added. Maybe that's when
// MainStart was added too? I dunno, who cares?

func isV1_7MainStart() bool {
	fType := reflect.TypeOf(testing.MainStart)
	if fType.NumIn() != 4 {
		return false
	}

	// First param is func(string, string) (bool, error)
	param := fType.In(0)
	if param.Kind() != reflect.Func {
		return false
	}
	if param.NumIn() != 2 || param.NumOut() != 2 {
		return false
	}
	if param.In(0).Kind() != reflect.String || param.In(1).Kind() != reflect.String {
		return false
	}
	if param.Out(0).Kind() != reflect.Bool ||
		(param.Out(1).Kind() != reflect.Interface && param.Out(1).Name() != "error") {
		return false
	}

	// Second param is []InternalTest
	param = fType.In(1)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalTest" {
		return false
	}

	// Third param is []InternalBenchmark
	param = fType.In(2)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalBenchmark" {
		return false
	}

	// Fourth param is []InternalExample
	param = fType.In(3)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalExample" {
		return false
	}

	return true
}

func isV1_8MainStart() bool {
	fType := reflect.TypeOf(testing.MainStart)
	if fType.NumIn() != 4 {
		return false
	}

	// First param is an internal interface
	param := fType.In(0)
	if param.Name() != "testDeps" || param.Kind() != reflect.Interface {
		return false
	}

	// Second param is []InternalTest
	param = fType.In(1)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalTest" {
		return false
	}

	// Third param is []InternalBenchmark
	param = fType.In(2)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalBenchmark" {
		return false
	}

	// Fourth param is []InternalExample
	param = fType.In(3)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalExample" {
		return false
	}

	return true
}

// testDeps is an implementation of the testDeps interface required by some
// versions of testing.MainStart
type testDeps struct{}

func (testDeps) MatchString(pat, str string) (bool, error) {
	return false, nil
}

func (testDeps) StartCPUProfile(w io.Writer) error {
	return pprof.StartCPUProfile(w)
}

func (testDeps) StopCPUProfile() {
	pprof.StopCPUProfile()
}

func (testDeps) WriteHeapProfile(w io.Writer) error {
	return pprof.WriteHeapProfile(w)
}

func (testDeps) WriteProfileTo(name string, w io.Writer, debug int) error {
	return pprof.Lookup(name).WriteTo(w, debug)
}
<commit_msg>Add method to testDeps required by Go tip<commit_after>package sweet

import (
	"io"
	"reflect"
	"runtime/pprof"
	"testing"
)

// Since testing.MainStart can change between versions this file exists to abstract
// that part away so we can support multiple versions at once.

func mainStart(s *S) (*testing.M, error) {
	tests := make([]testing.InternalTest, 0)
	tests = append(tests, testing.InternalTest{
		Name: "Tests",
		F: func(t *testing.T) {
			for _, suite := range s.addedSuites {
				runner := newSuiteRunner(s, suite)
				runner.Run(t)
			}
		},
	})
	benchmarks := make([]testing.InternalBenchmark, 0)
	examples := make([]testing.InternalExample, 0)

	fParams := make([]reflect.Value, 0)
	switch {
	case isV1_8MainStart():
		fParams = append(fParams, reflect.ValueOf(testDeps{}))
		fParams = append(fParams, reflect.ValueOf(tests))
		fParams = append(fParams, reflect.ValueOf(benchmarks))
		fParams = append(fParams, reflect.ValueOf(examples))
	case isV1_7MainStart():
		fParams = append(fParams, reflect.ValueOf(func(pat, str string) (bool, error) {
			return false, nil
		}))
		fParams = append(fParams, reflect.ValueOf(tests))
		fParams = append(fParams, reflect.ValueOf(benchmarks))
		fParams = append(fParams, reflect.ValueOf(examples))
	default:
		return nil, errUnsupportedVersion
	}

	fVal := reflect.ValueOf(testing.MainStart)
	res := fVal.Call(fParams)

	if len(res) != 1 {
		return nil, errUnknownResponse
	}

	mIface := res[0]
	if mIface.Kind() != reflect.Ptr {
		return nil, errUnknownResponse
	}

	mVal, ok := mIface.Interface().(*testing.M)
	if !ok {
		return nil, errUnknownResponse
	}

	return mVal, nil
}

// These functions check the testing.MainStart signatures to see which one matches up.  We only go back
// to 1.7 because that's when the subtest functionality that sweet relies on was added. Maybe that's when
// MainStart was added too? I dunno, who cares?

func isV1_7MainStart() bool {
	fType := reflect.TypeOf(testing.MainStart)
	if fType.NumIn() != 4 {
		return false
	}

	// First param is func(string, string) (bool, error)
	param := fType.In(0)
	if param.Kind() != reflect.Func {
		return false
	}
	if param.NumIn() != 2 || param.NumOut() != 2 {
		return false
	}
	if param.In(0).Kind() != reflect.String || param.In(1).Kind() != reflect.String {
		return false
	}
	if param.Out(0).Kind() != reflect.Bool ||
		(param.Out(1).Kind() != reflect.Interface && param.Out(1).Name() != "error") {
		return false
	}

	// Second param is []InternalTest
	param = fType.In(1)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalTest" {
		return false
	}

	// Third param is []InternalBenchmark
	param = fType.In(2)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalBenchmark" {
		return false
	}

	// Fourth param is []InternalExample
	param = fType.In(3)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalExample" {
		return false
	}

	return true
}

func isV1_8MainStart() bool {
	fType := reflect.TypeOf(testing.MainStart)
	if fType.NumIn() != 4 {
		return false
	}

	// First param is an internal interface
	param := fType.In(0)
	if param.Name() != "testDeps" || param.Kind() != reflect.Interface {
		return false
	}

	// Second param is []InternalTest
	param = fType.In(1)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalTest" {
		return false
	}

	// Third param is []InternalBenchmark
	param = fType.In(2)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalBenchmark" {
		return false
	}

	// Fourth param is []InternalExample
	param = fType.In(3)
	if param.Kind() != reflect.Slice || param.Elem().Name() != "InternalExample" {
		return false
	}

	return true
}

// testDeps is an implementation of the testDeps interface required by some
// versions of testing.MainStart
type testDeps struct{}

func (testDeps) MatchString(pat, str string) (bool, error) {
	return false, nil
}

func (testDeps) StartCPUProfile(w io.Writer) error {
	return pprof.StartCPUProfile(w)
}

func (testDeps) StopCPUProfile() {
	pprof.StopCPUProfile()
}

func (testDeps) WriteHeapProfile(w io.Writer) error {
	return pprof.WriteHeapProfile(w)
}

func (testDeps) WriteProfileTo(name string, w io.Writer, debug int) error {
	return pprof.Lookup(name).WriteTo(w, debug)
}

func (testDeps) ImportPath() string {
	return ""
}
<|endoftext|>


<commit_before>package engine

import (
	"testing"
)

func TestSetPrimaryPictureSource(t *testing.T) {
	tc := SetupEngineTest(t, "user config")
	defer tc.Cleanup()
	CreateAndSignupFakeUser(tc, "cfg")

	// TODO Setup pictures with multiple sources

	ctx := &Context{
		LogUI: tc.G.UI.GetLogUI(),
	}

	eng := NewUserConfigEngine(&UserConfigEngineArg{
		Key:   "picture.source",
		Value: "github",
	}, tc.G)
	err := RunEngine(eng, ctx)
	if err == nil {
		t.Fatal(err)
	}

	// TODO Check that the primary picture source was changed
}
<commit_msg>fixed test<commit_after>package engine

import (
	"testing"
)

func TestSetPrimaryPictureSource(t *testing.T) {
	tc := SetupEngineTest(t, "user config")
	defer tc.Cleanup()
	CreateAndSignupFakeUser(tc, "cfg")

	// TODO Setup pictures with multiple sources

	ctx := &Context{
		LogUI: tc.G.UI.GetLogUI(),
	}

	eng := NewUserConfigEngine(&UserConfigEngineArg{
		Key:   "picture.source",
		Value: "github",
	}, tc.G)
	err := RunEngine(eng, ctx)
	if err != nil {
		t.Fatal(err)
	}

	// TODO Check that the primary picture source was changed
}
<|endoftext|>


<commit_before>// Package opentsdb adds support for pushing stats to opentsdb.
package opentsdb

import (
	"bytes"
	"encoding/json"
	"expvar"
	"flag"
	"net/http"
	"sort"
	"strings"
	"time"
	"unicode"

	"vitess.io/vitess/go/stats"
	"vitess.io/vitess/go/vt/servenv"
)

var (
	openTsdbURI = flag.String("opentsdb_uri", "", "URI of opentsdb /api/put method")
)

// dataPoint represents a single OpenTSDB data point.
type dataPoint struct {
	// Example: sys.cpu.nice
	Metric string `json:"metric"`
	// Seconds or milliseconds since unix epoch.
	Timestamp float64           `json:"timestamp"`
	Value     float64           `json:"value"`
	Tags      map[string]string `json:"tags"`
}

// sendDataPoints pushes a list of data points to openTSDB.
// All other code in this file is just to support getting this function called
// with all stats represented as data points.
func sendDataPoints(data []dataPoint) error {
	json, err := json.Marshal(data)
	if err != nil {
		return err
	}

	resp, err := http.Post(*openTsdbURI, "application/json", bytes.NewReader(json))
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}

// openTSDBBackend implements stats.PushBackend
type openTSDBBackend struct {
	// The prefix is the name of the binary (vtgate, vttablet, etc.) and will be
	// prepended to all the stats reported.
	prefix string
	// Tags that should be included with every data point. If there's a tag name
	// collision between the common tags and a single data point's tags, the data
	// point tag will override the common tag.
	commonTags map[string]string
}

// dataCollector tracks state for a single pass of stats reporting / data collection.
type dataCollector struct {
	settings   *openTSDBBackend
	timestamp  int64
	dataPoints []dataPoint
}

// Init attempts to create a singleton openTSDBBackend and register it as a PushBackend.
// If it fails to create one, this is a noop. The prefix argument is an optional string
// to prepend to the name of every data point reported.
func Init(prefix string) {
	// Needs to happen in servenv.OnRun() instead of init because it requires flag parsing and logging
	servenv.OnRun(func() {
		if *openTsdbURI == "" {
			return
		}

		backend := &openTSDBBackend{
			prefix: prefix,
			// If you want to global service values like host, service name, git revision, etc,
			// this is the place to do it.
			commonTags: map[string]string{},
		}

		stats.RegisterPushBackend("opentsdb", backend)

		http.HandleFunc("/debug/opentsdb", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			dataPoints := (*backend).getDataPoints()
			sort.Sort(byMetric(dataPoints))

			if b, err := json.MarshalIndent(dataPoints, "", "  "); err != nil {
				w.Write([]byte(err.Error()))
			} else {
				w.Write(b)
			}
		})
	})
}

// PushAll pushes all stats to OpenTSDB
func (backend *openTSDBBackend) PushAll() error {
	return sendDataPoints(backend.getDataPoints())
}

// getDataPoints fetches all stats in an opentsdb-compatible format.
// This is separated from PushAll() so it can be reused for the /debug/opentsdb handler.
func (backend *openTSDBBackend) getDataPoints() []dataPoint {
	dataCollector := &dataCollector{
		settings:  backend,
		timestamp: time.Now().Unix(),
	}

	expvar.Do(func(kv expvar.KeyValue) {
		dataCollector.addExpVar(kv)
	})

	return dataCollector.dataPoints
}

// combineMetricName joins parts of a hierachical name with a "."
func combineMetricName(parts ...string) string {
	return strings.Join(parts, ".")
}

func (dc *dataCollector) addInt(metric string, val int64, tags map[string]string) {
	dc.addFloat(metric, float64(val), tags)
}

func (dc *dataCollector) addFloat(metric string, val float64, tags map[string]string) {
	var fullMetric string
	if len(dc.settings.prefix) > 0 {
		fullMetric = combineMetricName(dc.settings.prefix, metric)
	} else {
		fullMetric = metric
	}

	// Restrict metric and tag name/values to legal characters:
	// http://opentsdb.net/docs/build/html/user_guide/writing.html#metrics-and-tags
	//
	// Also make everything lowercase, since opentsdb is case sensitive and lowercase
	// simplifies the convention.
	sanitize := func(text string) string {
		var b bytes.Buffer
		for _, r := range text {
			if unicode.IsDigit(r) || unicode.IsLetter(r) || r == '-' || r == '_' || r == '/' || r == '.' {
				b.WriteRune(r)
			} else {
				// For characters that would cause errors, write underscore instead
				b.WriteRune('_')
			}
		}
		return strings.ToLower(b.String())
	}

	fullTags := make(map[string]string)
	for k, v := range dc.settings.commonTags {
		fullTags[sanitize(k)] = sanitize(v)
	}
	for k, v := range tags {
		fullTags[sanitize(k)] = sanitize(v)
	}

	dp := dataPoint{
		Metric:    sanitize(fullMetric),
		Value:     val,
		Timestamp: float64(dc.timestamp),
		Tags:      fullTags,
	}
	dc.dataPoints = append(dc.dataPoints, dp)
}

// addExpVar adds all the data points associated with a particular expvar to the list of
// opentsdb data points. How an expvar is translated depends on its type.
//
// Well-known metric types like histograms and integers are directly converted (saving labels
// as tags).
//
// Generic unrecognized expvars are serialized to json and their int/float values are exported.
// Strings and lists in expvars are not exported.
func (dc *dataCollector) addExpVar(kv expvar.KeyValue) {
	k := kv.Key
	switch v := kv.Value.(type) {
	case stats.FloatFunc:
		dc.addFloat(k, v(), nil)
	case *stats.Counter:
		dc.addInt(k, v.Get(), nil)
	case *stats.CounterFunc:
		dc.addInt(k, v.F(), nil)
	case *stats.Gauge:
		dc.addInt(k, v.Get(), nil)
	case *stats.GaugeFunc:
		dc.addInt(k, v.F(), nil)
	case *stats.CounterDuration:
		dc.addInt(k, int64(v.Get()), nil)
	case *stats.CounterDurationFunc:
		dc.addInt(k, int64(v.F()), nil)
	case *stats.MultiTimings:
		dc.addTimings(v.Labels(), &v.Timings, k)
	case *stats.Timings:
		dc.addTimings([]string{"Histograms"}, v, k)
	case *stats.Histogram:
		dc.addHistogram(v, 1, k, make(map[string]string))
	case *stats.CountersWithSingleLabel:
		for labelVal, val := range v.Counts() {
			dc.addInt(k, val, makeLabel(v.Label(), labelVal))
		}
	case *stats.CountersWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.CountersFuncWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.GaugesWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.GaugesFuncWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.GaugesWithSingleLabel:
		for labelVal, val := range v.Counts() {
			dc.addInt(k, val, makeLabel(v.Label(), labelVal))
		}
	default:
		// Deal with generic expvars by converting them to JSON and pulling out
		// all the floats. Strings and lists will not be exported to opentsdb.
		var obj map[string]interface{}
		if err := json.Unmarshal([]byte(v.String()), &obj); err != nil {
			return
		}

		// Recursive helper function.
		dc.addUnrecognizedExpvars(combineMetricName("expvar", k), obj)
	}
}

// makeLabel builds a tag list with a single label + value.
func makeLabel(labelName string, labelVal string) map[string]string {
	return map[string]string{labelName: labelVal}
}

// makeLabels takes the vitess stat representation of label values ("."-separated list) and breaks it
// apart into a map of label name -> label value.
func makeLabels(labelNames []string, labelValsCombined string) map[string]string {
	tags := make(map[string]string)
	labelVals := strings.Split(labelValsCombined, ".")
	for i, v := range labelVals {
		tags[labelNames[i]] = v
	}
	return tags
}

// addUnrecognizedExpvars recurses into a json object to pull out float64 variables to report.
func (dc *dataCollector) addUnrecognizedExpvars(prefix string, obj map[string]interface{}) {
	for k, v := range obj {
		prefix := combineMetricName(prefix, k)
		switch v := v.(type) {
		case map[string]interface{}:
			dc.addUnrecognizedExpvars(prefix, v)
		case float64:
			dc.addFloat(prefix, v, nil)
		}
	}
}

// addTimings converts a vitess Timings stat to something opentsdb can deal with.
func (dc *dataCollector) addTimings(labels []string, timings *stats.Timings, prefix string) {
	histograms := timings.Histograms()
	for labelValsCombined, histogram := range histograms {
		// If you prefer millisecond timings over nanoseconds you can pass 1000000 here instead of 1.
		dc.addHistogram(histogram, 1, prefix, makeLabels(labels, labelValsCombined))
	}
}

func (dc *dataCollector) addHistogram(histogram *stats.Histogram, divideBy int64, prefix string, tags map[string]string) {
	// TODO: OpenTSDB 2.3 doesn't have histogram support, although it's forthcoming.
	// For simplicity we report each bucket as a different metric.
	//
	// An alternative approach if you don't mind changing the code is to add a hook to Histogram creation that
	// associates each histogram with a shadow type that can track percentiles (like Timer from rcrowley/go-metrics).

	labels := histogram.Labels()
	buckets := histogram.Buckets()
	for i := range labels {
		dc.addInt(
			combineMetricName(prefix, labels[i]),
			buckets[i],
			tags,
		)
	}

	dc.addInt(
		combineMetricName(prefix, histogram.CountLabel()),
		(*histogram).Count(),
		tags,
	)
	dc.addInt(
		combineMetricName(prefix, histogram.TotalLabel()),
		(*histogram).Total()/divideBy,
		tags,
	)
}

// byMetric implements sort.Interface for []dataPoint based on the metric key
// and then tag values (prioritized in tag name order). Having a consistent sort order
// is convenient when refreshing /debug/opentsdb or for encoding and comparing JSON directly
// in the tests.
type byMetric []dataPoint

func (m byMetric) Len() int      { return len(m) }
func (m byMetric) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m byMetric) Less(i, j int) bool {
	if m[i].Metric < m[j].Metric {
		return true
	}

	if m[i].Metric > m[j].Metric {
		return false
	}

	// Metric names are the same. We can use tag values to figure out the sort order.
	// The deciding tag will be the lexicographically earliest tag name where tag values differ.
	decidingTagName := ""
	result := false
	for tagName, iVal := range m[i].Tags {
		jVal, ok := m[j].Tags[tagName]
		if !ok {
			// We'll arbitrarily declare that if i has any tag name that j doesn't then it sorts earlier.
			// This shouldn't happen in practice, though, if metric code is correct...
			return true
		}

		if iVal != jVal && (tagName < decidingTagName || decidingTagName == "") {
			decidingTagName = tagName
			result = iVal < jVal
		}
	}
	return result
}
<commit_msg>fix wrong spells in opentsdb.go<commit_after>// Package opentsdb adds support for pushing stats to opentsdb.
package opentsdb

import (
	"bytes"
	"encoding/json"
	"expvar"
	"flag"
	"net/http"
	"sort"
	"strings"
	"time"
	"unicode"

	"vitess.io/vitess/go/stats"
	"vitess.io/vitess/go/vt/servenv"
)

var (
	openTsdbURI = flag.String("opentsdb_uri", "", "URI of opentsdb /api/put method")
)

// dataPoint represents a single OpenTSDB data point.
type dataPoint struct {
	// Example: sys.cpu.nice
	Metric string `json:"metric"`
	// Seconds or milliseconds since unix epoch.
	Timestamp float64           `json:"timestamp"`
	Value     float64           `json:"value"`
	Tags      map[string]string `json:"tags"`
}

// sendDataPoints pushes a list of data points to openTSDB.
// All other code in this file is just to support getting this function called
// with all stats represented as data points.
func sendDataPoints(data []dataPoint) error {
	json, err := json.Marshal(data)
	if err != nil {
		return err
	}

	resp, err := http.Post(*openTsdbURI, "application/json", bytes.NewReader(json))
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}

// openTSDBBackend implements stats.PushBackend
type openTSDBBackend struct {
	// The prefix is the name of the binary (vtgate, vttablet, etc.) and will be
	// prepended to all the stats reported.
	prefix string
	// Tags that should be included with every data point. If there's a tag name
	// collision between the common tags and a single data point's tags, the data
	// point tag will override the common tag.
	commonTags map[string]string
}

// dataCollector tracks state for a single pass of stats reporting / data collection.
type dataCollector struct {
	settings   *openTSDBBackend
	timestamp  int64
	dataPoints []dataPoint
}

// Init attempts to create a singleton openTSDBBackend and register it as a PushBackend.
// If it fails to create one, this is a noop. The prefix argument is an optional string
// to prepend to the name of every data point reported.
func Init(prefix string) {
	// Needs to happen in servenv.OnRun() instead of init because it requires flag parsing and logging
	servenv.OnRun(func() {
		if *openTsdbURI == "" {
			return
		}

		backend := &openTSDBBackend{
			prefix: prefix,
			// If you want to global service values like host, service name, git revision, etc,
			// this is the place to do it.
			commonTags: map[string]string{},
		}

		stats.RegisterPushBackend("opentsdb", backend)

		http.HandleFunc("/debug/opentsdb", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			dataPoints := (*backend).getDataPoints()
			sort.Sort(byMetric(dataPoints))

			if b, err := json.MarshalIndent(dataPoints, "", "  "); err != nil {
				w.Write([]byte(err.Error()))
			} else {
				w.Write(b)
			}
		})
	})
}

// PushAll pushes all stats to OpenTSDB
func (backend *openTSDBBackend) PushAll() error {
	return sendDataPoints(backend.getDataPoints())
}

// getDataPoints fetches all stats in an opentsdb-compatible format.
// This is separated from PushAll() so it can be reused for the /debug/opentsdb handler.
func (backend *openTSDBBackend) getDataPoints() []dataPoint {
	dataCollector := &dataCollector{
		settings:  backend,
		timestamp: time.Now().Unix(),
	}

	expvar.Do(func(kv expvar.KeyValue) {
		dataCollector.addExpVar(kv)
	})

	return dataCollector.dataPoints
}

// combineMetricName joins parts of a hierarchical name with a "."
func combineMetricName(parts ...string) string {
	return strings.Join(parts, ".")
}

func (dc *dataCollector) addInt(metric string, val int64, tags map[string]string) {
	dc.addFloat(metric, float64(val), tags)
}

func (dc *dataCollector) addFloat(metric string, val float64, tags map[string]string) {
	var fullMetric string
	if len(dc.settings.prefix) > 0 {
		fullMetric = combineMetricName(dc.settings.prefix, metric)
	} else {
		fullMetric = metric
	}

	// Restrict metric and tag name/values to legal characters:
	// http://opentsdb.net/docs/build/html/user_guide/writing.html#metrics-and-tags
	//
	// Also make everything lowercase, since opentsdb is case sensitive and lowercase
	// simplifies the convention.
	sanitize := func(text string) string {
		var b bytes.Buffer
		for _, r := range text {
			if unicode.IsDigit(r) || unicode.IsLetter(r) || r == '-' || r == '_' || r == '/' || r == '.' {
				b.WriteRune(r)
			} else {
				// For characters that would cause errors, write underscore instead
				b.WriteRune('_')
			}
		}
		return strings.ToLower(b.String())
	}

	fullTags := make(map[string]string)
	for k, v := range dc.settings.commonTags {
		fullTags[sanitize(k)] = sanitize(v)
	}
	for k, v := range tags {
		fullTags[sanitize(k)] = sanitize(v)
	}

	dp := dataPoint{
		Metric:    sanitize(fullMetric),
		Value:     val,
		Timestamp: float64(dc.timestamp),
		Tags:      fullTags,
	}
	dc.dataPoints = append(dc.dataPoints, dp)
}

// addExpVar adds all the data points associated with a particular expvar to the list of
// opentsdb data points. How an expvar is translated depends on its type.
//
// Well-known metric types like histograms and integers are directly converted (saving labels
// as tags).
//
// Generic unrecognized expvars are serialized to json and their int/float values are exported.
// Strings and lists in expvars are not exported.
func (dc *dataCollector) addExpVar(kv expvar.KeyValue) {
	k := kv.Key
	switch v := kv.Value.(type) {
	case stats.FloatFunc:
		dc.addFloat(k, v(), nil)
	case *stats.Counter:
		dc.addInt(k, v.Get(), nil)
	case *stats.CounterFunc:
		dc.addInt(k, v.F(), nil)
	case *stats.Gauge:
		dc.addInt(k, v.Get(), nil)
	case *stats.GaugeFunc:
		dc.addInt(k, v.F(), nil)
	case *stats.CounterDuration:
		dc.addInt(k, int64(v.Get()), nil)
	case *stats.CounterDurationFunc:
		dc.addInt(k, int64(v.F()), nil)
	case *stats.MultiTimings:
		dc.addTimings(v.Labels(), &v.Timings, k)
	case *stats.Timings:
		dc.addTimings([]string{"Histograms"}, v, k)
	case *stats.Histogram:
		dc.addHistogram(v, 1, k, make(map[string]string))
	case *stats.CountersWithSingleLabel:
		for labelVal, val := range v.Counts() {
			dc.addInt(k, val, makeLabel(v.Label(), labelVal))
		}
	case *stats.CountersWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.CountersFuncWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.GaugesWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.GaugesFuncWithMultiLabels:
		for labelVals, val := range v.Counts() {
			dc.addInt(k, val, makeLabels(v.Labels(), labelVals))
		}
	case *stats.GaugesWithSingleLabel:
		for labelVal, val := range v.Counts() {
			dc.addInt(k, val, makeLabel(v.Label(), labelVal))
		}
	default:
		// Deal with generic expvars by converting them to JSON and pulling out
		// all the floats. Strings and lists will not be exported to opentsdb.
		var obj map[string]interface{}
		if err := json.Unmarshal([]byte(v.String()), &obj); err != nil {
			return
		}

		// Recursive helper function.
		dc.addUnrecognizedExpvars(combineMetricName("expvar", k), obj)
	}
}

// makeLabel builds a tag list with a single label + value.
func makeLabel(labelName string, labelVal string) map[string]string {
	return map[string]string{labelName: labelVal}
}

// makeLabels takes the vitess stat representation of label values ("."-separated list) and breaks it
// apart into a map of label name -> label value.
func makeLabels(labelNames []string, labelValsCombined string) map[string]string {
	tags := make(map[string]string)
	labelVals := strings.Split(labelValsCombined, ".")
	for i, v := range labelVals {
		tags[labelNames[i]] = v
	}
	return tags
}

// addUnrecognizedExpvars recurses into a json object to pull out float64 variables to report.
func (dc *dataCollector) addUnrecognizedExpvars(prefix string, obj map[string]interface{}) {
	for k, v := range obj {
		prefix := combineMetricName(prefix, k)
		switch v := v.(type) {
		case map[string]interface{}:
			dc.addUnrecognizedExpvars(prefix, v)
		case float64:
			dc.addFloat(prefix, v, nil)
		}
	}
}

// addTimings converts a vitess Timings stat to something opentsdb can deal with.
func (dc *dataCollector) addTimings(labels []string, timings *stats.Timings, prefix string) {
	histograms := timings.Histograms()
	for labelValsCombined, histogram := range histograms {
		// If you prefer millisecond timings over nanoseconds you can pass 1000000 here instead of 1.
		dc.addHistogram(histogram, 1, prefix, makeLabels(labels, labelValsCombined))
	}
}

func (dc *dataCollector) addHistogram(histogram *stats.Histogram, divideBy int64, prefix string, tags map[string]string) {
	// TODO: OpenTSDB 2.3 doesn't have histogram support, although it's forthcoming.
	// For simplicity we report each bucket as a different metric.
	//
	// An alternative approach if you don't mind changing the code is to add a hook to Histogram creation that
	// associates each histogram with a shadow type that can track percentiles (like Timer from rcrowley/go-metrics).

	labels := histogram.Labels()
	buckets := histogram.Buckets()
	for i := range labels {
		dc.addInt(
			combineMetricName(prefix, labels[i]),
			buckets[i],
			tags,
		)
	}

	dc.addInt(
		combineMetricName(prefix, histogram.CountLabel()),
		(*histogram).Count(),
		tags,
	)
	dc.addInt(
		combineMetricName(prefix, histogram.TotalLabel()),
		(*histogram).Total()/divideBy,
		tags,
	)
}

// byMetric implements sort.Interface for []dataPoint based on the metric key
// and then tag values (prioritized in tag name order). Having a consistent sort order
// is convenient when refreshing /debug/opentsdb or for encoding and comparing JSON directly
// in the tests.
type byMetric []dataPoint

func (m byMetric) Len() int      { return len(m) }
func (m byMetric) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m byMetric) Less(i, j int) bool {
	if m[i].Metric < m[j].Metric {
		return true
	}

	if m[i].Metric > m[j].Metric {
		return false
	}

	// Metric names are the same. We can use tag values to figure out the sort order.
	// The deciding tag will be the lexicographically earliest tag name where tag values differ.
	decidingTagName := ""
	result := false
	for tagName, iVal := range m[i].Tags {
		jVal, ok := m[j].Tags[tagName]
		if !ok {
			// We'll arbitrarily declare that if i has any tag name that j doesn't then it sorts earlier.
			// This shouldn't happen in practice, though, if metric code is correct...
			return true
		}

		if iVal != jVal && (tagName < decidingTagName || decidingTagName == "") {
			decidingTagName = tagName
			result = iVal < jVal
		}
	}
	return result
}
<|endoftext|>


<commit_before>package util

import (
	"fmt"
	"github.com/skia-dev/glog"
	"os/exec"
	"strings"
)

// DoCmd executes the given command line string; the command being
// run is expected to not care what its current working directory is.
// Returns the stdout and stderr.
func DoCmd(commandLine string) (string, error) {
	glog.Infof("Command: %q\n", commandLine)
	programAndArgs := strings.SplitN(commandLine, " ", 2)
	program := programAndArgs[0]
	args := []string{}
	if len(programAndArgs) > 1 {
		args = strings.Split(programAndArgs[1], " ")
	}
	cmd := exec.Command(program, args...)
	message, err := cmd.CombinedOutput()
	glog.Infof("StdOut + StdErr: %s\n", string(message))
	if err != nil {
		glog.Errorf("Exit status: %s\n", err)
		return string(message), fmt.Errorf("Failed to run command.")
	}
	return string(message), nil
}
<commit_msg>Fix goimports error<commit_after>package util

import (
	"fmt"
	"os/exec"
	"strings"

	"github.com/skia-dev/glog"
)

// DoCmd executes the given command line string; the command being
// run is expected to not care what its current working directory is.
// Returns the stdout and stderr.
func DoCmd(commandLine string) (string, error) {
	glog.Infof("Command: %q\n", commandLine)
	programAndArgs := strings.SplitN(commandLine, " ", 2)
	program := programAndArgs[0]
	args := []string{}
	if len(programAndArgs) > 1 {
		args = strings.Split(programAndArgs[1], " ")
	}
	cmd := exec.Command(program, args...)
	message, err := cmd.CombinedOutput()
	glog.Infof("StdOut + StdErr: %s\n", string(message))
	if err != nil {
		glog.Errorf("Exit status: %s\n", err)
		return string(message), fmt.Errorf("Failed to run command.")
	}
	return string(message), nil
}
<|endoftext|>


<commit_before>package gobject

/*
#ifndef uintptr
#define uintptr unsigned int*
#endif
#include <glib.h>
#include <glib-object.h>
#include <stdlib.h>
#include <stdint.h>

static inline GObject* to_GObject(void* o) { return G_OBJECT(o); }
static inline void* new_GObject(GType typ) { return g_object_new(typ, NULL); }

static inline const gchar* getTypeName(void * o) { return G_OBJECT_TYPE_NAME(o); }

static inline GObjectClass* get_object_class(void* o) {
	return G_OBJECT_GET_CLASS(o);
}

static inline GType _get_type_from_instance(void* o) {
    return G_TYPE_FROM_INSTANCE(o);
}

extern void weak_ref_callback(gpointer data, GObject* object);

static void _g_object_weak_ref(GObject* object) {
	g_object_weak_ref(object, weak_ref_callback, NULL);
}

static void _g_clear_object(void* object) {
	GObject* o = G_OBJECT(object);
	g_clear_object(o);
}

*/
// #cgo pkg-config: gobject-2.0
import "C"
import "unsafe"
import "reflect"
import "time"
import "fmt"

func GetTypeFromInstance(obj unsafe.Pointer) GType {
	return GType(C._get_type_from_instance(obj))
}

// Base interface which all gobject like structures must implement
// to be compatible with all gobject functions - public interfaces of gobject
type ObjectLike interface {
	ToNative() unsafe.Pointer
	Connect(s string, f interface{}, data ...interface{}) (*ClosureElement, *SignalError)
	Set(map[string]interface{})
	Get([]string) map[string]interface{}
}

//-----------------------------------------------------------------------
// GObject interfaces
//-----------------------------------------------------------------------
// Convenient struct - singleton
type gobject struct {
	object unsafe.Pointer
}

func (self gobject) ToNative() unsafe.Pointer {
	return self.object
}

func (self gobject) Connect(name string, f interface{}, data ...interface{}) (*ClosureElement, *SignalError) {
	return Connect(self, name, f, data...)
}

func (self gobject) Set(properties map[string]interface{}) {
	Set(self, properties)
}

func (self gobject) Get(properties []string) map[string]interface{} {
	return Get(self, properties)
}

func New(typ GType, properties map[string]interface{}) ObjectLike {
	obj := gobject{}
	obj.object = C.new_GObject(C.GType(typ))

	Set(obj, properties)

	return obj

}

func FindProperty(obj ObjectLike, propName string) *GParamSpec {
	cpn := GString(propName)
	defer cpn.Free()

	oc := C.get_object_class(obj.ToNative())
	pspec := C.g_object_class_find_property(oc, (*C.gchar)(cpn.GetPtr()))
	if pspec == nil {
		return nil
	}
	gpspec := GParamSpec{pspec}
	return &gpspec
}

func Set(obj ObjectLike, properties map[string]interface{}) {
	if len(properties) == 0 {
		return
	}

	for p, v := range properties {
		SetProperty(obj, p, v)
	}
}

func Get(obj ObjectLike, properties []string) map[string]interface{} {
	m := map[string]interface{}{}
	for _, p := range properties {
		gv := GetProperty(obj, p)
		if gv == nil {
			continue
		}
		defer gv.Free()
		val, err := ConvertToGo(gv.GetPtr(), gv.gtype)
		if err == nil {
			m[p] = val
		}
	}
	return m
}

func SetProperty(obj ObjectLike, propName string, value interface{}) {
	cpn := GString(propName)
	defer cpn.Free()
	v := ConvertToC(value)
	defer v.Free()

	C.g_object_set_property(C.to_GObject(obj.ToNative()), (*C.gchar)(cpn.GetPtr()),
		(*C.GValue)(v.ToCGValue()))

}

func GetProperty(obj ObjectLike, propName string) *GValue {
	pspec := FindProperty(obj, propName)
	if pspec == nil {
		return nil
	}
	gv := CreateCGValue(pspec.GetType())
	pn := GString(propName)
	defer pn.Free()
	C.g_object_get_property(C.to_GObject(obj.ToNative()),
		(*C.gchar)(pn.GetPtr()),
		(*C.GValue)(gv.ToCGValue()))
	return gv
}

func Ref(obj ObjectLike) {
	C.g_object_ref(C.gpointer(obj.ToNative()))
}

func Unref(obj ObjectLike) {
	C.g_object_unref(C.gpointer(obj.ToNative()))
}

func SignalLookup(name string, objectType GType) uint32 {
	n := GString(name)
	defer n.Free()
	s := C.g_signal_lookup((*C.gchar)(n.GetPtr()), C.GType(objectType))
	return uint32(s)
}

func getUniqueID() int64 {
	return time.Nanoseconds()
}

type SignalError struct {
	Err string
}

func (self SignalError) Error() string {
	return self.Err
}

func createClosure(f interface{}, data ...interface{}) ClosureFunc {
	cfunc := reflect.ValueOf(f)

	// cfunc is not function, then there is nothing to do
	if cfunc.Kind() != reflect.Func {
		return nil
	}

	// Test number and type of return arguments
	// If return value is bool and is the only one, then
	// return that value to handler.
	// For anything else automaticaly return true
	var isTrue bool = true
	if numReturn := cfunc.Type().NumOut(); numReturn == 1 {
		rt := cfunc.Type().Out(0)
		if rt.Kind() == reflect.Bool {
			isTrue = false
		}
	}

	// Do we have variadic function for additional arguments
	var argslice bool = false
	if cfunc.Type().IsVariadic() {
		argslice = true
	}

	return func(additionalArgs []interface{}) bool {
		// Additional data
		// Create slice of reflect.Value data
		var args = make([]reflect.Value, 0)
		if len(data) > 0 {
			for _, d := range data {
				args = append(args, reflect.ValueOf(d))
			}
		}
		if argslice == true {
			for _, i := range additionalArgs {
				args = append(args, reflect.ValueOf(i))
			}
		}
		res := cfunc.Call(args)
		if isTrue {
			return isTrue
		}
		return res[0].Bool()
	}
}

func Connect(obj ObjectLike, name string, f interface{}, data ...interface{}) (*ClosureElement, *SignalError) {
	s_id := SignalLookup(name, GetTypeFromInstance(obj.ToNative()))

	if s_id == 0 {
		return nil, &SignalError{"Signal not found"}
	}
	uid := getUniqueID()
	c := createClosure(f, data...)
	cloEl := RegisterHandler(obj, name, uid, c)
	return cloEl, nil
}

func IsObjectFloating(obj ObjectLike) bool {
	b := C.g_object_is_floating(C.gpointer(obj.ToNative()))
	return GoBool(unsafe.Pointer(&b))
}

func RefSink(obj ObjectLike) {
	C.g_object_ref_sink(C.gpointer(obj.ToNative()))
}

func ClearObject(obj ObjectLike) {
	C._g_clear_object(obj.ToNative())
}

func WeakRef(obj ObjectLike) {
	o := C.to_GObject(obj.ToNative())
	C._g_object_weak_ref(o)
}
//export weak_ref_callback
func weak_ref_callback(data unsafe.Pointer, obj unsafe.Pointer) {
	tn := C.getTypeName(obj)
	s := GoString(unsafe.Pointer(tn))
	fmt.Println("Finalizing...", s)
}
<commit_msg>Fixed WeakRef to work with callbacks.<commit_after>package gobject

/*
#ifndef uintptr
#define uintptr unsigned int*
#endif
#include <glib.h>
#include <glib-object.h>
#include <stdlib.h>
#include <stdint.h>

static inline GObject* to_GObject(void* o) { return G_OBJECT(o); }
static inline void* new_GObject(GType typ) { return g_object_new(typ, NULL); }

static inline const gchar* getTypeName(void * o) { return G_OBJECT_TYPE_NAME(o); }

static inline GObjectClass* get_object_class(void* o) {
	return G_OBJECT_GET_CLASS(o);
}

static inline GType _get_type_from_instance(void* o) {
    return G_TYPE_FROM_INSTANCE(o);
}

extern void weak_ref_callback(gpointer data, GObject* object);

static void _g_object_weak_ref(GObject* object, gint64 data) {
	gint64* intdata = (gint64*)malloc(sizeof(gint64));
	*intdata = data;
	g_object_weak_ref(object, weak_ref_callback, (gpointer)intdata);
}

static void destroy_data(gpointer data) {
	free(data);
}

static void _g_clear_object(void* object) {
	GObject* o = G_OBJECT(object);
	g_clear_object(o);
}

*/
// #cgo pkg-config: gobject-2.0
import "C"
import "unsafe"
import "reflect"
import "time"

func GetTypeFromInstance(obj unsafe.Pointer) GType {
	return GType(C._get_type_from_instance(obj))
}

// Base interface which all gobject like structures must implement
// to be compatible with all gobject functions - public interfaces of gobject
type ObjectLike interface {
	ToNative() unsafe.Pointer
	Connect(s string, f interface{}, data ...interface{}) (*ClosureElement, *SignalError)
	Set(map[string]interface{})
	Get([]string) map[string]interface{}
}

//-----------------------------------------------------------------------
// GObject interfaces
//-----------------------------------------------------------------------
// Convenient struct - singleton
type gobject struct {
	object unsafe.Pointer
}

func (self gobject) ToNative() unsafe.Pointer {
	return self.object
}

func (self gobject) Connect(name string, f interface{}, data ...interface{}) (*ClosureElement, *SignalError) {
	return Connect(self, name, f, data...)
}

func (self gobject) Set(properties map[string]interface{}) {
	Set(self, properties)
}

func (self gobject) Get(properties []string) map[string]interface{} {
	return Get(self, properties)
}

func New(typ GType, properties map[string]interface{}) ObjectLike {
	obj := gobject{}
	obj.object = C.new_GObject(C.GType(typ))

	Set(obj, properties)

	return obj

}

func FindProperty(obj ObjectLike, propName string) *GParamSpec {
	cpn := GString(propName)
	defer cpn.Free()

	oc := C.get_object_class(obj.ToNative())
	pspec := C.g_object_class_find_property(oc, (*C.gchar)(cpn.GetPtr()))
	if pspec == nil {
		return nil
	}
	gpspec := GParamSpec{pspec}
	return &gpspec
}

func Set(obj ObjectLike, properties map[string]interface{}) {
	if len(properties) == 0 {
		return
	}

	for p, v := range properties {
		SetProperty(obj, p, v)
	}
}

func Get(obj ObjectLike, properties []string) map[string]interface{} {
	m := map[string]interface{}{}
	for _, p := range properties {
		gv := GetProperty(obj, p)
		if gv == nil {
			continue
		}
		defer gv.Free()
		val, err := ConvertToGo(gv.GetPtr(), gv.gtype)
		if err == nil {
			m[p] = val
		}
	}
	return m
}

func SetProperty(obj ObjectLike, propName string, value interface{}) {
	cpn := GString(propName)
	defer cpn.Free()
	v := ConvertToC(value)
	defer v.Free()

	C.g_object_set_property(C.to_GObject(obj.ToNative()), (*C.gchar)(cpn.GetPtr()),
		(*C.GValue)(v.ToCGValue()))

}

func GetProperty(obj ObjectLike, propName string) *GValue {
	pspec := FindProperty(obj, propName)
	if pspec == nil {
		return nil
	}
	gv := CreateCGValue(pspec.GetType())
	pn := GString(propName)
	defer pn.Free()
	C.g_object_get_property(C.to_GObject(obj.ToNative()),
		(*C.gchar)(pn.GetPtr()),
		(*C.GValue)(gv.ToCGValue()))
	return gv
}

func Ref(obj ObjectLike) {
	C.g_object_ref(C.gpointer(obj.ToNative()))
}

func Unref(obj ObjectLike) {
	C.g_object_unref(C.gpointer(obj.ToNative()))
}

func SignalLookup(name string, objectType GType) uint32 {
	n := GString(name)
	defer n.Free()
	s := C.g_signal_lookup((*C.gchar)(n.GetPtr()), C.GType(objectType))
	return uint32(s)
}

func getUniqueID() int64 {
	return time.Nanoseconds()
}

type SignalError struct {
	Err string
}

func (self SignalError) Error() string {
	return self.Err
}

func createClosure(f interface{}, data ...interface{}) ClosureFunc {
	cfunc := reflect.ValueOf(f)

	// cfunc is not function, then there is nothing to do
	if cfunc.Kind() != reflect.Func {
		return nil
	}

	// Test number and type of return arguments
	// If return value is bool and is the only one, then
	// return that value to handler.
	// For anything else automaticaly return true
	var isTrue bool = true
	if numReturn := cfunc.Type().NumOut(); numReturn == 1 {
		rt := cfunc.Type().Out(0)
		if rt.Kind() == reflect.Bool {
			isTrue = false
		}
	}

	// Do we have variadic function for additional arguments
	var argslice bool = false
	if cfunc.Type().IsVariadic() {
		argslice = true
	}

	return func(additionalArgs []interface{}) bool {
		// Additional data
		// Create slice of reflect.Value data
		var args = make([]reflect.Value, 0)
		if len(data) > 0 {
			for _, d := range data {
				args = append(args, reflect.ValueOf(d))
			}
		}
		if argslice == true {
			for _, i := range additionalArgs {
				args = append(args, reflect.ValueOf(i))
			}
		}
		res := cfunc.Call(args)
		if isTrue {
			return isTrue
		}
		return res[0].Bool()
	}
}

func Connect(obj ObjectLike, name string, f interface{}, data ...interface{}) (*ClosureElement, *SignalError) {
	s_id := SignalLookup(name, GetTypeFromInstance(obj.ToNative()))

	if s_id == 0 {
		return nil, &SignalError{"Signal not found"}
	}
	uid := getUniqueID()
	c := createClosure(f, data...)
	cloEl := RegisterHandler(obj, name, uid, c)
	return cloEl, nil
}

func IsObjectFloating(obj ObjectLike) bool {
	b := C.g_object_is_floating(C.gpointer(obj.ToNative()))
	return GoBool(unsafe.Pointer(&b))
}

func RefSink(obj ObjectLike) {
	C.g_object_ref_sink(C.gpointer(obj.ToNative()))
}

func ClearObject(obj ObjectLike) {
	C._g_clear_object(obj.ToNative())
}

// WeakRef closure stack
type WeakClosureFunc func()

var _weakClosures map[int64]WeakClosureFunc

func WeakRef(obj ObjectLike, f WeakClosureFunc) int64 {
	uid := getUniqueID()
	_weakClosures[uid] = f
	o := C.to_GObject(obj.ToNative())
	C._g_object_weak_ref(o, C.gint64(uid))

	return uid
}

//export weak_ref_callback
func weak_ref_callback(data unsafe.Pointer, obj unsafe.Pointer) {
	cint := int64(*((*C.gint64)(data)))

	if f, ok := _weakClosures[cint]; ok {
		// Call WeakClosureFunc to clean up something
		f()

		// Remove this closure from _weakClosures
		delete(_weakClosures, cint)
	}

	// Free data
	C.destroy_data(C.gpointer(data))
}

func init() {
	_weakClosures = make(map[int64]WeakClosureFunc)
}
<|endoftext|>


<commit_before>package bsw

import (
	"crypto/tls"
	"net/http"
	"net/url"
	"regexp"
)

// Using http(s), attempt to connect to an IP. If connection is successfull return any hostnames from the possible
// 'Location' headers.
func Headers(ip string) (Results, error) {
	results := []Result{}
	for _, proto := range []string{"http", "https"} {
		if host := hostnameFromHttpLocationHeader(ip, proto); host != "" {
			results = append(results, Result{Source: "Headers", IP: ip, Hostname: host})
		}
	}
	return results, nil
}

// Performs http(s) request and parses possible 'Location' headers.
func hostnameFromHttpLocationHeader(ip, protocol string) string {
	req, err := http.NewRequest("GET", protocol+"://"+ip, nil)
	if err != nil {
		return ""
	}
	tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	res, err := tr.RoundTrip(req)
	if err != nil {
		return ""
	}
	location := res.Header["Location"]
	if location != nil {
		u, err := url.Parse(location[0])
		if err != nil {
			return ""
		}
		host := u.Host
		if m, _ := regexp.Match("[a-zA-Z]+", []byte(host)); m == true {
			return host
		}
		return ""
	}
	return ""
}
<commit_msg>Adds timeout for header functions<commit_after>package bsw

import (
	"crypto/tls"
	"net"
	"net/http"
	"net/url"
	"regexp"
	"time"
)

// Using http(s), attempt to connect to an IP. If connection is successfull return any hostnames from the possible
// 'Location' headers.
func Headers(ip string) (Results, error) {
	results := []Result{}
	for _, proto := range []string{"http", "https"} {
		if host := hostnameFromHttpLocationHeader(ip, proto); host != "" {
			results = append(results, Result{Source: "Headers", IP: ip, Hostname: host})
		}
	}
	return results, nil
}

// Performs http(s) request and parses possible 'Location' headers.
func hostnameFromHttpLocationHeader(ip, protocol string) string {
	req, err := http.NewRequest("GET", protocol+"://"+ip, nil)
	if err != nil {
		return ""
	}
	tr := &http.Transport{
		Dial: func(network, addr string) (net.Conn, error) {
			return net.DialTimeout(network, addr, time.Duration(1*time.Second))
		},
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	res, err := tr.RoundTrip(req)
	if err != nil {
		return ""
	}
	location := res.Header["Location"]
	if location != nil {
		u, err := url.Parse(location[0])
		if err != nil {
			return ""
		}
		host := u.Host
		if m, _ := regexp.Match("[a-zA-Z]+", []byte(host)); m == true {
			return host
		}
		return ""
	}
	return ""
}
<|endoftext|>


<commit_before>package bufit

import (
	"bytes"
	"crypto/rand"
	"io"
	"io/ioutil"
	"os"
	"sync"
	"testing"
	"time"
)

func exampleBytes() {
	buf := newWriter(make([]byte, 0, 10))
	io.Copy(os.Stdout, buf)
	io.Copy(os.Stdout, io.NewSectionReader(*&buf, 0, 100))

	io.WriteString(buf, "Hello ")
	r := io.NewSectionReader(*&buf, 0, int64(buf.Len()))
	io.CopyN(os.Stdout, r, 5)
	io.CopyN(os.Stdout, buf, 5)
	io.WriteString(buf, "World")
	r = io.NewSectionReader(*&buf, 0, int64(buf.Len()))
	io.CopyN(os.Stdout, r, 6)

	io.WriteString(buf, "abcdefg")
	io.Copy(os.Stdout, buf)
	io.Copy(os.Stdout, buf)

	io.WriteString(buf, "Hello World")
	r = io.NewSectionReader(*&buf, 0, int64(buf.Len()))
	io.CopyN(os.Stdout, r, 5)
	io.CopyN(os.Stdout, buf, 4)

	io.WriteString(buf, "abcdefg")
	io.Copy(os.Stdout, buf)
	io.Copy(os.Stdout, buf)
	//Output:
	// HelloHello World WorldabcdefgHelloHello Worldabcdefg
}

type badBuffer []byte

func (b *badBuffer) Write(p []byte) (int, error) {
	*b = append(*b, p...)
	return len(p), nil
}

func (b *badBuffer) Read(p []byte) (n int, err error) {
	n = copy(p, *b)
	*b = (*b)[n:]
	if len(*b) == 0 {
		err = io.EOF
	}
	return n, err
}

func BenchmarkBuffer(b *testing.B) {
	buf := New()
	data, _ := ioutil.ReadAll(io.LimitReader(rand.Reader, 32*1024))

	go func() {
		for i := 0; i < 1000; i++ {
			buf.Write(data)
		}
		buf.Close()
	}()

	r := buf.NextReader()

	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			rr := buf.NextReader()
			io.Copy(ioutil.Discard, rr)
			rr.Close()
		}
	})

	r.Close()
	b.ReportAllocs()
}

func BenchmarkReadWriter(b *testing.B) {
	buf := newWriter(nil)
	data, _ := ioutil.ReadAll(io.LimitReader(rand.Reader, 32*1024))
	temp := make([]byte, 32*1024)
	for i := 0; i < b.N; i++ {
		buf.Write(data)
		io.CopyBuffer(ioutil.Discard, buf, temp)
	}
	b.ReportAllocs()
}

func TestConcurrent(t *testing.T) {
	var grp sync.WaitGroup
	buf := New()

	var rs []io.ReadCloser
	for i := 0; i < 1000; i++ {
		rs = append(rs, buf.NextReader())
	}

	testData := bytes.NewBuffer(nil)
	io.CopyN(testData, rand.Reader, 32*1024*10)

	for _, r := range rs {
		grp.Add(1)
		go func(r io.ReadCloser) {
			defer grp.Done()
			defer r.Close()
			data, err := ioutil.ReadAll(r)
			if err != nil {
				t.Error(err)
			}
			if !bytes.Equal(testData.Bytes(), data) {
				t.Error("unexpected result...", testData.Len(), len(data))
			}
		}(r)
	}

	r := bytes.NewReader(testData.Bytes())
	for r.Len() > 0 {
		io.CopyN(buf, r, 32*1024*2)
		<-time.After(100 * time.Millisecond)
	}
	buf.Close()
	grp.Wait()
}

func TestQuit(t *testing.T) {
	buf := New()
	r := buf.NextReader()

	wait := make(chan struct{})
	go func() {
		io.Copy(ioutil.Discard, r)
		close(wait)
	}()

	r.Close()
	select {
	case <-wait:
	case <-time.After(100 * time.Millisecond):
		t.Error("timed out waiting for Reader to Close")
	}
}

func ExampleBuffer() {
	// Start a new buffer
	buf := New()

	// Create two readers
	r1, r2 := buf.NextReader(), buf.NextReader()

	// Broadcast a message
	io.WriteString(buf, "Hello World\n")

	// Wait
	var grp sync.WaitGroup
	grp.Add(4)

	// Read fast
	go func() {
		defer grp.Done()
		io.Copy(os.Stdout, r1) // "Hello World\n"
	}()

	// Read slow
	go func() {
		defer grp.Done()
		<-time.After(100 * time.Millisecond)
		io.CopyN(os.Stdout, r2, 5) // "Hello"
		<-time.After(time.Second)
		io.Copy(os.Stdout, r2) // "World\n"
	}()

	// Both readers will read the entire buffer! The slow reader
	// won't block the fast one from reading ahead either.

	// Late reader
	// Since this reader joins after all existing readers have Read "Hello"
	// "Hello" has already been cleared from the Buffer, this Reader will only see
	// "World\n" and beyond.
	go func() {
		defer grp.Done()
		<-time.After(500 * time.Millisecond)
		r3 := buf.NextReader()
		io.Copy(os.Stdout, r3) // "World\n"
	}()

	// Short Reader
	// **Important!** if your reader isn't going to read until the buffer is empty
	// you'll need to call Close() when you are done with it to tell the buffer
	// it's done reading data.
	go func() {
		defer grp.Done()
		<-time.After(100 * time.Millisecond)
		r4 := buf.NextReader()
		io.CopyN(os.Stdout, r4, 5) // "Hello"
		r4.Close()                 // tell the buffer you're done reading
	}()

	// **Important!** mark close so that readers can ret. io.EOF
	buf.Close()

	grp.Wait()
	// Output:
	// Hello World
	// HelloHelloHello World
	//  World
}
<commit_msg>Changed exampleBytes to ExampleWriter to expose example<commit_after>package bufit

import (
	"bytes"
	"crypto/rand"
	"io"
	"io/ioutil"
	"os"
	"sync"
	"testing"
	"time"
)

func ExampleWriter() {
	buf := newWriter(make([]byte, 0, 10))
	io.Copy(os.Stdout, buf)
	io.Copy(os.Stdout, io.NewSectionReader(*&buf, 0, 100))

	io.WriteString(buf, "Hello ")
	r := io.NewSectionReader(*&buf, 0, int64(buf.Len()))
	io.CopyN(os.Stdout, r, 5)
	io.CopyN(os.Stdout, buf, 5)
	io.WriteString(buf, "World")
	r = io.NewSectionReader(*&buf, 0, int64(buf.Len()))
	io.CopyN(os.Stdout, r, 6)

	io.WriteString(buf, "abcdefg")
	io.Copy(os.Stdout, buf)
	io.Copy(os.Stdout, buf)

	io.WriteString(buf, "Hello World")
	r = io.NewSectionReader(*&buf, 0, int64(buf.Len()))
	io.CopyN(os.Stdout, r, 5)
	io.CopyN(os.Stdout, buf, 4)

	io.WriteString(buf, "abcdefg")
	io.Copy(os.Stdout, buf)
	io.Copy(os.Stdout, buf)
	//Output:
	// HelloHello World WorldabcdefgHelloHello Worldabcdefg
}

type badBuffer []byte

func (b *badBuffer) Write(p []byte) (int, error) {
	*b = append(*b, p...)
	return len(p), nil
}

func (b *badBuffer) Read(p []byte) (n int, err error) {
	n = copy(p, *b)
	*b = (*b)[n:]
	if len(*b) == 0 {
		err = io.EOF
	}
	return n, err
}

func BenchmarkBuffer(b *testing.B) {
	buf := New()
	data, _ := ioutil.ReadAll(io.LimitReader(rand.Reader, 32*1024))

	go func() {
		for i := 0; i < 1000; i++ {
			buf.Write(data)
		}
		buf.Close()
	}()

	r := buf.NextReader()

	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			rr := buf.NextReader()
			io.Copy(ioutil.Discard, rr)
			rr.Close()
		}
	})

	r.Close()
	b.ReportAllocs()
}

func BenchmarkReadWriter(b *testing.B) {
	buf := newWriter(nil)
	data, _ := ioutil.ReadAll(io.LimitReader(rand.Reader, 32*1024))
	temp := make([]byte, 32*1024)
	for i := 0; i < b.N; i++ {
		buf.Write(data)
		io.CopyBuffer(ioutil.Discard, buf, temp)
	}
	b.ReportAllocs()
}

func TestConcurrent(t *testing.T) {
	var grp sync.WaitGroup
	buf := New()

	var rs []io.ReadCloser
	for i := 0; i < 1000; i++ {
		rs = append(rs, buf.NextReader())
	}

	testData := bytes.NewBuffer(nil)
	io.CopyN(testData, rand.Reader, 32*1024*10)

	for _, r := range rs {
		grp.Add(1)
		go func(r io.ReadCloser) {
			defer grp.Done()
			defer r.Close()
			data, err := ioutil.ReadAll(r)
			if err != nil {
				t.Error(err)
			}
			if !bytes.Equal(testData.Bytes(), data) {
				t.Error("unexpected result...", testData.Len(), len(data))
			}
		}(r)
	}

	r := bytes.NewReader(testData.Bytes())
	for r.Len() > 0 {
		io.CopyN(buf, r, 32*1024*2)
		<-time.After(100 * time.Millisecond)
	}
	buf.Close()
	grp.Wait()
}

func TestQuit(t *testing.T) {
	buf := New()
	r := buf.NextReader()

	wait := make(chan struct{})
	go func() {
		io.Copy(ioutil.Discard, r)
		close(wait)
	}()

	r.Close()
	select {
	case <-wait:
	case <-time.After(100 * time.Millisecond):
		t.Error("timed out waiting for Reader to Close")
	}
}

func ExampleBuffer() {
	// Start a new buffer
	buf := New()

	// Create two readers
	r1, r2 := buf.NextReader(), buf.NextReader()

	// Broadcast a message
	io.WriteString(buf, "Hello World\n")

	// Wait
	var grp sync.WaitGroup
	grp.Add(4)

	// Read fast
	go func() {
		defer grp.Done()
		io.Copy(os.Stdout, r1) // "Hello World\n"
	}()

	// Read slow
	go func() {
		defer grp.Done()
		<-time.After(100 * time.Millisecond)
		io.CopyN(os.Stdout, r2, 5) // "Hello"
		<-time.After(time.Second)
		io.Copy(os.Stdout, r2) // "World\n"
	}()

	// Both readers will read the entire buffer! The slow reader
	// won't block the fast one from reading ahead either.

	// Late reader
	// Since this reader joins after all existing readers have Read "Hello"
	// "Hello" has already been cleared from the Buffer, this Reader will only see
	// "World\n" and beyond.
	go func() {
		defer grp.Done()
		<-time.After(500 * time.Millisecond)
		r3 := buf.NextReader()
		io.Copy(os.Stdout, r3) // "World\n"
	}()

	// Short Reader
	// **Important!** if your reader isn't going to read until the buffer is empty
	// you'll need to call Close() when you are done with it to tell the buffer
	// it's done reading data.
	go func() {
		defer grp.Done()
		<-time.After(100 * time.Millisecond)
		r4 := buf.NextReader()
		io.CopyN(os.Stdout, r4, 5) // "Hello"
		r4.Close()                 // tell the buffer you're done reading
	}()

	// **Important!** mark close so that readers can ret. io.EOF
	buf.Close()

	grp.Wait()
	// Output:
	// Hello World
	// HelloHelloHello World
	//  World
}
<|endoftext|>


<commit_before>package main

import "time"

var JapaneseWeekDay = map[string]string{
	"Mon": "月",
	"Tue": "火",
	"Wed": "水",
	"Thu": "木",
	"Fri": "金",
	"Sat": "土",
	"Sun": "日",
}

func dateFormat(date time.Time) string {
	return date.Format("1月2日（") + JapaneseWeekDay[date.Format("Mon")] + "）"
}

func timeFormat(t time.Time) string {
	return t.Format("03:04")
}

func TodayMessage(c Calendar) string {
	today := time.Now()
	ans := "今日" + dateFormat(today) + "のごみは\n"
	ans += c.Date(today) + "\n"
	ans += "です(｀･ω･´) " + timeFormat(time.Now())
	return ans
}

func TomorrowMessage(c Calendar) string {
	tomorrow := time.Now().Add(24 * time.Hour)
	ans := "明日" + dateFormat(tomorrow) + "のごみは\n"
	ans += c.Date(tomorrow) + "\n"
	ans += "です(｀･ω･´) " + timeFormat(time.Now())
	return ans
}
<commit_msg>24時間表記になっていない問題を修正<commit_after>package main

import "time"

var JapaneseWeekDay = map[string]string{
	"Mon": "月",
	"Tue": "火",
	"Wed": "水",
	"Thu": "木",
	"Fri": "金",
	"Sat": "土",
	"Sun": "日",
}

func dateFormat(date time.Time) string {
	return date.Format("1月2日（") + JapaneseWeekDay[date.Format("Mon")] + "）"
}

func timeFormat(t time.Time) string {
	return t.Format("15:04")
}

func TodayMessage(c Calendar) string {
	today := time.Now()
	ans := "今日" + dateFormat(today) + "のごみは\n"
	ans += c.Date(today) + "\n"
	ans += "です(｀･ω･´) " + timeFormat(time.Now())
	return ans
}

func TomorrowMessage(c Calendar) string {
	tomorrow := time.Now().Add(24 * time.Hour)
	ans := "明日" + dateFormat(tomorrow) + "のごみは\n"
	ans += c.Date(tomorrow) + "\n"
	ans += "です(｀･ω･´) " + timeFormat(time.Now())
	return ans
}
<|endoftext|>


<commit_before>package plugins

import (
	"fmt"
	"os"

	"github.com/InnovaCo/serve/manifest"
	"github.com/InnovaCo/serve/utils"
)

func init() {
	manifest.PluginRegestry.Add("build.debian", BuildDebian{})
}

type BuildDebian struct{}

func (p BuildDebian) Run(data manifest.Manifest) error {
	env := make(map[string]string)

	// required fields
	env["MANIFEST_PACKAGE"] = data.GetString("package")
	env["MANIFEST_INFO_NAME"] = data.GetString("name")
	env["MANIFEST_INFO_VERSION"] = data.GetString("version")
	env["MANIFEST_BUILD_DEBIAN_SECTION"] = data.GetString("category")
	env["MANIFEST_INFO_CATEGORY"] = data.GetString("category")
	env["MANIFEST_BUILD_DEBIAN_MAINTAINER_NAME"] = data.GetString("maintainer-name")
	env["MANIFEST_BUILD_DEBIAN_MAINTAINER_EMAIL"] = data.GetString("maintainer-email")
	env["MANIFEST_BUILD_DEBIAN_INSTALL_ROOT"] = data.GetString("install-root")

	daemon := data.GetString("daemon")
	daemonArgs := data.GetString("daemon-args")

	if daemon != "" {
		daemonArgs = fmt.Sprintf(
			"consul supervisor --service '%s' --port $PORT1 start %s %s",
			data.GetString("package"),
			daemon,
			daemonArgs,
		)

		daemon = "/usr/local/bin/serve-tools"
	}

	// optional fields
	env["MANIFEST_BUILD_DEBIAN_DAEMON"] = daemon
	env["MANIFEST_BUILD_DEBIAN_DAEMON_ARGS"] = daemonArgs
	env["MANIFEST_BUILD_DEBIAN_SERVICE_OWNER"] = data.GetString("service-owner")
	env["MANIFEST_BUILD_DEBIAN_DAEMON_USER"] = data.GetString("daemon-user")
	env["MANIFEST_BUILD_DEBIAN_DAEMON_PORT"] = data.GetString("daemon-port")
	env["MANIFEST_BUILD_DEBIAN_MAKE_PIDFILE"] = data.GetString("make-pidfile")
	env["MANIFEST_BUILD_DEBIAN_DEPENDS"] = data.GetString("depends")
	env["MANIFEST_BUILD_DEBIAN_DESCRIPTION"] = data.GetString("description")
	env["MANIFEST_BUILD_DEBIAN_INIT"] = data.GetString("init")
	env["MANIFEST_BUILD_DEBIAN_CRON"] = data.GetString("cron")

	env["GO_PIPELINE_LABEL"] = data.GetString("build-number")
	env["GO_STAGE_COUNTER"] = data.GetString("stage-counter")

	for k, v := range env {
		fmt.Printf("export %s=\"%s\"\n", k, v)
		os.Setenv(k, v)
	}

	return utils.RunCmd(
		"%s/go/debian-build.sh --distribution=%s",
		data.GetString("ci-tools-path"),
		data.GetString("distribution"),
	)
}
<commit_msg>= deb: register to consul with category prefix<commit_after>package plugins

import (
	"fmt"
	"os"

	"github.com/InnovaCo/serve/manifest"
	"github.com/InnovaCo/serve/utils"
)

func init() {
	manifest.PluginRegestry.Add("build.debian", BuildDebian{})
}

type BuildDebian struct{}

func (p BuildDebian) Run(data manifest.Manifest) error {
	env := make(map[string]string)

	// required fields
	env["MANIFEST_PACKAGE"] = data.GetString("package")
	env["MANIFEST_INFO_NAME"] = data.GetString("name")
	env["MANIFEST_INFO_VERSION"] = data.GetString("version")
	env["MANIFEST_BUILD_DEBIAN_SECTION"] = data.GetString("category")
	env["MANIFEST_INFO_CATEGORY"] = data.GetString("category")
	env["MANIFEST_BUILD_DEBIAN_MAINTAINER_NAME"] = data.GetString("maintainer-name")
	env["MANIFEST_BUILD_DEBIAN_MAINTAINER_EMAIL"] = data.GetString("maintainer-email")
	env["MANIFEST_BUILD_DEBIAN_INSTALL_ROOT"] = data.GetString("install-root")

	daemon := data.GetString("daemon")
	daemonArgs := data.GetString("daemon-args")

	if daemon != "" {
		daemonArgs = fmt.Sprintf(
			"consul supervisor --service '%s/%s' --port $PORT1 start %s %s",
			data.GetString("category"),
			data.GetString("package"),
			daemon,
			daemonArgs,
		)

		daemon = "/usr/local/bin/serve-tools"
	}

	// optional fields
	env["MANIFEST_BUILD_DEBIAN_DAEMON"] = daemon
	env["MANIFEST_BUILD_DEBIAN_DAEMON_ARGS"] = daemonArgs
	env["MANIFEST_BUILD_DEBIAN_SERVICE_OWNER"] = data.GetString("service-owner")
	env["MANIFEST_BUILD_DEBIAN_DAEMON_USER"] = data.GetString("daemon-user")
	env["MANIFEST_BUILD_DEBIAN_DAEMON_PORT"] = data.GetString("daemon-port")
	env["MANIFEST_BUILD_DEBIAN_MAKE_PIDFILE"] = data.GetString("make-pidfile")
	env["MANIFEST_BUILD_DEBIAN_DEPENDS"] = data.GetString("depends")
	env["MANIFEST_BUILD_DEBIAN_DESCRIPTION"] = data.GetString("description")
	env["MANIFEST_BUILD_DEBIAN_INIT"] = data.GetString("init")
	env["MANIFEST_BUILD_DEBIAN_CRON"] = data.GetString("cron")

	env["GO_PIPELINE_LABEL"] = data.GetString("build-number")
	env["GO_STAGE_COUNTER"] = data.GetString("stage-counter")

	for k, v := range env {
		fmt.Printf("export %s=\"%s\"\n", k, v)
		os.Setenv(k, v)
	}

	return utils.RunCmd(
		"%s/go/debian-build.sh --distribution=%s",
		data.GetString("ci-tools-path"),
		data.GetString("distribution"),
	)
}
<|endoftext|>


<commit_before>package gormigrate

import (
	"os"
	"testing"

	"github.com/jinzhu/gorm"
	_ "github.com/joho/godotenv/autoload"
	"github.com/stretchr/testify/assert"
)

var databases []database

type database struct {
	name    string
	connEnv string
}

var migrations = []*Migration{
	{
		ID: "201608301400",
		Migrate: func(tx *gorm.DB) error {
			return tx.AutoMigrate(&Person{}).Error
		},
		Rollback: func(tx *gorm.DB) error {
			return tx.DropTable("people").Error
		},
	},
	{
		ID: "201608301430",
		Migrate: func(tx *gorm.DB) error {
			return tx.AutoMigrate(&Pet{}).Error
		},
		Rollback: func(tx *gorm.DB) error {
			return tx.DropTable("pets").Error
		},
	},
}

var extendedMigrations = append(migrations, &Migration{
	ID: "201807221927",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&Book{}).Error
	},
	Rollback: func(tx *gorm.DB) error {
		return tx.DropTable("books").Error
	},
})

type Person struct {
	gorm.Model
	Name string
}

type Pet struct {
	gorm.Model
	Name     string
	PersonID int
}

type Book struct {
	gorm.Model
	Name     string
	PersonID int
}

func TestMigration(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)

		err := m.Migrate()
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.Equal(t, 2, tableCount(t, db, "migrations"))

		err = m.RollbackLast()
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))

		err = m.RollbackLast()
		assert.NoError(t, err)
		assert.False(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.Equal(t, 0, tableCount(t, db, "migrations"))
	})
}

func TestMigrateTo(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, extendedMigrations)

		err := m.MigrateTo("201608301430")
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.False(t, db.HasTable(&Book{}))
		assert.Equal(t, 2, tableCount(t, db, "migrations"))
	})
}

func TestRollbackTo(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, extendedMigrations)

		// First, apply all migrations.
		err := m.Migrate()
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.True(t, db.HasTable(&Book{}))
		assert.Equal(t, 3, tableCount(t, db, "migrations"))

		// Rollback to the first migration: only the last 2 migrations are expected to be rolled back.
		err = m.RollbackTo("201608301400")
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.False(t, db.HasTable(&Book{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))
	})
}

// If initSchema is defined, but no migrations are provided,
// then initSchema is executed.
func TestInitSchemaNoMigrations(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, []*Migration{})
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Person{}).Error; err != nil {
				return err
			}
			if err := tx.AutoMigrate(&Pet{}).Error; err != nil {
				return err
			}
			return nil
		})

		assert.NoError(t, m.Migrate())
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))
	})
}

// If initSchema is defined and migrations are provided,
// then initSchema is executed and the migration IDs are stored,
// even though the relevant migrations are not applied.
func TestInitSchemaWithMigrations(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Person{}).Error; err != nil {
				return err
			}
			return nil
		})

		assert.NoError(t, m.Migrate())
		assert.True(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.Equal(t, 3, tableCount(t, db, "migrations"))
	})
}

// If the schema has already been initialised,
// then initSchema() is not executed, even if defined.
func TestInitSchemaAlreadyInitialised(t *testing.T) {
	type Car struct {
		gorm.Model
	}

	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, []*Migration{})

		// Migrate with empty initialisation
		m.InitSchema(func(tx *gorm.DB) error {
			return nil
		})
		assert.NoError(t, m.Migrate())

		// Then migrate again, this time with a non empty initialisation
		// This second initialisation should not happen!
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Car{}).Error; err != nil {
				return err
			}
			return nil
		})
		assert.NoError(t, m.Migrate())

		assert.False(t, db.HasTable(&Car{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))
	})
}

// If the schema has already been initialised,
// then initSchema() is not executed, even if defined.
func TestInitSchemaExistingMigrations(t *testing.T) {
	type Car struct {
		gorm.Model
	}

	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)

		// Migrate without initialisation
		assert.NoError(t, m.Migrate())

		// Then migrate again, this time with a non empty initialisation
		// This initialisation should not happen!
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Car{}).Error; err != nil {
				return err
			}
			return nil
		})
		assert.NoError(t, m.Migrate())

		assert.False(t, db.HasTable(&Car{}))
		assert.Equal(t, 2, tableCount(t, db, "migrations"))
	})
}

func TestMigrationIDDoesNotExist(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.MigrateTo("1234"))
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.RollbackTo("1234"))
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.MigrateTo(""))
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.RollbackTo(""))
	})
}

func TestMissingID(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		migrationsMissingID := []*Migration{
			{
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
		}

		m := New(db, DefaultOptions, migrationsMissingID)
		assert.Equal(t, ErrMissingID, m.Migrate())
	})
}

func TestReservedID(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		migrationsReservedID := []*Migration{
			{
				ID: "SCHEMA_INIT",
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
		}

		m := New(db, DefaultOptions, migrationsReservedID)
		_, isReservedIDError := m.Migrate().(*ReservedIDError)
		assert.True(t, isReservedIDError)
	})
}

func TestDuplicatedID(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		migrationsDuplicatedID := []*Migration{
			{
				ID: "201705061500",
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
			{
				ID: "201705061500",
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
		}

		m := New(db, DefaultOptions, migrationsDuplicatedID)
		_, isDuplicatedIDError := m.Migrate().(*DuplicatedIDError)
		assert.True(t, isDuplicatedIDError)
	})
}

func TestEmptyMigrationList(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		t.Run("with empty list", func(t *testing.T) {
			m := New(db, DefaultOptions, []*Migration{})
			err := m.Migrate()
			assert.Equal(t, ErrNoMigrationDefined, err)
		})

		t.Run("with nil list", func(t *testing.T) {
			m := New(db, DefaultOptions, nil)
			err := m.Migrate()
			assert.Equal(t, ErrNoMigrationDefined, err)
		})
	})
}

func tableCount(t *testing.T, db *gorm.DB, tableName string) (count int) {
	assert.NoError(t, db.Table(tableName).Count(&count).Error)
	return
}

func forEachDatabase(t *testing.T, fn func(database *gorm.DB)) {
	if len(databases) == 0 {
		panic("No database choosen for testing!")
	}

	for _, database := range databases {
		db, err := gorm.Open(database.name, os.Getenv(database.connEnv))
		assert.NoError(t, err, "Could not connect to database %s, %v", database.name, err)

		defer db.Close()

		// ensure tables do not exists
		assert.NoError(t, db.DropTableIfExists("migrations", "people", "pets").Error)

		fn(db)
	}
}
<commit_msg>Fixed comment.<commit_after>package gormigrate

import (
	"os"
	"testing"

	"github.com/jinzhu/gorm"
	_ "github.com/joho/godotenv/autoload"
	"github.com/stretchr/testify/assert"
)

var databases []database

type database struct {
	name    string
	connEnv string
}

var migrations = []*Migration{
	{
		ID: "201608301400",
		Migrate: func(tx *gorm.DB) error {
			return tx.AutoMigrate(&Person{}).Error
		},
		Rollback: func(tx *gorm.DB) error {
			return tx.DropTable("people").Error
		},
	},
	{
		ID: "201608301430",
		Migrate: func(tx *gorm.DB) error {
			return tx.AutoMigrate(&Pet{}).Error
		},
		Rollback: func(tx *gorm.DB) error {
			return tx.DropTable("pets").Error
		},
	},
}

var extendedMigrations = append(migrations, &Migration{
	ID: "201807221927",
	Migrate: func(tx *gorm.DB) error {
		return tx.AutoMigrate(&Book{}).Error
	},
	Rollback: func(tx *gorm.DB) error {
		return tx.DropTable("books").Error
	},
})

type Person struct {
	gorm.Model
	Name string
}

type Pet struct {
	gorm.Model
	Name     string
	PersonID int
}

type Book struct {
	gorm.Model
	Name     string
	PersonID int
}

func TestMigration(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)

		err := m.Migrate()
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.Equal(t, 2, tableCount(t, db, "migrations"))

		err = m.RollbackLast()
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))

		err = m.RollbackLast()
		assert.NoError(t, err)
		assert.False(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.Equal(t, 0, tableCount(t, db, "migrations"))
	})
}

func TestMigrateTo(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, extendedMigrations)

		err := m.MigrateTo("201608301430")
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.False(t, db.HasTable(&Book{}))
		assert.Equal(t, 2, tableCount(t, db, "migrations"))
	})
}

func TestRollbackTo(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, extendedMigrations)

		// First, apply all migrations.
		err := m.Migrate()
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.True(t, db.HasTable(&Book{}))
		assert.Equal(t, 3, tableCount(t, db, "migrations"))

		// Rollback to the first migration: only the last 2 migrations are expected to be rolled back.
		err = m.RollbackTo("201608301400")
		assert.NoError(t, err)
		assert.True(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.False(t, db.HasTable(&Book{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))
	})
}

// If initSchema is defined, but no migrations are provided,
// then initSchema is executed.
func TestInitSchemaNoMigrations(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, []*Migration{})
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Person{}).Error; err != nil {
				return err
			}
			if err := tx.AutoMigrate(&Pet{}).Error; err != nil {
				return err
			}
			return nil
		})

		assert.NoError(t, m.Migrate())
		assert.True(t, db.HasTable(&Person{}))
		assert.True(t, db.HasTable(&Pet{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))
	})
}

// If initSchema is defined and migrations are provided,
// then initSchema is executed and the migration IDs are stored,
// even though the relevant migrations are not applied.
func TestInitSchemaWithMigrations(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Person{}).Error; err != nil {
				return err
			}
			return nil
		})

		assert.NoError(t, m.Migrate())
		assert.True(t, db.HasTable(&Person{}))
		assert.False(t, db.HasTable(&Pet{}))
		assert.Equal(t, 3, tableCount(t, db, "migrations"))
	})
}

// If the schema has already been initialised,
// then initSchema() is not executed, even if defined.
func TestInitSchemaAlreadyInitialised(t *testing.T) {
	type Car struct {
		gorm.Model
	}

	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, []*Migration{})

		// Migrate with empty initialisation
		m.InitSchema(func(tx *gorm.DB) error {
			return nil
		})
		assert.NoError(t, m.Migrate())

		// Then migrate again, this time with a non empty initialisation
		// This second initialisation should not happen!
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Car{}).Error; err != nil {
				return err
			}
			return nil
		})
		assert.NoError(t, m.Migrate())

		assert.False(t, db.HasTable(&Car{}))
		assert.Equal(t, 1, tableCount(t, db, "migrations"))
	})
}

// If the schema has not already been initialised,
// but any other migration has already been applied,
// then initSchema() is not executed, even if defined.
func TestInitSchemaExistingMigrations(t *testing.T) {
	type Car struct {
		gorm.Model
	}

	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)

		// Migrate without initialisation
		assert.NoError(t, m.Migrate())

		// Then migrate again, this time with a non empty initialisation
		// This initialisation should not happen!
		m.InitSchema(func(tx *gorm.DB) error {
			if err := tx.AutoMigrate(&Car{}).Error; err != nil {
				return err
			}
			return nil
		})
		assert.NoError(t, m.Migrate())

		assert.False(t, db.HasTable(&Car{}))
		assert.Equal(t, 2, tableCount(t, db, "migrations"))
	})
}

func TestMigrationIDDoesNotExist(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		m := New(db, DefaultOptions, migrations)
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.MigrateTo("1234"))
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.RollbackTo("1234"))
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.MigrateTo(""))
		assert.Equal(t, ErrMigrationIDDoesNotExist, m.RollbackTo(""))
	})
}

func TestMissingID(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		migrationsMissingID := []*Migration{
			{
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
		}

		m := New(db, DefaultOptions, migrationsMissingID)
		assert.Equal(t, ErrMissingID, m.Migrate())
	})
}

func TestReservedID(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		migrationsReservedID := []*Migration{
			{
				ID: "SCHEMA_INIT",
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
		}

		m := New(db, DefaultOptions, migrationsReservedID)
		_, isReservedIDError := m.Migrate().(*ReservedIDError)
		assert.True(t, isReservedIDError)
	})
}

func TestDuplicatedID(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		migrationsDuplicatedID := []*Migration{
			{
				ID: "201705061500",
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
			{
				ID: "201705061500",
				Migrate: func(tx *gorm.DB) error {
					return nil
				},
			},
		}

		m := New(db, DefaultOptions, migrationsDuplicatedID)
		_, isDuplicatedIDError := m.Migrate().(*DuplicatedIDError)
		assert.True(t, isDuplicatedIDError)
	})
}

func TestEmptyMigrationList(t *testing.T) {
	forEachDatabase(t, func(db *gorm.DB) {
		t.Run("with empty list", func(t *testing.T) {
			m := New(db, DefaultOptions, []*Migration{})
			err := m.Migrate()
			assert.Equal(t, ErrNoMigrationDefined, err)
		})

		t.Run("with nil list", func(t *testing.T) {
			m := New(db, DefaultOptions, nil)
			err := m.Migrate()
			assert.Equal(t, ErrNoMigrationDefined, err)
		})
	})
}

func tableCount(t *testing.T, db *gorm.DB, tableName string) (count int) {
	assert.NoError(t, db.Table(tableName).Count(&count).Error)
	return
}

func forEachDatabase(t *testing.T, fn func(database *gorm.DB)) {
	if len(databases) == 0 {
		panic("No database choosen for testing!")
	}

	for _, database := range databases {
		db, err := gorm.Open(database.name, os.Getenv(database.connEnv))
		assert.NoError(t, err, "Could not connect to database %s, %v", database.name, err)

		defer db.Close()

		// ensure tables do not exists
		assert.NoError(t, db.DropTableIfExists("migrations", "people", "pets").Error)

		fn(db)
	}
}
<|endoftext|>