<commit_before>/*
Copyright 2019 The Knative 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 network

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"knative.dev/pkg/network"
	"knative.dev/pkg/network/prober"
	_ "knative.dev/pkg/system/testing"
)

func TestProbeHandlerSuccessfulProbe(t *testing.T) {
	body := "Inner Body"
	cases := []struct {
		name    string
		options []interface{}
		want    bool
		expErr  bool
	}{{
		name: "successful probe when both headers are specified",
		options: []interface{}{
			prober.WithHeader(ProbeHeaderName, ProbeHeaderValue),
			prober.WithHeader(HashHeaderName, "foo-bar-baz"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "forwards to inner handler when probe header is not specified",
		options: []interface{}{
			prober.WithHeader(HashHeaderName, "foo-bar-baz"),
			prober.ExpectsBody(body),
			// Validates the header is stripped before forwarding to the inner handler
			prober.ExpectsHeader(HashHeaderName, "false"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "forwards to inner handler when probe header is not 'probe'",
		options: []interface{}{
			prober.WithHeader(ProbeHeaderName, "queue"),
			prober.WithHeader(HashHeaderName, "foo-bar-baz"),
			prober.ExpectsBody(body),
			prober.ExpectsHeader(ProbeHeaderName, "true"),
			// Validates the header is stripped before forwarding to the inner handler
			prober.ExpectsHeader(HashHeaderName, "false"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "failed probe when hash header is not present",
		options: []interface{}{
			prober.WithHeader(ProbeHeaderName, ProbeHeaderValue),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want:   false,
		expErr: true,
	}}

	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, ok := r.Header[ProbeHeaderName]
		w.Header().Set(ProbeHeaderName, fmt.Sprintf("%t", ok))
		_, ok = r.Header[HashHeaderName]
		w.Header().Set(HashHeaderName, fmt.Sprintf("%t", ok))
		w.Write([]byte(body))
	})
	h = NewProbeHandler(h)
	ts := httptest.NewServer(h)
	defer ts.Close()

	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := prober.Do(context.Background(), network.AutoTransport, ts.URL, c.options...)
			if err != nil && !c.expErr {
				t.Errorf("prober.Do() = %v, no error expected", err)
			}
			if err == nil && c.expErr {
				t.Errorf("prober.Do() = nil, expected an error")
			}
			if got != c.want {
				t.Errorf("unexpected probe result: want: %t, got: %t", c.want, got)
			}
		})
	}
}
<commit_msg>Add benchmark for network probe handler (#6797)<commit_after>/*
Copyright 2019 The Knative 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 network

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"knative.dev/pkg/network"
	"knative.dev/pkg/network/prober"
	_ "knative.dev/pkg/system/testing"
)

func TestProbeHandlerSuccessfulProbe(t *testing.T) {
	body := "Inner Body"
	cases := []struct {
		name    string
		options []interface{}
		want    bool
		expErr  bool
	}{{
		name: "successful probe when both headers are specified",
		options: []interface{}{
			prober.WithHeader(ProbeHeaderName, ProbeHeaderValue),
			prober.WithHeader(HashHeaderName, "foo-bar-baz"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "forwards to inner handler when probe header is not specified",
		options: []interface{}{
			prober.WithHeader(HashHeaderName, "foo-bar-baz"),
			prober.ExpectsBody(body),
			// Validates the header is stripped before forwarding to the inner handler
			prober.ExpectsHeader(HashHeaderName, "false"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "forwards to inner handler when probe header is not 'probe'",
		options: []interface{}{
			prober.WithHeader(ProbeHeaderName, "queue"),
			prober.WithHeader(HashHeaderName, "foo-bar-baz"),
			prober.ExpectsBody(body),
			prober.ExpectsHeader(ProbeHeaderName, "true"),
			// Validates the header is stripped before forwarding to the inner handler
			prober.ExpectsHeader(HashHeaderName, "false"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "failed probe when hash header is not present",
		options: []interface{}{
			prober.WithHeader(ProbeHeaderName, ProbeHeaderValue),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want:   false,
		expErr: true,
	}}

	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, ok := r.Header[ProbeHeaderName]
		w.Header().Set(ProbeHeaderName, fmt.Sprintf("%t", ok))
		_, ok = r.Header[HashHeaderName]
		w.Header().Set(HashHeaderName, fmt.Sprintf("%t", ok))
		w.Write([]byte(body))
	})
	h = NewProbeHandler(h)
	ts := httptest.NewServer(h)
	defer ts.Close()

	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := prober.Do(context.Background(), network.AutoTransport, ts.URL, c.options...)
			if err != nil && !c.expErr {
				t.Errorf("prober.Do() = %v, no error expected", err)
			}
			if err == nil && c.expErr {
				t.Errorf("prober.Do() = nil, expected an error")
			}
			if got != c.want {
				t.Errorf("Unexpected probe result: want: %t, got: %t", c.want, got)
			}
		})
	}
}

func BenchmarkProbeHandler(b *testing.B) {
	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Inner Body"))
	})
	h = NewProbeHandler(h)
	ts := httptest.NewServer(h)
	defer ts.Close()
	options := []interface{}{
		prober.ExpectsStatusCodes([]int{http.StatusOK}),
	}

	b.Run(fmt.Sprint("sequential"), func(b *testing.B) {
		for j := 0; j < b.N; j++ {
			got, err := prober.Do(context.Background(), network.AutoTransport, ts.URL, options...)
			if err != nil {
				b.Errorf("Do = %v", err)
			}
			if !got {
				b.Errorf("Unexpected probe result: got: %t, want: true", got)
			}
		}
	})

	b.Run(fmt.Sprint("parallel"), func(b *testing.B) {
		b.RunParallel(func(pb *testing.PB) {
			for pb.Next() {
				got, err := prober.Do(context.Background(), network.AutoTransport, ts.URL, options...)
				if err != nil {
					b.Errorf("Do = %v", err)
				}
				if !got {
					b.Errorf("Unexpected probe result: got: %t, want: true", got)
				}
			}
		})
	})
}
<|endoftext|>


<commit_before>// +build providerless

/*
Copyright 2016 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 auth

import (
	// Initialize common client auth plugins.
	_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
)
<commit_msg>Common auth plugins should always be available<commit_after>/*
Copyright 2016 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 auth

import (
	// Initialize common client auth plugins.
	_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
)
<|endoftext|>


<commit_before>package prescription_test

import (
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"syreclabs.com/go/faker"

	"github.com/tidepool-org/platform/structure"
	"github.com/tidepool-org/platform/structure/validator"
	userTest "github.com/tidepool-org/platform/user/test"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/tidepool-org/platform/prescription/test"
	"github.com/tidepool-org/platform/user"

	"github.com/tidepool-org/platform/prescription"
)

var _ = Describe("Prescription", func() {
	Context("With a submitted revision", func() {
		var revisionCreate *prescription.RevisionCreate
		var userID string

		BeforeEach(func() {
			revisionCreate = test.RandomRevisionCreate()
			revisionCreate.State = prescription.StateSubmitted
			userID = user.NewID()
		})

		Context("Create new prescription", func() {
			var prescr *prescription.Prescription

			BeforeEach(func() {
				prescr = prescription.NewPrescription(userID, revisionCreate)
				Expect(prescr).ToNot(BeNil())
			})

			It("creates a non-empty id", func() {
				Expect(prescr.ID).ToNot(BeEmpty())
			})

			It("does not set the patientId", func() {
				Expect(prescr.PatientUserID).To(BeEmpty())
			})

			It("generates a non-empty access code", func() {
				Expect(prescr.AccessCode).ToNot(BeEmpty())
			})

			It("sets the state to the revision state", func() {
				Expect(prescr.State).To(Equal(revisionCreate.State))
			})

			It("sets the latest revision attribute to new revision", func() {
				Expect(prescr.LatestRevision).ToNot(BeNil())
			})

			It("populates the revision history with the newly created revision", func() {
				Expect(prescr.RevisionHistory).ToNot(BeEmpty())
				Expect(prescr.RevisionHistory[0]).To(Equal(prescr.LatestRevision))
			})

			It("sets the created user id correctly", func() {
				Expect(prescr.CreatedUserID).To(Equal(userID))
			})

			It("sets the prescriber user id correctly", func() {
				Expect(prescr.PrescriberUserID).To(Equal(userID))
			})

			It("sets the created time correctly", func() {
				Expect(prescr.CreatedTime).To(BeTemporally("~", time.Now()))
			})

			It("does not set the deleted time", func() {
				Expect(prescr.DeletedTime).To(BeNil())
			})

			It("does not set the deleted user id", func() {
				Expect(prescr.DeletedUserID).To(Equal(""))
			})

			It("creates a revision with id 0", func() {
				Expect(prescr.LatestRevision.RevisionID).To(Equal(0))
			})

			It("sets the modified time", func() {
				Expect(prescr.ModifiedTime).To(BeTemporally("~", time.Now()))
			})

			It("sets the modified time", func() {
				Expect(prescr.ModifiedUserID).To(Equal(userID))
			})
		})
	})

	Describe("Update", func() {
		var revisionCreate *prescription.RevisionCreate
		var usr *user.User

		BeforeEach(func() {
			revisionCreate = test.RandomRevisionCreate()
			revisionCreate.State = prescription.StatePending
			usr = userTest.RandomUser()
		})

		Describe("AddRevision", func() {
			var prescr *prescription.Prescription
			var newRevision *prescription.RevisionCreate
			var update *prescription.Update

			BeforeEach(func() {
				prescr = prescription.NewPrescription(*usr.UserID, revisionCreate)
				newRevision = test.RandomRevisionCreate()
				update = prescription.NewPrescriptionAddRevisionUpdate(usr, prescr, newRevision)
			})

			It("sets the revision correctly", func() {
				expectedRevision := prescription.NewRevision(*usr.UserID, prescr.LatestRevision.RevisionID+1, newRevision)
				expectedRevision.Attributes.CreatedTime = update.Revision.Attributes.CreatedTime
				Expect(*update.Revision).To(Equal(*expectedRevision))
			})

			It("sets the state correctly", func() {
				Expect(update.State).To(Equal(newRevision.State))
			})

			It("sets the prescriber id correctly", func() {
				Expect(update.PrescriberUserID).To(Equal(*usr.UserID))
			})

			It("doesn't set the patient id", func() {
				Expect(update.PatientUserID).To(BeEmpty())
			})

			It("sets the expiration time", func() {
				Expect(*update.ExpirationTime).To(BeTemporally(">", time.Now()))
			})

			It("sets the modified time", func() {
				Expect(update.ModifiedTime).To(BeTemporally("~", time.Now(), 10*time.Millisecond))
			})

			It("sets the modified user id", func() {
				Expect(update.ModifiedUserID).To(Equal(*usr.UserID))
			})
		})

		Describe("ClaimUpdate", func() {
			var prescr *prescription.Prescription
			var update *prescription.Update

			BeforeEach(func() {
				revisionCreate.State = prescription.StateSubmitted
				prescr = prescription.NewPrescription(*usr.UserID, revisionCreate)
				update = prescription.NewPrescriptionClaimUpdate(usr, prescr)
			})

			It("sets the state to claimed", func() {
				Expect(update.State).To(Equal(prescription.StateClaimed))
			})

			It("sets the patient id correctly", func() {
				Expect(update.PatientUserID).To(Equal(*usr.UserID))
			})

			It("doesn't set the prescriber id", func() {
				Expect(update.PrescriberUserID).To(BeEmpty())
			})

			It("resets the expiration time", func() {
				Expect(update.ExpirationTime).To(BeNil())
			})

			It("sets the modified time", func() {
				Expect(update.ModifiedTime).To(BeTemporally("~", time.Now()))
			})

			It("sets the modified user id", func() {
				Expect(update.ModifiedUserID).To(Equal(*usr.UserID))
			})
		})

		Describe("StateUpdate", func() {
			var prescr *prescription.Prescription
			var update *prescription.Update

			BeforeEach(func() {
				revisionCreate.State = prescription.StateClaimed
				prescr = prescription.NewPrescription(*usr.UserID, revisionCreate)
				stateUpdate := prescription.NewStateUpdate()
				stateUpdate.State = prescription.StateActive
				update = prescription.NewPrescriptionStateUpdate(usr, prescr, stateUpdate)
			})

			It("doesn't create a new revision", func() {
				Expect(update.Revision).To(BeNil())
			})

			It("sets the state to claimed", func() {
				Expect(update.State).To(Equal(prescription.StateActive))
			})

			It("doesn't set a patient id", func() {
				Expect(update.PatientUserID).To(BeEmpty())
			})

			It("doesn't set the prescriber id", func() {
				Expect(update.PrescriberUserID).To(BeEmpty())
			})

			It("resets the expiration time", func() {
				Expect(update.ExpirationTime).To(BeNil())
			})

			It("sets the modified time", func() {
				Expect(update.ModifiedTime).To(BeTemporally("~", time.Now()))
			})

			It("sets the modified user id", func() {
				Expect(update.ModifiedUserID).To(Equal(*usr.UserID))
			})
		})
	})

	Describe("Filter", func() {
		Describe("Validate", func() {
			When("current user is NOT a clinician", func() {
				var usr *user.User
				var filter *prescription.Filter
				var validate structure.Validator

				BeforeEach(func() {
					usr = userTest.RandomUser()
					usr.Roles = &[]string{}

					var err error
					filter, err = prescription.NewFilter(usr)
					Expect(err).ToNot(HaveOccurred())

					validate = validator.New()
					Expect(validate.Validate(filter)).ToNot(HaveOccurred())
				})

				It("fails when patient id is not same as current user id", func() {
					patientID := userTest.RandomID()
					Expect(patientID).ToNot(Equal(filter.PatientUserID))
					filter.PatientUserID = patientID

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the state is draft", func() {
					filter.State = prescription.StateDraft

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the state is pending", func() {
					filter.State = prescription.StatePending

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the state is expired", func() {
					filter.State = prescription.StateExpired

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when the state is submitted", func() {
					filter.State = prescription.StateSubmitted

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is active", func() {
					filter.State = prescription.StateActive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is inactive", func() {
					filter.State = prescription.StateInactive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is claimed", func() {
					filter.State = prescription.StateClaimed

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the state is unrecognized", func() {
					filter.State = "invalid"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when patient email is set", func() {
					filter.PatientEmail = faker.Internet().Email()

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail with a valid id", func() {
					filter.ID = primitive.NewObjectID().Hex()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the id is 13 hex characters", func() {
					filter.ID = fmt.Sprintf("%sa", primitive.NewObjectID().Hex())

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the id contains non-hex character", func() {
					filter.ID = "507f1f77bcf86cd799439011z"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})
			})

			When("current user is a clinician", func() {
				var usr *user.User
				var filter *prescription.Filter
				var validate structure.Validator

				BeforeEach(func() {
					usr = userTest.RandomUser()
					usr.Roles = &[]string{user.RoleClinic}

					var err error
					filter, err = prescription.NewFilter(usr)
					Expect(err).ToNot(HaveOccurred())

					validate = validator.New()
					Expect(validate.Validate(filter)).ToNot(HaveOccurred())
				})

				It("fails when patient id is invalid", func() {
					filter.PatientUserID = "invalid"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when patient id invalid", func() {
					filter.PatientUserID = userTest.RandomID()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is draft", func() {
					filter.State = prescription.StateDraft

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is pending", func() {
					filter.State = prescription.StatePending

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is expired", func() {
					filter.State = prescription.StateExpired

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is submitted", func() {
					filter.State = prescription.StateSubmitted

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is active", func() {
					filter.State = prescription.StateActive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is inactive", func() {
					filter.State = prescription.StateInactive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is claimed", func() {
					filter.State = prescription.StateClaimed

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the state is unrecognized", func() {
					filter.State = "invalid"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when patient email is valid", func() {
					filter.PatientEmail = faker.Internet().Email()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when patient email is invalid", func() {
					filter.PatientEmail = "invalid-email.com"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when the patient email is valid", func() {
					filter.PatientEmail = faker.Internet().Email()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail with a valid id", func() {
					filter.ID = primitive.NewObjectID().Hex()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the id is 13 hex characters", func() {
					filter.ID = fmt.Sprintf("%sa", primitive.NewObjectID().Hex())

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the id contains non-hex character", func() {
					filter.ID = "507f1f77bcf86cd799439011z"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})
			})
		})
	})
})
<commit_msg>Fix randomly failing time comparison<commit_after>package prescription_test

import (
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"syreclabs.com/go/faker"

	"github.com/tidepool-org/platform/structure"
	"github.com/tidepool-org/platform/structure/validator"
	userTest "github.com/tidepool-org/platform/user/test"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/tidepool-org/platform/prescription/test"
	"github.com/tidepool-org/platform/user"

	"github.com/tidepool-org/platform/prescription"
)

var _ = Describe("Prescription", func() {
	Context("With a submitted revision", func() {
		var revisionCreate *prescription.RevisionCreate
		var userID string

		BeforeEach(func() {
			revisionCreate = test.RandomRevisionCreate()
			revisionCreate.State = prescription.StateSubmitted
			userID = user.NewID()
		})

		Context("Create new prescription", func() {
			var prescr *prescription.Prescription

			BeforeEach(func() {
				prescr = prescription.NewPrescription(userID, revisionCreate)
				Expect(prescr).ToNot(BeNil())
			})

			It("creates a non-empty id", func() {
				Expect(prescr.ID).ToNot(BeEmpty())
			})

			It("does not set the patientId", func() {
				Expect(prescr.PatientUserID).To(BeEmpty())
			})

			It("generates a non-empty access code", func() {
				Expect(prescr.AccessCode).ToNot(BeEmpty())
			})

			It("sets the state to the revision state", func() {
				Expect(prescr.State).To(Equal(revisionCreate.State))
			})

			It("sets the latest revision attribute to new revision", func() {
				Expect(prescr.LatestRevision).ToNot(BeNil())
			})

			It("populates the revision history with the newly created revision", func() {
				Expect(prescr.RevisionHistory).ToNot(BeEmpty())
				Expect(prescr.RevisionHistory[0]).To(Equal(prescr.LatestRevision))
			})

			It("sets the created user id correctly", func() {
				Expect(prescr.CreatedUserID).To(Equal(userID))
			})

			It("sets the prescriber user id correctly", func() {
				Expect(prescr.PrescriberUserID).To(Equal(userID))
			})

			It("sets the created time correctly", func() {
				Expect(prescr.CreatedTime).To(BeTemporally("~", time.Now()))
			})

			It("does not set the deleted time", func() {
				Expect(prescr.DeletedTime).To(BeNil())
			})

			It("does not set the deleted user id", func() {
				Expect(prescr.DeletedUserID).To(Equal(""))
			})

			It("creates a revision with id 0", func() {
				Expect(prescr.LatestRevision.RevisionID).To(Equal(0))
			})

			It("sets the modified time", func() {
				Expect(prescr.ModifiedTime).To(BeTemporally("~", time.Now()))
			})

			It("sets the modified time", func() {
				Expect(prescr.ModifiedUserID).To(Equal(userID))
			})
		})
	})

	Describe("Update", func() {
		var revisionCreate *prescription.RevisionCreate
		var usr *user.User

		BeforeEach(func() {
			revisionCreate = test.RandomRevisionCreate()
			revisionCreate.State = prescription.StatePending
			usr = userTest.RandomUser()
		})

		Describe("AddRevision", func() {
			var prescr *prescription.Prescription
			var newRevision *prescription.RevisionCreate
			var update *prescription.Update

			BeforeEach(func() {
				prescr = prescription.NewPrescription(*usr.UserID, revisionCreate)
				newRevision = test.RandomRevisionCreate()
				update = prescription.NewPrescriptionAddRevisionUpdate(usr, prescr, newRevision)
			})

			It("sets the revision correctly", func() {
				expectedRevision := prescription.NewRevision(*usr.UserID, prescr.LatestRevision.RevisionID+1, newRevision)
				expectedRevision.Attributes.CreatedTime = update.Revision.Attributes.CreatedTime
				Expect(*update.Revision).To(Equal(*expectedRevision))
			})

			It("sets the state correctly", func() {
				Expect(update.State).To(Equal(newRevision.State))
			})

			It("sets the prescriber id correctly", func() {
				Expect(update.PrescriberUserID).To(Equal(*usr.UserID))
			})

			It("doesn't set the patient id", func() {
				Expect(update.PatientUserID).To(BeEmpty())
			})

			It("sets the expiration time", func() {
				Expect(*update.ExpirationTime).To(BeTemporally(">", time.Now()))
			})

			It("sets the modified time", func() {
				Expect(update.ModifiedTime).To(BeTemporally("~", time.Now(), 10*time.Millisecond))
			})

			It("sets the modified user id", func() {
				Expect(update.ModifiedUserID).To(Equal(*usr.UserID))
			})
		})

		Describe("ClaimUpdate", func() {
			var prescr *prescription.Prescription
			var update *prescription.Update

			BeforeEach(func() {
				revisionCreate.State = prescription.StateSubmitted
				prescr = prescription.NewPrescription(*usr.UserID, revisionCreate)
				update = prescription.NewPrescriptionClaimUpdate(usr, prescr)
			})

			It("sets the state to claimed", func() {
				Expect(update.State).To(Equal(prescription.StateClaimed))
			})

			It("sets the patient id correctly", func() {
				Expect(update.PatientUserID).To(Equal(*usr.UserID))
			})

			It("doesn't set the prescriber id", func() {
				Expect(update.PrescriberUserID).To(BeEmpty())
			})

			It("resets the expiration time", func() {
				Expect(update.ExpirationTime).To(BeNil())
			})

			It("sets the modified time", func() {
				Expect(update.ModifiedTime).To(BeTemporally("~", time.Now(), time.Second))
			})

			It("sets the modified user id", func() {
				Expect(update.ModifiedUserID).To(Equal(*usr.UserID))
			})
		})

		Describe("StateUpdate", func() {
			var prescr *prescription.Prescription
			var update *prescription.Update

			BeforeEach(func() {
				revisionCreate.State = prescription.StateClaimed
				prescr = prescription.NewPrescription(*usr.UserID, revisionCreate)
				stateUpdate := prescription.NewStateUpdate()
				stateUpdate.State = prescription.StateActive
				update = prescription.NewPrescriptionStateUpdate(usr, prescr, stateUpdate)
			})

			It("doesn't create a new revision", func() {
				Expect(update.Revision).To(BeNil())
			})

			It("sets the state to claimed", func() {
				Expect(update.State).To(Equal(prescription.StateActive))
			})

			It("doesn't set a patient id", func() {
				Expect(update.PatientUserID).To(BeEmpty())
			})

			It("doesn't set the prescriber id", func() {
				Expect(update.PrescriberUserID).To(BeEmpty())
			})

			It("resets the expiration time", func() {
				Expect(update.ExpirationTime).To(BeNil())
			})

			It("sets the modified time", func() {
				Expect(update.ModifiedTime).To(BeTemporally("~", time.Now()))
			})

			It("sets the modified user id", func() {
				Expect(update.ModifiedUserID).To(Equal(*usr.UserID))
			})
		})
	})

	Describe("Filter", func() {
		Describe("Validate", func() {
			When("current user is NOT a clinician", func() {
				var usr *user.User
				var filter *prescription.Filter
				var validate structure.Validator

				BeforeEach(func() {
					usr = userTest.RandomUser()
					usr.Roles = &[]string{}

					var err error
					filter, err = prescription.NewFilter(usr)
					Expect(err).ToNot(HaveOccurred())

					validate = validator.New()
					Expect(validate.Validate(filter)).ToNot(HaveOccurred())
				})

				It("fails when patient id is not same as current user id", func() {
					patientID := userTest.RandomID()
					Expect(patientID).ToNot(Equal(filter.PatientUserID))
					filter.PatientUserID = patientID

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the state is draft", func() {
					filter.State = prescription.StateDraft

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the state is pending", func() {
					filter.State = prescription.StatePending

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the state is expired", func() {
					filter.State = prescription.StateExpired

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when the state is submitted", func() {
					filter.State = prescription.StateSubmitted

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is active", func() {
					filter.State = prescription.StateActive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is inactive", func() {
					filter.State = prescription.StateInactive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is claimed", func() {
					filter.State = prescription.StateClaimed

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the state is unrecognized", func() {
					filter.State = "invalid"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when patient email is set", func() {
					filter.PatientEmail = faker.Internet().Email()

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail with a valid id", func() {
					filter.ID = primitive.NewObjectID().Hex()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the id is 13 hex characters", func() {
					filter.ID = fmt.Sprintf("%sa", primitive.NewObjectID().Hex())

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the id contains non-hex character", func() {
					filter.ID = "507f1f77bcf86cd799439011z"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})
			})

			When("current user is a clinician", func() {
				var usr *user.User
				var filter *prescription.Filter
				var validate structure.Validator

				BeforeEach(func() {
					usr = userTest.RandomUser()
					usr.Roles = &[]string{user.RoleClinic}

					var err error
					filter, err = prescription.NewFilter(usr)
					Expect(err).ToNot(HaveOccurred())

					validate = validator.New()
					Expect(validate.Validate(filter)).ToNot(HaveOccurred())
				})

				It("fails when patient id is invalid", func() {
					filter.PatientUserID = "invalid"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when patient id invalid", func() {
					filter.PatientUserID = userTest.RandomID()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is draft", func() {
					filter.State = prescription.StateDraft

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is pending", func() {
					filter.State = prescription.StatePending

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is expired", func() {
					filter.State = prescription.StateExpired

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is submitted", func() {
					filter.State = prescription.StateSubmitted

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is active", func() {
					filter.State = prescription.StateActive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is inactive", func() {
					filter.State = prescription.StateInactive

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail when the state is claimed", func() {
					filter.State = prescription.StateClaimed

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the state is unrecognized", func() {
					filter.State = "invalid"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when patient email is valid", func() {
					filter.PatientEmail = faker.Internet().Email()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when patient email is invalid", func() {
					filter.PatientEmail = "invalid-email.com"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("doesn't fail when the patient email is valid", func() {
					filter.PatientEmail = faker.Internet().Email()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("doesn't fail with a valid id", func() {
					filter.ID = primitive.NewObjectID().Hex()

					filter.Validate(validate)
					Expect(validate.Error()).ToNot(HaveOccurred())
				})

				It("fails when the id is 13 hex characters", func() {
					filter.ID = fmt.Sprintf("%sa", primitive.NewObjectID().Hex())

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})

				It("fails when the id contains non-hex character", func() {
					filter.ID = "507f1f77bcf86cd799439011z"

					filter.Validate(validate)
					Expect(validate.Error()).To(HaveOccurred())
				})
			})
		})
	})
})
<|endoftext|>


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

package main

import (
	"flag"
	"fmt"
	"http"
	"io"
	"log"
	"os"

	"goauth2.googlecode.com/hg/oauth"
)

var (
	code         = flag.String("code", "", "Authorization Code")
	token        = flag.String("token", "", "Access Token")
	clientId     = flag.String("id", "", "Client ID")
	clientSecret = flag.String("secret", "", "Client Secret")
)

const activities = "https://www.googleapis.com/buzz/v1/activities/@me/@public?max-results=1"

func main() {
	flag.Parse()
	rt := &oauth.Transport{
		ClientId:     *clientId,
		ClientSecret: *clientSecret,
		Scope:        "https://www.googleapis.com/auth/buzz",
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
	}
	if *code == "" && *token == "" {
		url := rt.AuthorizeURL()
		fmt.Println("Visit this URL to get a code:")
		fmt.Println(url)
		return
	}
	if *token == "" {
		_, err := rt.Exchange(*code)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		rt.Credentials = &oauth.Credentials{
			AccessToken: *token,
		}
	}
	c := &http.Client{rt}
	r, _, err := c.Get(activities)
	if err != nil {
		log.Fatal(err)
	}
	io.Copy(os.Stdout, r.Body)
	r.Body.Close()
	fmt.Println()
	fmt.Println("Access Token:", rt.Credentials.AccessToken)
}
<commit_msg>Cleaner example code<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This program makes a call to the buzz API, authenticated with OAuth2.
package main

import (
	"flag"
	"fmt"
	"http"
	"io"
	"log"
	"os"

	"goauth2.googlecode.com/hg/oauth"
)

var (
	code         = flag.String("code", "", "Authorization Code")
	token        = flag.String("token", "", "Access Token")
	clientId     = flag.String("id", "", "Client ID")
	clientSecret = flag.String("secret", "", "Client Secret")
)

const usageMsg = `
You must specify at least -id and -secret.
To obtain these details, see the "OAuth 2 Credentials" section under
the "API Access" tab on this page: https://code.google.com/apis/console/
`

const activities = "https://www.googleapis.com/buzz/v1/activities/@me/@public?max-results=1&alt=json"

func main() {
	flag.Parse()
	if *clientId == "" || *clientSecret == "" {
		flag.Usage()
		fmt.Fprint(os.Stderr, usageMsg)
		return
	}

	// Set up a Transport for making OAuth2-authenticated calls
	rt := &oauth.Transport{
		ClientId:     *clientId,
		ClientSecret: *clientSecret,
		Scope:        "https://www.googleapis.com/auth/buzz",
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
	}

	// Step one, get an authorization code from the data provider.
	// ("Please ask the user if I can access this resource.")
	if *code == "" && *token == "" {
		url := rt.AuthorizeURL()
		fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE")
		fmt.Println(url)
		return
	}

	// Step two, exchange the authorization code for an access token.
	// ("Here's the code you gave the user, now give me a token!")
	if *token == "" {
		cred, err := rt.Exchange(*code)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Now run again with -token=%s\n", cred.AccessToken)
		// We needn't return here; the Transport is actually all set
		// up with the right credentials by this point (making the
		// following 'rt.Credentials = ...' line redundant).
		// The process has been split up to demonstrate how one might
		// set up Credentials that have been stored elsewhere.
		return
	}

	// Step three, make the actual request using the token to authenticate.
	// ("Here's the token, let me in!")
	rt.Credentials = &oauth.Credentials{
		AccessToken: *token,
		// If you were storing this information somewhere,
		// you'd want to store the RefreshToken field as well.
	}
	c := &http.Client{rt}
	r, _, err := c.Get(activities)
	if err != nil {
		log.Fatal(err)
	}
	defer r.Body.Close()
	io.Copy(os.Stdout, r.Body)
	fmt.Println()
}
<|endoftext|>


<commit_before>package chessboard

import "fmt"

var starting = [8][8]byte{
	{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
	{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
	{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
}

type Board struct {
	matrix [8][8]byte
}

func NewBoard() *Board {
	board := new(Board)
	board.matrix = starting
	return board
}

func (board Board) Piece(p Point) byte {
	return board.matrix[p.y][p.x]
}

func (board Board) Print() {
	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()

	for i := 0; i < 8; i++ {
		fmt.Print(" +")
		for j := 0; j < 8; j++ {
			fmt.Print("-+")
		}
		fmt.Println()
		fmt.Printf("%d|", i+1)
		for j := 0; j < 8; j++ {
			fmt.Printf("%c|", board.Piece(Point{i, j}))
		}
		fmt.Println(i + 1)
	}
	fmt.Print(" +")
	for i := 0; i < 8; i++ {
		fmt.Print("-+")
	}
	fmt.Println()

	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()
}
<commit_msg>Remove getter of piece<commit_after>package chessboard

import "fmt"

var starting = [8][8]byte{
	{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
	{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
	{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
	{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
}

type Board struct {
	matrix [8][8]byte
}

func NewBoard() *Board {
	board := new(Board)
	board.matrix = starting
	return board
}

func (board Board) Print() {
	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()

	for i := 0; i < 8; i++ {
		fmt.Print(" +")
		for j := 0; j < 8; j++ {
			fmt.Print("-+")
		}
		fmt.Println()
		fmt.Printf("%d|", i+1)
		for j := 0; j < 8; j++ {
			fmt.Printf("%c|", board.matrix[i][j])
		}
		fmt.Println(i + 1)
	}
	fmt.Print(" +")
	for i := 0; i < 8; i++ {
		fmt.Print("-+")
	}
	fmt.Println()

	fmt.Print(" ")
	for i := 0; i < 8; i++ {
		fmt.Printf(" %c", 'a'+i)
	}
	fmt.Println()
}
<|endoftext|>


<commit_before>// Types passed and returned to and from the API

package api

import "time"

const (
	timeFormat = `"` + time.RFC3339 + `"`
)

// Error is returned from one drive when things go wrong
type Error struct {
	ErrorInfo struct {
		Code       string `json:"code"`
		Message    string `json:"message"`
		InnerError struct {
			Code string `json:"code"`
		} `json:"innererror"`
	} `json:"error"`
}

// Error returns a string for the error and statistifes the error interface
func (e *Error) Error() string {
	out := e.ErrorInfo.Code
	if e.ErrorInfo.InnerError.Code != "" {
		out += ": " + e.ErrorInfo.InnerError.Code
	}
	out += ": " + e.ErrorInfo.Message
	return out
}

// Check Error statisfies the error interface
var _ error = (*Error)(nil)

// Identity represents an identity of an actor. For example, and actor
// can be a user, device, or application.
type Identity struct {
	DisplayName string `json:"displayName"`
	ID          string `json:"id"`
}

// IdentitySet is a keyed collection of Identity objects. It is used
// to represent a set of identities associated with various events for
// an item, such as created by or last modified by.
type IdentitySet struct {
	User        Identity `json:"user"`
	Application Identity `json:"application"`
	Device      Identity `json:"device"`
}

// Quota groups storage space quota-related information on OneDrive into a single structure.
type Quota struct {
	Total     int    `json:"total"`
	Used      int    `json:"used"`
	Remaining int    `json:"remaining"`
	Deleted   int    `json:"deleted"`
	State     string `json:"state"` // normal | nearing | critical | exceeded
}

// Drive is a representation of a drive resource
type Drive struct {
	ID        string      `json:"id"`
	DriveType string      `json:"driveType"`
	Owner     IdentitySet `json:"owner"`
	Quota     Quota       `json:"quota"`
}

// Timestamp represents represents date and time information for the
// OneDrive API, by using ISO 8601 and is always in UTC time.
type Timestamp time.Time

// MarshalJSON turns a Timestamp into JSON (in UTC)
func (t *Timestamp) MarshalJSON() (out []byte, err error) {
	out = (*time.Time)(t).UTC().AppendFormat(out, timeFormat)
	return out, nil
}

// UnmarshalJSON turns JSON into a Timestamp
func (t *Timestamp) UnmarshalJSON(data []byte) error {
	newT, err := time.Parse(timeFormat, string(data))
	if err != nil {
		return err
	}
	*t = Timestamp(newT)
	return nil
}

// ItemReference groups data needed to reference a OneDrive item
// across the service into a single structure.
type ItemReference struct {
	DriveID string `json:"driveId"` // Unique identifier for the Drive that contains the item.	Read-only.
	ID      string `json:"id"`      // Unique identifier for the item.	Read/Write.
	Path    string `json:"path"`    // Path that used to navigate to the item.	Read/Write.
}

// FolderFacet groups folder-related data on OneDrive into a single structure
type FolderFacet struct {
	ChildCount int64 `json:"childCount"` // Number of children contained immediately within this container.
}

// HashesType groups different types of hashes into a single structure, for an item on OneDrive.
type HashesType struct {
	Sha1Hash  string `json:"sha1Hash"`  // base64 encoded SHA1 hash for the contents of the file (if available)
	Crc32Hash string `json:"crc32Hash"` // base64 encoded CRC32 value of the file (if available)
}

// FileFacet groups file-related data on OneDrive into a single structure.
type FileFacet struct {
	MimeType string     `json:"mimeType"` // The MIME type for the file. This is determined by logic on the server and might not be the value provided when the file was uploaded.
	Hashes   HashesType `json:"hashes"`   // Hashes of the file's binary content, if available.
}

// FileSystemInfoFacet contains properties that are reported by the
// device's local file system for the local version of an item. This
// facet can be used to specify the last modified date or created date
// of the item as it was on the local device.
type FileSystemInfoFacet struct {
	CreatedDateTime      Timestamp `json:"createdDateTime"`      // The UTC date and time the file was created on a client.
	LastModifiedDateTime Timestamp `json:"lastModifiedDateTime"` // The UTC date and time the file was last modified on a client.
}

// DeletedFacet indicates that the item on OneDrive has been
// deleted. In this version of the API, the presence (non-null) of the
// facet value indicates that the file was deleted. A null (or
// missing) value indicates that the file is not deleted.
type DeletedFacet struct {
}

// Item represents metadata for an item in OneDrive
type Item struct {
	ID                   string               `json:"id"`                   // The unique identifier of the item within the Drive. Read-only.
	Name                 string               `json:"name"`                 // The name of the item (filename and extension). Read-write.
	ETag                 string               `json:"eTag"`                 // eTag for the entire item (metadata + content). Read-only.
	CTag                 string               `json:"cTag"`                 // An eTag for the content of the item. This eTag is not changed if only the metadata is changed. Read-only.
	CreatedBy            IdentitySet          `json:"createdBy"`            // Identity of the user, device, and application which created the item. Read-only.
	LastModifiedBy       IdentitySet          `json:"lastModifiedBy"`       // Identity of the user, device, and application which last modified the item. Read-only.
	CreatedDateTime      Timestamp            `json:"createdDateTime"`      // Date and time of item creation. Read-only.
	LastModifiedDateTime Timestamp            `json:"lastModifiedDateTime"` // Date and time the item was last modified. Read-only.
	Size                 int64                `json:"size"`                 // Size of the item in bytes. Read-only.
	ParentReference      *ItemReference       `json:"parentReference"`      // Parent information, if the item has a parent. Read-write.
	WebURL               string               `json:"webUrl"`               // URL that displays the resource in the browser. Read-only.
	Description          string               `json:"description"`          // Provide a user-visible description of the item. Read-write.
	Folder               *FolderFacet         `json:"folder"`               // Folder metadata, if the item is a folder. Read-only.
	File                 *FileFacet           `json:"file"`                 // File metadata, if the item is a file. Read-only.
	FileSystemInfo       *FileSystemInfoFacet `json:"fileSystemInfo"`       // File system information on client. Read-write.
	//	Image                *ImageFacet          `json:"image"`                // Image metadata, if the item is an image. Read-only.
	//	Photo                *PhotoFacet          `json:"photo"`                // Photo metadata, if the item is a photo. Read-only.
	//	Audio                *AudioFacet          `json:"audio"`                // Audio metadata, if the item is an audio file. Read-only.
	//	Video                *VideoFacet          `json:"video"`                // Video metadata, if the item is a video. Read-only.
	//	Location             *LocationFacet       `json:"location"`             // Location metadata, if the item has location data. Read-only.
	Deleted *DeletedFacet `json:"deleted"` // Information about the deleted state of the item. Read-only.
}

// ViewDeltaResponse is the response to the view delta method
type ViewDeltaResponse struct {
	Value      []Item `json:"value"`            // An array of Item objects which have been created, modified, or deleted.
	NextLink   string `json:"@odata.nextLink"`  // A URL to retrieve the next available page of changes.
	DeltaLink  string `json:"@odata.deltaLink"` // A URL returned instead of @odata.nextLink after all current changes have been returned. Used to read the next set of changes in the future.
	DeltaToken string `json:"@delta.token"`     // A token value that can be used in the query string on manually-crafted calls to view.delta. Not needed if you're using nextLink and deltaLink.
}

// ListChildrenResponse is the response to the list children method
type ListChildrenResponse struct {
	Value    []Item `json:"value"`           // An array of Item objects
	NextLink string `json:"@odata.nextLink"` // A URL to retrieve the next available page of items.
}

// CreateItemRequest is the request to create an item object
type CreateItemRequest struct {
	Name             string      `json:"name"`                   // Name of the folder to be created.
	Folder           FolderFacet `json:"folder"`                 // Empty Folder facet to indicate that folder is the type of resource to be created.
	ConflictBehavior string      `json:"@name.conflictBehavior"` // Determines what to do if an item with a matching name already exists in this folder. Accepted values are: rename, replace, and fail (the default).
}

// SetFileSystemInfo is used to Update an object's FileSystemInfo.
type SetFileSystemInfo struct {
	FileSystemInfo FileSystemInfoFacet `json:"fileSystemInfo"` // File system information on client. Read-write.
}

// CreateUploadResponse is the response from creating an upload session
type CreateUploadResponse struct {
	UploadURL          string    `json:"uploadUrl"`          // "https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337",
	ExpirationDateTime Timestamp `json:"expirationDateTime"` // "2015-01-29T09:21:55.523Z",
	NextExpectedRanges []string  `json:"nextExpectedRanges"` // ["0-"]
}

// UploadFragmentResponse is the response from uploading a fragment
type UploadFragmentResponse struct {
	ExpirationDateTime Timestamp `json:"expirationDateTime"` // "2015-01-29T09:21:55.523Z",
	NextExpectedRanges []string  `json:"nextExpectedRanges"` // ["0-"]
}

// CopyItemRequest is the request to copy an item object
//
// Note: The parentReference should include either an id or path but
// not both. If both are included, they need to reference the same
// item or an error will occur.
type CopyItemRequest struct {
	ParentReference ItemReference `json:"parentReference"` // Reference to the parent item the copy will be created in.
	Name            *string       `json:"name"`            // Optional The new name for the copy. If this isn't provided, the same name will be used as the original.
}

// AsyncOperationStatus provides information on the status of a asynchronous job progress.
//
// The following API calls return AsyncOperationStatus resources:
//
// Copy Item
// Upload From URL
type AsyncOperationStatus struct {
	Operation          string  `json:"operation"`          // The type of job being run.
	PercentageComplete float64 `json:"percentageComplete"` // An float value between 0 and 100 that indicates the percentage complete.
	Status             string  `json:"status"`             // A string value that maps to an enumeration of possible values about the status of the job. "notStarted | inProgress | completed | updating | failed | deletePending | deleteFailed | waiting"
}
<commit_msg>Remove Go 1.5-ism to make compilable by go 1.3 & 1.4 - fixes #201<commit_after>// Types passed and returned to and from the API

package api

import "time"

const (
	timeFormat = `"` + time.RFC3339 + `"`
)

// Error is returned from one drive when things go wrong
type Error struct {
	ErrorInfo struct {
		Code       string `json:"code"`
		Message    string `json:"message"`
		InnerError struct {
			Code string `json:"code"`
		} `json:"innererror"`
	} `json:"error"`
}

// Error returns a string for the error and statistifes the error interface
func (e *Error) Error() string {
	out := e.ErrorInfo.Code
	if e.ErrorInfo.InnerError.Code != "" {
		out += ": " + e.ErrorInfo.InnerError.Code
	}
	out += ": " + e.ErrorInfo.Message
	return out
}

// Check Error statisfies the error interface
var _ error = (*Error)(nil)

// Identity represents an identity of an actor. For example, and actor
// can be a user, device, or application.
type Identity struct {
	DisplayName string `json:"displayName"`
	ID          string `json:"id"`
}

// IdentitySet is a keyed collection of Identity objects. It is used
// to represent a set of identities associated with various events for
// an item, such as created by or last modified by.
type IdentitySet struct {
	User        Identity `json:"user"`
	Application Identity `json:"application"`
	Device      Identity `json:"device"`
}

// Quota groups storage space quota-related information on OneDrive into a single structure.
type Quota struct {
	Total     int    `json:"total"`
	Used      int    `json:"used"`
	Remaining int    `json:"remaining"`
	Deleted   int    `json:"deleted"`
	State     string `json:"state"` // normal | nearing | critical | exceeded
}

// Drive is a representation of a drive resource
type Drive struct {
	ID        string      `json:"id"`
	DriveType string      `json:"driveType"`
	Owner     IdentitySet `json:"owner"`
	Quota     Quota       `json:"quota"`
}

// Timestamp represents represents date and time information for the
// OneDrive API, by using ISO 8601 and is always in UTC time.
type Timestamp time.Time

// MarshalJSON turns a Timestamp into JSON (in UTC)
func (t *Timestamp) MarshalJSON() (out []byte, err error) {
	timeString := (*time.Time)(t).UTC().Format(timeFormat)
	return []byte(timeString), nil
}

// UnmarshalJSON turns JSON into a Timestamp
func (t *Timestamp) UnmarshalJSON(data []byte) error {
	newT, err := time.Parse(timeFormat, string(data))
	if err != nil {
		return err
	}
	*t = Timestamp(newT)
	return nil
}

// ItemReference groups data needed to reference a OneDrive item
// across the service into a single structure.
type ItemReference struct {
	DriveID string `json:"driveId"` // Unique identifier for the Drive that contains the item.	Read-only.
	ID      string `json:"id"`      // Unique identifier for the item.	Read/Write.
	Path    string `json:"path"`    // Path that used to navigate to the item.	Read/Write.
}

// FolderFacet groups folder-related data on OneDrive into a single structure
type FolderFacet struct {
	ChildCount int64 `json:"childCount"` // Number of children contained immediately within this container.
}

// HashesType groups different types of hashes into a single structure, for an item on OneDrive.
type HashesType struct {
	Sha1Hash  string `json:"sha1Hash"`  // base64 encoded SHA1 hash for the contents of the file (if available)
	Crc32Hash string `json:"crc32Hash"` // base64 encoded CRC32 value of the file (if available)
}

// FileFacet groups file-related data on OneDrive into a single structure.
type FileFacet struct {
	MimeType string     `json:"mimeType"` // The MIME type for the file. This is determined by logic on the server and might not be the value provided when the file was uploaded.
	Hashes   HashesType `json:"hashes"`   // Hashes of the file's binary content, if available.
}

// FileSystemInfoFacet contains properties that are reported by the
// device's local file system for the local version of an item. This
// facet can be used to specify the last modified date or created date
// of the item as it was on the local device.
type FileSystemInfoFacet struct {
	CreatedDateTime      Timestamp `json:"createdDateTime"`      // The UTC date and time the file was created on a client.
	LastModifiedDateTime Timestamp `json:"lastModifiedDateTime"` // The UTC date and time the file was last modified on a client.
}

// DeletedFacet indicates that the item on OneDrive has been
// deleted. In this version of the API, the presence (non-null) of the
// facet value indicates that the file was deleted. A null (or
// missing) value indicates that the file is not deleted.
type DeletedFacet struct {
}

// Item represents metadata for an item in OneDrive
type Item struct {
	ID                   string               `json:"id"`                   // The unique identifier of the item within the Drive. Read-only.
	Name                 string               `json:"name"`                 // The name of the item (filename and extension). Read-write.
	ETag                 string               `json:"eTag"`                 // eTag for the entire item (metadata + content). Read-only.
	CTag                 string               `json:"cTag"`                 // An eTag for the content of the item. This eTag is not changed if only the metadata is changed. Read-only.
	CreatedBy            IdentitySet          `json:"createdBy"`            // Identity of the user, device, and application which created the item. Read-only.
	LastModifiedBy       IdentitySet          `json:"lastModifiedBy"`       // Identity of the user, device, and application which last modified the item. Read-only.
	CreatedDateTime      Timestamp            `json:"createdDateTime"`      // Date and time of item creation. Read-only.
	LastModifiedDateTime Timestamp            `json:"lastModifiedDateTime"` // Date and time the item was last modified. Read-only.
	Size                 int64                `json:"size"`                 // Size of the item in bytes. Read-only.
	ParentReference      *ItemReference       `json:"parentReference"`      // Parent information, if the item has a parent. Read-write.
	WebURL               string               `json:"webUrl"`               // URL that displays the resource in the browser. Read-only.
	Description          string               `json:"description"`          // Provide a user-visible description of the item. Read-write.
	Folder               *FolderFacet         `json:"folder"`               // Folder metadata, if the item is a folder. Read-only.
	File                 *FileFacet           `json:"file"`                 // File metadata, if the item is a file. Read-only.
	FileSystemInfo       *FileSystemInfoFacet `json:"fileSystemInfo"`       // File system information on client. Read-write.
	//	Image                *ImageFacet          `json:"image"`                // Image metadata, if the item is an image. Read-only.
	//	Photo                *PhotoFacet          `json:"photo"`                // Photo metadata, if the item is a photo. Read-only.
	//	Audio                *AudioFacet          `json:"audio"`                // Audio metadata, if the item is an audio file. Read-only.
	//	Video                *VideoFacet          `json:"video"`                // Video metadata, if the item is a video. Read-only.
	//	Location             *LocationFacet       `json:"location"`             // Location metadata, if the item has location data. Read-only.
	Deleted *DeletedFacet `json:"deleted"` // Information about the deleted state of the item. Read-only.
}

// ViewDeltaResponse is the response to the view delta method
type ViewDeltaResponse struct {
	Value      []Item `json:"value"`            // An array of Item objects which have been created, modified, or deleted.
	NextLink   string `json:"@odata.nextLink"`  // A URL to retrieve the next available page of changes.
	DeltaLink  string `json:"@odata.deltaLink"` // A URL returned instead of @odata.nextLink after all current changes have been returned. Used to read the next set of changes in the future.
	DeltaToken string `json:"@delta.token"`     // A token value that can be used in the query string on manually-crafted calls to view.delta. Not needed if you're using nextLink and deltaLink.
}

// ListChildrenResponse is the response to the list children method
type ListChildrenResponse struct {
	Value    []Item `json:"value"`           // An array of Item objects
	NextLink string `json:"@odata.nextLink"` // A URL to retrieve the next available page of items.
}

// CreateItemRequest is the request to create an item object
type CreateItemRequest struct {
	Name             string      `json:"name"`                   // Name of the folder to be created.
	Folder           FolderFacet `json:"folder"`                 // Empty Folder facet to indicate that folder is the type of resource to be created.
	ConflictBehavior string      `json:"@name.conflictBehavior"` // Determines what to do if an item with a matching name already exists in this folder. Accepted values are: rename, replace, and fail (the default).
}

// SetFileSystemInfo is used to Update an object's FileSystemInfo.
type SetFileSystemInfo struct {
	FileSystemInfo FileSystemInfoFacet `json:"fileSystemInfo"` // File system information on client. Read-write.
}

// CreateUploadResponse is the response from creating an upload session
type CreateUploadResponse struct {
	UploadURL          string    `json:"uploadUrl"`          // "https://sn3302.up.1drv.com/up/fe6987415ace7X4e1eF866337",
	ExpirationDateTime Timestamp `json:"expirationDateTime"` // "2015-01-29T09:21:55.523Z",
	NextExpectedRanges []string  `json:"nextExpectedRanges"` // ["0-"]
}

// UploadFragmentResponse is the response from uploading a fragment
type UploadFragmentResponse struct {
	ExpirationDateTime Timestamp `json:"expirationDateTime"` // "2015-01-29T09:21:55.523Z",
	NextExpectedRanges []string  `json:"nextExpectedRanges"` // ["0-"]
}

// CopyItemRequest is the request to copy an item object
//
// Note: The parentReference should include either an id or path but
// not both. If both are included, they need to reference the same
// item or an error will occur.
type CopyItemRequest struct {
	ParentReference ItemReference `json:"parentReference"` // Reference to the parent item the copy will be created in.
	Name            *string       `json:"name"`            // Optional The new name for the copy. If this isn't provided, the same name will be used as the original.
}

// AsyncOperationStatus provides information on the status of a asynchronous job progress.
//
// The following API calls return AsyncOperationStatus resources:
//
// Copy Item
// Upload From URL
type AsyncOperationStatus struct {
	Operation          string  `json:"operation"`          // The type of job being run.
	PercentageComplete float64 `json:"percentageComplete"` // An float value between 0 and 100 that indicates the percentage complete.
	Status             string  `json:"status"`             // A string value that maps to an enumeration of possible values about the status of the job. "notStarted | inProgress | completed | updating | failed | deletePending | deleteFailed | waiting"
}
<|endoftext|>


<commit_before>package main

import "testing"

func TestSomethingExciting(t *testing.T) {
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // OK
	}
	doStuffTo(transport)
}

func doStuffTo(t *http.Transport) {}
<commit_msg>Fix frontend errors in `DisabledCertificateCheck` tests.<commit_after>package main

import (
	"crypto/tls"
	"net/http"
	"testing"
)

func TestSomethingExciting(t *testing.T) {
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // OK
	}
	doStuffTo(transport)
}

func doStuffTo(t *http.Transport) {}
<|endoftext|>


<commit_before>package generator

import (
	"errors"
	"fmt"
	"go/ast"

	"github.com/momchil-atanasov/gostub/resolution"
	"github.com/momchil-atanasov/gostub/util"
)

// Config is used to pass a rather large configuration to the
// Generate method.
type Config struct {

	// SourcePackageLocation specifies the location
	// (e.g. "github.com/momchil-atanasov/gostub") where the interface
	// to be stubbed is located.
	SourcePackageLocation string

	// SourceInterfaceName specifies the name of the interface to be stubbed
	SourceInterfaceName string

	// TargetFilePath specifies the file in which the stub will be saved.
	TargetFilePath string

	// TargetPackageName specifies the name of the package in which the
	// stub will be saved. Ideally, this should equal the last segment of
	// the TargetPackageLocation (e.g. "gostub_stubs")
	TargetPackageName string

	// TargetStructName specifies the name of the stub structure
	// that will implement the interface
	TargetStructName string
}

func Generate(config Config) error {
	locator := resolution.NewLocator()

	// Do an initial search only with what we have as input
	context := resolution.NewSingleLocationContext(config.SourcePackageLocation)
	discovery, err := locator.FindIdentType(context, ast.NewIdent(config.SourceInterfaceName))
	if err != nil {
		return err
	}

	model := NewGeneratorModel(config.TargetPackageName, config.TargetStructName)
	stubGen := newGenerator(model, locator)
	err = stubGen.ProcessInterface(discovery)
	if err != nil {
		return err
	}

	err = model.Save(config.TargetFilePath)
	if err != nil {
		return err
	}

	fmt.Printf("Stub '%s' successfully created in '%s'.\n", config.TargetStructName, config.TargetFilePath)
	return nil
}

func newGenerator(model *GeneratorModel, locator *resolution.Locator) *stubGenerator {
	return &stubGenerator{
		model:    model,
		locator:  locator,
		resolver: NewResolver(model, locator),
	}
}

type stubGenerator struct {
	model    *GeneratorModel
	locator  *resolution.Locator
	resolver *Resolver
}

func (g *stubGenerator) ProcessInterface(discovery resolution.TypeDiscovery) error {
	context := resolution.NewASTFileLocatorContext(discovery.File, discovery.Location)
	g.resolver.SetLocatorContext(context)
	iFaceType, isIFace := discovery.Spec.Type.(*ast.InterfaceType)
	if !isIFace {
		return errors.New(fmt.Sprintf("Type '%s' in '%s' is not interface!", discovery.Spec.Name.String(), discovery.Location))
	}
	for method := range util.EachMethodInInterfaceType(iFaceType) {
		funcType := method.Type.(*ast.FuncType)
		source := &MethodConfig{
			MethodName:    method.Names[0].String(),
			MethodParams:  g.getNormalizedParams(funcType),
			MethodResults: g.getNormalizedResults(funcType),
		}
		err := g.model.AddMethod(source)
		if err != nil {
			return err
		}
	}
	for subIFaceType := range util.EachSubInterfaceInInterfaceType(iFaceType) {
		switch t := subIFaceType.Type.(type) {
		case *ast.Ident:
			discovery, err := g.locator.FindIdentType(context, t)
			if err != nil {
				return err
			}
			err = g.ProcessInterface(discovery)
			if err != nil {
				return err
			}
		case *ast.SelectorExpr:
			discovery, err := g.locator.FindSelectorType(context, t)
			if err != nil {
				return err
			}
			err = g.ProcessInterface(discovery)
			if err != nil {
				return err
			}
		default:
			panic("Unknown statement in interface declaration.")
		}
	}
	return nil
}

func (g *stubGenerator) getNormalizedParams(funcType *ast.FuncType) []*ast.Field {
	normalizedParams := []*ast.Field{}
	paramIndex := 1
	for param := range util.EachFieldInFieldList(funcType.Params) {
		count := util.FieldTypeReuseCount(param)
		for i := 0; i < count; i++ {
			fieldName := fmt.Sprintf("arg%d", paramIndex)
			fieldType, _ := g.resolver.ResolveType(param.Type)
			normalizedParam := util.CreateField(fieldName, fieldType)
			normalizedParams = append(normalizedParams, normalizedParam)
			paramIndex++
		}
	}
	return normalizedParams
}

func (g *stubGenerator) getNormalizedResults(funcType *ast.FuncType) []*ast.Field {
	normalizedResults := []*ast.Field{}
	resultIndex := 1
	for result := range util.EachFieldInFieldList(funcType.Results) {
		count := util.FieldTypeReuseCount(result)
		for i := 0; i < count; i++ {
			fieldName := fmt.Sprintf("result%d", resultIndex)
			fieldType, _ := g.resolver.ResolveType(result.Type)
			normalizedResult := util.CreateField(fieldName, fieldType)
			normalizedResults = append(normalizedResults, normalizedResult)
			resultIndex++
		}
	}
	return normalizedResults
}
<commit_msg>Improve error handling<commit_after>package generator

import (
	"errors"
	"fmt"
	"go/ast"

	"github.com/momchil-atanasov/gostub/resolution"
	"github.com/momchil-atanasov/gostub/util"
)

// Config is used to pass a rather large configuration to the
// Generate method.
type Config struct {

	// SourcePackageLocation specifies the location
	// (e.g. "github.com/momchil-atanasov/gostub") where the interface
	// to be stubbed is located.
	SourcePackageLocation string

	// SourceInterfaceName specifies the name of the interface to be stubbed
	SourceInterfaceName string

	// TargetFilePath specifies the file in which the stub will be saved.
	TargetFilePath string

	// TargetPackageName specifies the name of the package in which the
	// stub will be saved. Ideally, this should equal the last segment of
	// the TargetPackageLocation (e.g. "gostub_stubs")
	TargetPackageName string

	// TargetStructName specifies the name of the stub structure
	// that will implement the interface
	TargetStructName string
}

func Generate(config Config) error {
	locator := resolution.NewLocator()

	// Do an initial search only with what we have as input
	context := resolution.NewSingleLocationContext(config.SourcePackageLocation)
	discovery, err := locator.FindIdentType(context, ast.NewIdent(config.SourceInterfaceName))
	if err != nil {
		return err
	}

	model := NewGeneratorModel(config.TargetPackageName, config.TargetStructName)
	stubGen := newGenerator(model, locator)
	err = stubGen.ProcessInterface(discovery)
	if err != nil {
		return err
	}

	err = model.Save(config.TargetFilePath)
	if err != nil {
		return err
	}

	fmt.Printf("Stub '%s' successfully created in '%s'.\n", config.TargetStructName, config.TargetFilePath)
	return nil
}

func newGenerator(model *GeneratorModel, locator *resolution.Locator) *stubGenerator {
	return &stubGenerator{
		model:    model,
		locator:  locator,
		resolver: NewResolver(model, locator),
	}
}

type stubGenerator struct {
	model    *GeneratorModel
	locator  *resolution.Locator
	resolver *Resolver
}

func (g *stubGenerator) ProcessInterface(discovery resolution.TypeDiscovery) error {
	context := resolution.NewASTFileLocatorContext(discovery.File, discovery.Location)
	g.resolver.SetLocatorContext(context)
	iFaceType, isIFace := discovery.Spec.Type.(*ast.InterfaceType)
	if !isIFace {
		return errors.New(fmt.Sprintf("Type '%s' in '%s' is not interface!", discovery.Spec.Name.String(), discovery.Location))
	}
	for method := range util.EachMethodInInterfaceType(iFaceType) {
		funcType := method.Type.(*ast.FuncType)
		normalizedParams, err := g.getNormalizedParams(funcType)
		if err != nil {
			return err
		}
		normalizedResults, err := g.getNormalizedResults(funcType)
		if err != nil {
			return err
		}
		source := &MethodConfig{
			MethodName:    method.Names[0].String(),
			MethodParams:  normalizedParams,
			MethodResults: normalizedResults,
		}
		err = g.model.AddMethod(source)
		if err != nil {
			return err
		}
	}
	for subIFaceType := range util.EachSubInterfaceInInterfaceType(iFaceType) {
		switch t := subIFaceType.Type.(type) {
		case *ast.Ident:
			discovery, err := g.locator.FindIdentType(context, t)
			if err != nil {
				return err
			}
			err = g.ProcessInterface(discovery)
			if err != nil {
				return err
			}
		case *ast.SelectorExpr:
			discovery, err := g.locator.FindSelectorType(context, t)
			if err != nil {
				return err
			}
			err = g.ProcessInterface(discovery)
			if err != nil {
				return err
			}
		default:
			return errors.New("Unknown statement in interface declaration.")
		}
	}
	return nil
}

func (g *stubGenerator) getNormalizedParams(funcType *ast.FuncType) ([]*ast.Field, error) {
	normalizedParams := []*ast.Field{}
	paramIndex := 1
	for param := range util.EachFieldInFieldList(funcType.Params) {
		count := util.FieldTypeReuseCount(param)
		for i := 0; i < count; i++ {
			fieldName := fmt.Sprintf("arg%d", paramIndex)
			fieldType, err := g.resolver.ResolveType(param.Type)
			if err != nil {
				return nil, err
			}
			normalizedParam := util.CreateField(fieldName, fieldType)
			normalizedParams = append(normalizedParams, normalizedParam)
			paramIndex++
		}
	}
	return normalizedParams, nil
}

func (g *stubGenerator) getNormalizedResults(funcType *ast.FuncType) ([]*ast.Field, error) {
	normalizedResults := []*ast.Field{}
	resultIndex := 1
	for result := range util.EachFieldInFieldList(funcType.Results) {
		count := util.FieldTypeReuseCount(result)
		for i := 0; i < count; i++ {
			fieldName := fmt.Sprintf("result%d", resultIndex)
			fieldType, err := g.resolver.ResolveType(result.Type)
			if err != nil {
				return nil, err
			}
			normalizedResult := util.CreateField(fieldName, fieldType)
			normalizedResults = append(normalizedResults, normalizedResult)
			resultIndex++
		}
	}
	return normalizedResults, nil
}
<|endoftext|>


<commit_before>package params

import (
	"fmt"
)

const (
	// VersionMajor is a major version component of the current release
	VersionMajor = 0

	// VersionMinor is a minor version component of the current release
	VersionMinor = 9

	// VersionPatch is a patch version component of the current release
	VersionPatch = 8

	// VersionMeta is metadata to append to the version string
	VersionMeta = "unstable"
)

// Version exposes string representation of program version.
var Version = fmt.Sprintf("%d.%d.%d-%s", VersionMajor, VersionMinor, VersionPatch, VersionMeta)
<commit_msg>Started 0.9.9-unstable<commit_after>package params

import (
	"fmt"
)

const (
	// VersionMajor is a major version component of the current release
	VersionMajor = 0

	// VersionMinor is a minor version component of the current release
	VersionMinor = 9

	// VersionPatch is a patch version component of the current release
	VersionPatch = 9

	// VersionMeta is metadata to append to the version string
	VersionMeta = "unstable"
)

// Version exposes string representation of program version.
var Version = fmt.Sprintf("%d.%d.%d-%s", VersionMajor, VersionMinor, VersionPatch, VersionMeta)
<|endoftext|>


<commit_before>// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp

import (
	"context"
	"net/http"

	"github.com/caddyserver/caddy/v2"
)

func init() {
	caddy.RegisterModule(VarsMiddleware{})
	caddy.RegisterModule(VarsMatcher{})
}

// VarsMiddleware is an HTTP middleware which sets variables
// in the context, mainly for use by placeholders. The
// placeholders have the form: `{http.vars.variable_name}`
type VarsMiddleware map[string]string

// CaddyModule returns the Caddy module information.
func (VarsMiddleware) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.vars",
		New: func() caddy.Module { return new(VarsMiddleware) },
	}
}

func (t VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
	vars := r.Context().Value(VarsCtxKey).(map[string]interface{})
	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
	for k, v := range t {
		keyExpanded := repl.ReplaceAll(k, "")
		valExpanded := repl.ReplaceAll(v, "")
		vars[keyExpanded] = valExpanded
	}
	return next.ServeHTTP(w, r)
}

// VarsMatcher is an HTTP request matcher which can match
// requests based on variables in the context.
type VarsMatcher map[string]string

// CaddyModule returns the Caddy module information.
func (VarsMatcher) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.matchers.vars",
		New: func() caddy.Module { return new(VarsMatcher) },
	}
}

// Match matches a request based on variables in the context.
func (m VarsMatcher) Match(r *http.Request) bool {
	vars := r.Context().Value(VarsCtxKey).(map[string]string)
	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
	for k, v := range m {
		keyExpanded := repl.ReplaceAll(k, "")
		valExpanded := repl.ReplaceAll(v, "")
		if vars[keyExpanded] != valExpanded {
			return false
		}
	}
	return true
}

// GetVar gets a value out of the context's variable table by key.
// If the key does not exist, the return value will be nil.
func GetVar(ctx context.Context, key string) interface{} {
	varMap, ok := ctx.Value(VarsCtxKey).(map[string]interface{})
	if !ok {
		return nil
	}
	return varMap[key]
}

// SetVar sets a value in the context's variable table with
// the given key. It overwrites any previous value with the
// same key.
func SetVar(ctx context.Context, key string, value interface{}) {
	varMap, ok := ctx.Value(VarsCtxKey).(map[string]interface{})
	if !ok {
		return
	}
	varMap[key] = value
}

// Interface guards
var (
	_ MiddlewareHandler = (*VarsMiddleware)(nil)
	_ RequestMatcher    = (*VarsMatcher)(nil)
)
<commit_msg>http: Fix vars matcher<commit_after>// Copyright 2015 Matthew Holt and The Caddy 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 caddyhttp

import (
	"context"
	"fmt"
	"net/http"

	"github.com/caddyserver/caddy/v2"
)

func init() {
	caddy.RegisterModule(VarsMiddleware{})
	caddy.RegisterModule(VarsMatcher{})
}

// VarsMiddleware is an HTTP middleware which sets variables
// in the context, mainly for use by placeholders. The
// placeholders have the form: `{http.vars.variable_name}`
type VarsMiddleware map[string]string

// CaddyModule returns the Caddy module information.
func (VarsMiddleware) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.handlers.vars",
		New: func() caddy.Module { return new(VarsMiddleware) },
	}
}

func (t VarsMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
	vars := r.Context().Value(VarsCtxKey).(map[string]interface{})
	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
	for k, v := range t {
		keyExpanded := repl.ReplaceAll(k, "")
		valExpanded := repl.ReplaceAll(v, "")
		vars[keyExpanded] = valExpanded
	}
	return next.ServeHTTP(w, r)
}

// VarsMatcher is an HTTP request matcher which can match
// requests based on variables in the context.
type VarsMatcher map[string]string

// CaddyModule returns the Caddy module information.
func (VarsMatcher) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "http.matchers.vars",
		New: func() caddy.Module { return new(VarsMatcher) },
	}
}

// Match matches a request based on variables in the context.
func (m VarsMatcher) Match(r *http.Request) bool {
	vars := r.Context().Value(VarsCtxKey).(map[string]interface{})
	repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
	for k, v := range m {
		keyExpanded := repl.ReplaceAll(k, "")
		valExpanded := repl.ReplaceAll(v, "")
		var varStr string
		switch vv := vars[keyExpanded].(type) {
		case string:
			varStr = vv
		case fmt.Stringer:
			varStr = vv.String()
		case error:
			varStr = vv.Error()
		default:
			varStr = fmt.Sprintf("%v", vv)
		}
		if varStr != valExpanded {
			return false
		}
	}
	return true
}

// GetVar gets a value out of the context's variable table by key.
// If the key does not exist, the return value will be nil.
func GetVar(ctx context.Context, key string) interface{} {
	varMap, ok := ctx.Value(VarsCtxKey).(map[string]interface{})
	if !ok {
		return nil
	}
	return varMap[key]
}

// SetVar sets a value in the context's variable table with
// the given key. It overwrites any previous value with the
// same key.
func SetVar(ctx context.Context, key string, value interface{}) {
	varMap, ok := ctx.Value(VarsCtxKey).(map[string]interface{})
	if !ok {
		return
	}
	varMap[key] = value
}

// Interface guards
var (
	_ MiddlewareHandler = (*VarsMiddleware)(nil)
	_ RequestMatcher    = (*VarsMatcher)(nil)
)
<|endoftext|>


<commit_before>package operator

import (
	"fmt"
	"github.com/beard1ess/gauss/parsing"
	"reflect"
	"strconv"
)

func recursion(

	original parsing.Keyvalue,
	modified parsing.Keyvalue,
	input_path []string,
	ObjectDiff parsing.ConsumableDifference,

) parsing.ConsumableDifference {

	path := make([]string, len(input_path))
	copy(path, input_path)
	if reflect.DeepEqual(original, modified) {
		return ObjectDiff
	}

	if !(parsing.UnorderedKeyMatch(original, modified)) {

		for k, v := range modified {
			if parsing.IndexOf(parsing.ListStripper(original), k) == -1 {
				added := parsing.AddedDifference{Path: parsing.PathFormatter(path), Key: k, Value: v}
				ObjectDiff.Added = append(ObjectDiff.Added, added)
				delete(modified, k)
			}
		}
		for k, v := range original {
			if parsing.IndexOf(parsing.ListStripper(modified), k) == -1 {
				removed := parsing.RemovedDifference{Path: parsing.PathFormatter(path), Key: k, Value: v}
				ObjectDiff.Removed = append(ObjectDiff.Removed, removed)
				delete(original, k)
			}
		}

		ObjectDiff = recursion(original, modified, path, ObjectDiff)
		return ObjectDiff

	} else if len(parsing.ListStripper(original)) > 1 || len(parsing.ListStripper(modified)) > 1 {

		for k := range original {
			ObjectDiff = recursion(
				parsing.Keyvalue{k: original[k]},
				parsing.Keyvalue{k: modified[k]},
				path, ObjectDiff)
		}
		return ObjectDiff
	} else {

		for k := range original {

			if !(reflect.DeepEqual(valMod, valOrig)) {
				// Specifically handle type mismatch
				if reflect.TypeOf(valOrig) != reflect.TypeOf(valMod) {

					changed := parsing.ChangedDifference{Path: parsing.PathFormatter(path),
						Key: k, OldValue: valOrig, NewValue: valMod}
					ObjectDiff.Changed = append(ObjectDiff.Changed, changed)
					return ObjectDiff

				} else if reflect.TypeOf(valOrig).Kind() == reflect.Map {

					path = append(path, k)
					ObjectDiff = recursion(parsing.Remarshal(valOrig), parsing.Remarshal(valMod), path, ObjectDiff)
					return ObjectDiff

				} else if reflect.TypeOf(valOrig).Kind() == reflect.Slice {

					// Variable setup
					var match bool
					valOrig, _ := valOrig.([]interface{})
					valMod, _ := valMod.([]interface{})
					path = append(path, k)
					npath := make([]string, len(path))

					if len(valOrig) != len(valMod) {
						// If slice length mismatches we need to handle that a particular way
						if len(valOrig) > len(valMod) {
							for i := range valOrig {
								for ii := range valMod {
									if reflect.DeepEqual(valOrig[i], valMod[ii]) {

										match = true

									} else if i == ii {

										iter := len(path) - 1
										path[iter] = path[iter] + "[" + strconv.Itoa(i) + "]"
										ObjectDiff = recursion(parsing.Remarshal(valOrig[i]), parsing.Remarshal(valMod[i]),
											path, ObjectDiff)

									}
								}
								if !(match) {
									removed := parsing.RemovedDifference{Path: parsing.PathFormatter(path),
										Key: k, Value: valOrig}
									ObjectDiff.Removed = append(ObjectDiff.Removed, removed)
								} else {
									match = false
								}
							}
							return ObjectDiff
						} else {
							for i := range valMod {
								for ii := range valOrig {
									if reflect.DeepEqual(valOrig[ii], valMod[i]) {
										match = true
									} else if i == ii {
										iter := len(path) - 1
										path[iter] = path[iter] + "[" + strconv.Itoa(i) + "]"
										ObjectDiff = recursion(parsing.Remarshal(valOrig[i]), parsing.Remarshal(valMod[i]),
											path, ObjectDiff)
									}
								}
								if !(match) {
									added := parsing.AddedDifference{Path: parsing.PathFormatter(path),
										Key: k, Value: valMod}
									ObjectDiff.Added = append(ObjectDiff.Added, added)

								} else {
									match = false
								}
							}
							return ObjectDiff
						}
					} else {
						// If both slice lengths are equal
						for i := range valOrig {
							copy(npath, path)
							if !(reflect.DeepEqual(valOrig[i], valMod[i])) {
								iter := len(npath) - 1
								npath[iter] = npath[iter] + "[" + strconv.Itoa(i) + "]"
								ObjectDiff = recursion(parsing.Remarshal(valOrig[i]), parsing.Remarshal(valMod[i]),
									npath, ObjectDiff)
							}
						}
						return ObjectDiff
					}
				} else {
					changed := parsing.ChangedDifference{Path: parsing.PathFormatter(path),
						Key: k, OldValue: valOrig, NewValue: valMod}
					ObjectDiff.Changed = append(ObjectDiff.Changed, changed)
					return ObjectDiff
				}
			}
		}
	}

func Recursion(original parsing.Keyvalue, modified parsing.Keyvalue, path []string) parsing.ConsumableDifference {
	var ObjectDiff = parsing.ConsumableDifference{}
	return recursion(original, modified, path, ObjectDiff)
}
<commit_msg>Pull recursion from master due to merge conflicts<commit_after>package operator

import (
	"github.com/beard1ess/gauss/parsing"
	"reflect"
	"strconv"
)

func recursion(

	original parsing.Keyvalue,
	modified parsing.Keyvalue,
	input_path []string,
	ObjectDiff parsing.ConsumableDifference,

) parsing.ConsumableDifference {

	path := make([]string, len(input_path))
	copy(path, input_path)
	if reflect.DeepEqual(original, modified) {
		return ObjectDiff
	}

	if !(parsing.UnorderedKeyMatch(original, modified)) {

		for k, v := range modified {
			if parsing.IndexOf(parsing.ListStripper(original), k) == -1 {
				added := parsing.AddedDifference{Path: parsing.PathFormatter(path), Key: k, Value: v}
				ObjectDiff.Added = append(ObjectDiff.Added, added)
				delete(modified, k)
			}
		}
		for k, v := range original {
			if parsing.IndexOf(parsing.ListStripper(modified), k) == -1 {
				removed := parsing.RemovedDifference{Path: parsing.PathFormatter(path), Key: k, Value: v}
				ObjectDiff.Removed = append(ObjectDiff.Removed, removed)
				delete(original, k)
			}
		}

		ObjectDiff = recursion(original, modified, path, ObjectDiff)
		return ObjectDiff

	} else if len(parsing.ListStripper(original)) > 1 || len(parsing.ListStripper(modified)) > 1 {

		for k := range original {
			ObjectDiff = recursion(
				parsing.Keyvalue{k: original[k]},
				parsing.Keyvalue{k: modified[k]},
				path, ObjectDiff)
		}
		return ObjectDiff
	} else {

		for k := range original {

			var valOrig, valMod interface{}
			if reflect.TypeOf(original).Kind() == reflect.String {
				valOrig = original
			} else {
				valOrig = original[k]
			}
			if reflect.TypeOf(modified).Kind() == reflect.String {
				valMod = modified
			} else {
				valMod = modified[k]
			}

			if !(reflect.DeepEqual(valMod, valOrig)) {
				// Specifically handle type mismatch
				if reflect.TypeOf(valOrig) != reflect.TypeOf(valMod) {

					changed := parsing.ChangedDifference{Path: parsing.PathFormatter(path),
						Key: k, OldValue: valOrig, NewValue: valMod}
					ObjectDiff.Changed = append(ObjectDiff.Changed, changed)
					return ObjectDiff

				} else if reflect.TypeOf(valOrig).Kind() == reflect.Map {

					path = append(path, k)
					ObjectDiff = recursion(parsing.Remarshal(valOrig), parsing.Remarshal(valMod), path, ObjectDiff)
					return ObjectDiff

				} else if reflect.TypeOf(valOrig).Kind() == reflect.Slice {

					// Variable setup
					var match bool
					valOrig, _ := valOrig.([]interface{})
					valMod, _ := valMod.([]interface{})
					path = append(path, k)
					npath := make([]string, len(path))

					if len(valOrig) != len(valMod) {
						// If slice length mismatches we need to handle that a particular way
						if len(valOrig) > len(valMod) {
							for i := range valOrig {
								for ii := range valMod {
									if reflect.DeepEqual(valOrig[i], valMod[ii]) {

										match = true

									} else if i == ii {

										iter := len(path) - 1
										path[iter] = path[iter] + "[" + strconv.Itoa(i) + "]"
										ObjectDiff = recursion(parsing.Remarshal(valOrig[i]), parsing.Remarshal(valMod[i]),
											path, ObjectDiff)

									}
								}
								if !(match) {
									removed := parsing.RemovedDifference{Path: parsing.PathFormatter(path),
										Key: k, Value: valOrig}
									ObjectDiff.Removed = append(ObjectDiff.Removed, removed)
								} else {
									match = false
								}
							}
							return ObjectDiff
						} else {
							for i := range valMod {
								for ii := range valOrig {
									if reflect.DeepEqual(valOrig[ii], valMod[i]) {
										match = true
									} else if i == ii {
										iter := len(path) - 1
										path[iter] = path[iter] + "[" + strconv.Itoa(i) + "]"
										ObjectDiff = recursion(parsing.Remarshal(valOrig[i]), parsing.Remarshal(valMod[i]),
											path, ObjectDiff)
									}
								}
								if !(match) {
									added := parsing.AddedDifference{Path: parsing.PathFormatter(path),
										Key: k, Value: valMod}
									ObjectDiff.Added = append(ObjectDiff.Added, added)

								} else {
									match = false
								}
							}
							return ObjectDiff
						}
					} else {
						// If both slice lengths are equal
						for i := range valOrig {
							copy(npath, path)
							if !(reflect.DeepEqual(valOrig[i], valMod[i])) {
								iter := len(npath) - 1
								npath[iter] = npath[iter] + "[" + strconv.Itoa(i) + "]"
								ObjectDiff = recursion(parsing.Remarshal(valOrig[i]), parsing.Remarshal(valMod[i]),
									npath, ObjectDiff)
							}
						}
						return ObjectDiff
					}
				} else {
					changed := parsing.ChangedDifference{Path: parsing.PathFormatter(path),
						Key: k, OldValue: valOrig, NewValue: valMod}
					ObjectDiff.Changed = append(ObjectDiff.Changed, changed)
					return ObjectDiff
				}
			}
		}
	}
	return ObjectDiff
}

func Recursion(original parsing.Keyvalue, modified parsing.Keyvalue, path []string) parsing.ConsumableDifference {
	var ObjectDiff = parsing.ConsumableDifference{}
	return recursion(original, modified, path, ObjectDiff)
}
<|endoftext|>