<commit_before>package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"encoding/json"

	strfmt "github.com/go-swagger/go-swagger/strfmt"
	"github.com/go-swagger/go-swagger/swag"

	"github.com/go-swagger/go-swagger/errors"
	"github.com/go-swagger/go-swagger/httpkit/validate"
)

/*CreateSubscriptionRequest Entity for requesting that a subscription be created.

swagger:model CreateSubscriptionRequest
*/
type CreateSubscriptionRequest struct {

	/* {"description":"ID of the BillForward Account who will own this subscription. You should ensure beforehand that the customer has had a BillForward Account created for them.","verbs":["POST"]}

	Required: true
	*/
	AccountID string `json:"accountID,omitempty"`

	/* {"default":false,"description":"Whether this subscription should become an 'aggregating subscription', collecting charges (starting now) from all other subscriptions (current and future) belonging to this BillForward Account.","verbs":["POST"]}
	 */
	AggregateAllSubscriptionsOnAccount *bool `json:"aggregateAllSubscriptionsOnAccount,omitempty"`

	/* {"default":true,"description":"Whether to override the `end` date to line up with the current period end of the 'aggregating subscription' to which this subscription belongs.","verbs":["POST"]}
	 */
	AlignPeriodWithAggregatingSubscription *bool `json:"alignPeriodWithAggregatingSubscription,omitempty"`

	/* {"default":"(null)","description":"Description of the created subscription. This is primarily for your benefit — for example, you could write here the mechanism through which you obtained this customer. (e.g. 'Customer obtained through Lazy Wednesdays promotion').","verbs":["POST"]}
	 */
	Description *string `json:"description,omitempty"`

	/* {"default":"(1 period ahead of the `start` time)","description":"ISO 8601 UTC DateTime (e.g. 2015-06-16T11:58:41Z) describing the date at which the subscription should finish its first service period.","verbs":["POST"]}
	 */
	End *strfmt.DateTime `json:"end,omitempty"`

	/* {"default":"None","description":"The action that should be taken, should an invoice for some subscription to this rate plan remain unpaid despite the dunning period's being exceeded.
CancelSubscription — Demotes the subscription to the `Failed` state as soon as the dunning period is exceeded.
None — The subscription is allowed to continue in the `AwaitingPayment` state indefinitely even if the dunning period is exceeded.For slow payment cycles — or when manual invoice remediation is common — None is recommended.
In a heavily-automated SaaS environment, automatic cancellation via CancelSubscription is recommended.","verbs":["POST","PUT","GET"]}
	 */
	FailedPaymentBehaviour *string `json:"failedPaymentBehaviour,omitempty"`

	/* { "description" : "Add metadata.", "verbs":["POST"] }
	 */
	Metadata DynamicMetadata `json:"metadata,omitempty"`

	/* {"default":"(Subscription will be named after the rate plan to which the subscription subscribes)","description":"Name of the created subscription. This is primarily for your benefit — for example, to enable you to identify subscriptions at a glance in the BillForward web interface (e.g. 'Customer 1425, guy@mail.com, Premium membership').","verbs":["POST"]}
	 */
	Name *string `json:"name,omitempty"`

	/* {"default":"(Auto-populated using your authentication credentials)","description":"ID of the BillForward Organization within which the requested Subscription should be created. If omitted, this will be auto-populated using your authentication credentials.","verbs":["POST"]}
	 */
	OrganizationID *string `json:"organizationID,omitempty"`

	/* {"default":"(If a subscription exists which 'aggregates all subscriptions belonging to this BillForward Account', refer to the ID of that subscription. Otherwise: null)","description":"ID of a parent subscription which will collect the charges raised by this subscription. The parent becomes responsible for paying those charges. If a subscription exists which 'aggregates all subscriptions belonging to this BillForward Account', then that parent will override any parent specified here.","verbs":["POST"]}
	 */
	ParentID *string `json:"parentID,omitempty"`

	/* PaymentTerms payment terms
	 */
	PaymentTerms *int64 `json:"paymentTerms,omitempty"`

	/* {"default":"(empty list)","description":"Quantities that this subscription possesses (upon beginning service), of pricing components upon the subscription's rate plan. For example: you can set the subscription to begin its service with '5 widgets' consumed. Otherwise the 'default quantity' will be observed instead, for each pricing component upon the rate plan.","verbs":["POST"]}
	 */
	PricingComponentQuantities []*PricingComponentQuantityRequest `json:"pricingComponentQuantities,omitempty"`

	/* {"description":"Name or ID of the product.","verbs":["POST"]}

	Required: true
	*/
	Product string `json:"product,omitempty"`

	/* {"description":"ID or name of the rate plan to which the subscription will be subscribing. Lookup by name is only possible if a `productID` is specified.","verbs":["POST"]}

	Required: true
	*/
	ProductRatePlan string `json:"productRatePlan,omitempty"`

	/* {"default":"(ServerNow upon receiving request)","description":"ISO 8601 UTC DateTime (e.g. 2015-06-16T11:58:41Z) describing the date at which the subscription should enter its first service period.","verbs":["POST"]}
	 */
	Start *strfmt.DateTime `json:"start,omitempty"`

	/* {"default":"Provisioned","description":"The state in which the created subscription will begin.
Provisioned — The subscription will wait (without raising any invoices or beginning its service) until explicit action is taken to change its state.
AwaitingPayment — The subscription is activated. After `start` time is surpassed, it will begin service and raise its first invoice.","verbs":["POST"]}
	 */
	State *string `json:"state,omitempty"`

	/* {"default":"(null)","description":"ISO 8601 UTC DateTime (e.g. 2015-06-16T11:58:41Z) describing the date at which the subscription should leave the trial period.","verbs":["POST"]}
	 */
	TrialEnd *strfmt.DateTime `json:"trialEnd,omitempty"`

	/* Type type
	 */
	Type *string `json:"type,omitempty"`
}

// Validate validates this create subscription request
func (m *CreateSubscriptionRequest) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateAccountID(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateFailedPaymentBehaviour(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validatePricingComponentQuantities(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateProduct(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateProductRatePlan(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateState(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateType(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateAccountID(formats strfmt.Registry) error {

	if err := validate.RequiredString("accountID", "body", string(m.AccountID)); err != nil {
		return err
	}

	return nil
}

var createSubscriptionRequestFailedPaymentBehaviourEnum []interface{}

func (m *CreateSubscriptionRequest) validateFailedPaymentBehaviourEnum(path, location string, value string) error {
	if createSubscriptionRequestFailedPaymentBehaviourEnum == nil {
		var res []string
		if err := json.Unmarshal([]byte(`["CancelSubscription","None"]`), &res); err != nil {
			return err
		}
		for _, v := range res {
			createSubscriptionRequestFailedPaymentBehaviourEnum = append(createSubscriptionRequestFailedPaymentBehaviourEnum, v)
		}
	}
	if err := validate.Enum(path, location, value, createSubscriptionRequestFailedPaymentBehaviourEnum); err != nil {
		return err
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateFailedPaymentBehaviour(formats strfmt.Registry) error {

	if swag.IsZero(m.FailedPaymentBehaviour) { // not required
		return nil
	}

	if err := m.validateFailedPaymentBehaviourEnum("failedPaymentBehaviour", "body", *m.FailedPaymentBehaviour); err != nil {
		return err
	}

	return nil
}

func (m *CreateSubscriptionRequest) validatePricingComponentQuantities(formats strfmt.Registry) error {

	if swag.IsZero(m.PricingComponentQuantities) { // not required
		return nil
	}

	for i := 0; i < len(m.PricingComponentQuantities); i++ {

		if m.PricingComponentQuantities[i] != nil {

			if err := m.PricingComponentQuantities[i].Validate(formats); err != nil {
				return err
			}
		}

	}

	return nil
}

func (m *CreateSubscriptionRequest) validateProduct(formats strfmt.Registry) error {

	if err := validate.RequiredString("product", "body", string(m.Product)); err != nil {
		return err
	}

	return nil
}

func (m *CreateSubscriptionRequest) validateProductRatePlan(formats strfmt.Registry) error {

	if err := validate.RequiredString("productRatePlan", "body", string(m.ProductRatePlan)); err != nil {
		return err
	}

	return nil
}

var createSubscriptionRequestStateEnum []interface{}

func (m *CreateSubscriptionRequest) validateStateEnum(path, location string, value string) error {
	if createSubscriptionRequestStateEnum == nil {
		var res []string
		if err := json.Unmarshal([]byte(`["Trial","Provisioned","Paid","AwaitingPayment","Cancelled","Failed","Expired"]`), &res); err != nil {
			return err
		}
		for _, v := range res {
			createSubscriptionRequestStateEnum = append(createSubscriptionRequestStateEnum, v)
		}
	}
	if err := validate.Enum(path, location, value, createSubscriptionRequestStateEnum); err != nil {
		return err
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateState(formats strfmt.Registry) error {

	if swag.IsZero(m.State) { // not required
		return nil
	}

	if err := m.validateStateEnum("state", "body", *m.State); err != nil {
		return err
	}

	return nil
}

var createSubscriptionRequestTypeEnum []interface{}

func (m *CreateSubscriptionRequest) validateTypeEnum(path, location string, value string) error {
	if createSubscriptionRequestTypeEnum == nil {
		var res []string
		if err := json.Unmarshal([]byte(`["Subscription","FixedTerm","Trial"]`), &res); err != nil {
			return err
		}
		for _, v := range res {
			createSubscriptionRequestTypeEnum = append(createSubscriptionRequestTypeEnum, v)
		}
	}
	if err := validate.Enum(path, location, value, createSubscriptionRequestTypeEnum); err != nil {
		return err
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateType(formats strfmt.Registry) error {

	if swag.IsZero(m.Type) { // not required
		return nil
	}

	if err := m.validateTypeEnum("type", "body", *m.Type); err != nil {
		return err
	}

	return nil
}
<commit_msg>models: Regenerate<commit_after>package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"encoding/json"

	strfmt "github.com/go-swagger/go-swagger/strfmt"
	"github.com/go-swagger/go-swagger/swag"

	"github.com/go-swagger/go-swagger/errors"
	"github.com/go-swagger/go-swagger/httpkit/validate"
)

/*CreateSubscriptionRequest Entity for requesting that a subscription be created.

swagger:model CreateSubscriptionRequest
*/
type CreateSubscriptionRequest struct {

	/* {"description":"ID of the BillForward Account who will own this subscription. You should ensure beforehand that the customer has had a BillForward Account created for them.","verbs":["POST"]}

	Required: true
	*/
	AccountID string `json:"accountID,omitempty"`

	/* {"default":false,"description":"Whether this subscription should become an 'aggregating subscription', collecting charges (starting now) from all other subscriptions (current and future) belonging to this BillForward Account.","verbs":["POST"]}
	 */
	AggregateAllSubscriptionsOnAccount *bool `json:"aggregateAllSubscriptionsOnAccount,omitempty"`

	/* {"default":true,"description":"Whether to override the `end` date to line up with the current period end of the 'aggregating subscription' to which this subscription belongs.","verbs":["POST"]}
	 */
	AlignPeriodWithAggregatingSubscription *bool `json:"alignPeriodWithAggregatingSubscription,omitempty"`

	/* {"description":"start of the contracted period.  This will be after a trial, if one exists","verbs":["GET"]}
	 */
	ContractStart *strfmt.DateTime `json:"contractStart,omitempty"`

	/* {"default":"(null)","description":"Description of the created subscription. This is primarily for your benefit — for example, you could write here the mechanism through which you obtained this customer. (e.g. 'Customer obtained through Lazy Wednesdays promotion').","verbs":["POST"]}
	 */
	Description *string `json:"description,omitempty"`

	/* {"default":"(1 period ahead of the `start` time)","description":"ISO 8601 UTC DateTime (e.g. 2015-06-16T11:58:41Z) describing the date at which the subscription should finish its first service period.","verbs":["POST"]}
	 */
	End *strfmt.DateTime `json:"end,omitempty"`

	/* {"default":"None","description":"The action that should be taken, should an invoice for some subscription to this rate plan remain unpaid despite the dunning period's being exceeded.
CancelSubscription — Demotes the subscription to the `Failed` state as soon as the dunning period is exceeded.
None — The subscription is allowed to continue in the `AwaitingPayment` state indefinitely even if the dunning period is exceeded.For slow payment cycles — or when manual invoice remediation is common — None is recommended.
In a heavily-automated SaaS environment, automatic cancellation via CancelSubscription is recommended.","verbs":["POST","PUT","GET"]}
	 */
	FailedPaymentBehaviour *string `json:"failedPaymentBehaviour,omitempty"`

	/* { "description" : "Add metadata.", "verbs":["POST"] }
	 */
	Metadata DynamicMetadata `json:"metadata,omitempty"`

	/* {"default":"(Subscription will be named after the rate plan to which the subscription subscribes)","description":"Name of the created subscription. This is primarily for your benefit — for example, to enable you to identify subscriptions at a glance in the BillForward web interface (e.g. 'Customer 1425, guy@mail.com, Premium membership').","verbs":["POST"]}
	 */
	Name *string `json:"name,omitempty"`

	/* {"default":"(Auto-populated using your authentication credentials)","description":"ID of the BillForward Organization within which the requested Subscription should be created. If omitted, this will be auto-populated using your authentication credentials.","verbs":["POST"]}
	 */
	OrganizationID *string `json:"organizationID,omitempty"`

	/* {"default":"(If a subscription exists which 'aggregates all subscriptions belonging to this BillForward Account', refer to the ID of that subscription. Otherwise: null)","description":"ID of a parent subscription which will collect the charges raised by this subscription. The parent becomes responsible for paying those charges. If a subscription exists which 'aggregates all subscriptions belonging to this BillForward Account', then that parent will override any parent specified here.","verbs":["POST"]}
	 */
	ParentID *string `json:"parentID,omitempty"`

	/* PaymentTerms payment terms
	 */
	PaymentTerms *int64 `json:"paymentTerms,omitempty"`

	/* {"default":"(empty list)","description":"Quantities that this subscription possesses (upon beginning service), of pricing components upon the subscription's rate plan. For example: you can set the subscription to begin its service with '5 widgets' consumed. Otherwise the 'default quantity' will be observed instead, for each pricing component upon the rate plan.","verbs":["POST"]}
	 */
	PricingComponentQuantities []*PricingComponentQuantityRequest `json:"pricingComponentQuantities,omitempty"`

	/* {"description":"Name or ID of the product.","verbs":["POST"]}

	Required: true
	*/
	Product string `json:"product,omitempty"`

	/* {"description":"ID or name of the rate plan to which the subscription will be subscribing. Lookup by name is only possible if a `productID` is specified.","verbs":["POST"]}

	Required: true
	*/
	ProductRatePlan string `json:"productRatePlan,omitempty"`

	/* {"default":"(ServerNow upon receiving request)","description":"ISO 8601 UTC DateTime (e.g. 2015-06-16T11:58:41Z) describing the date at which the subscription should enter its first service period.","verbs":["POST"]}
	 */
	Start *strfmt.DateTime `json:"start,omitempty"`

	/* {"default":"Provisioned","description":"The state in which the created subscription will begin.
Provisioned — The subscription will wait (without raising any invoices or beginning its service) until explicit action is taken to change its state.
AwaitingPayment — The subscription is activated. After `start` time is surpassed, it will begin service and raise its first invoice.","verbs":["POST"]}
	 */
	State *string `json:"state,omitempty"`

	/* {"default":"(null)","description":"ISO 8601 UTC DateTime (e.g. 2015-06-16T11:58:41Z) describing the date at which the subscription should leave the trial period.","verbs":["POST"]}
	 */
	TrialEnd *strfmt.DateTime `json:"trialEnd,omitempty"`

	/* Type type
	 */
	Type *string `json:"type,omitempty"`
}

// Validate validates this create subscription request
func (m *CreateSubscriptionRequest) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateAccountID(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateFailedPaymentBehaviour(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validatePricingComponentQuantities(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateProduct(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateProductRatePlan(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateState(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateType(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateAccountID(formats strfmt.Registry) error {

	if err := validate.RequiredString("accountID", "body", string(m.AccountID)); err != nil {
		return err
	}

	return nil
}

var createSubscriptionRequestFailedPaymentBehaviourEnum []interface{}

func (m *CreateSubscriptionRequest) validateFailedPaymentBehaviourEnum(path, location string, value string) error {
	if createSubscriptionRequestFailedPaymentBehaviourEnum == nil {
		var res []string
		if err := json.Unmarshal([]byte(`["CancelSubscription","None"]`), &res); err != nil {
			return err
		}
		for _, v := range res {
			createSubscriptionRequestFailedPaymentBehaviourEnum = append(createSubscriptionRequestFailedPaymentBehaviourEnum, v)
		}
	}
	if err := validate.Enum(path, location, value, createSubscriptionRequestFailedPaymentBehaviourEnum); err != nil {
		return err
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateFailedPaymentBehaviour(formats strfmt.Registry) error {

	if swag.IsZero(m.FailedPaymentBehaviour) { // not required
		return nil
	}

	if err := m.validateFailedPaymentBehaviourEnum("failedPaymentBehaviour", "body", *m.FailedPaymentBehaviour); err != nil {
		return err
	}

	return nil
}

func (m *CreateSubscriptionRequest) validatePricingComponentQuantities(formats strfmt.Registry) error {

	if swag.IsZero(m.PricingComponentQuantities) { // not required
		return nil
	}

	for i := 0; i < len(m.PricingComponentQuantities); i++ {

		if m.PricingComponentQuantities[i] != nil {

			if err := m.PricingComponentQuantities[i].Validate(formats); err != nil {
				return err
			}
		}

	}

	return nil
}

func (m *CreateSubscriptionRequest) validateProduct(formats strfmt.Registry) error {

	if err := validate.RequiredString("product", "body", string(m.Product)); err != nil {
		return err
	}

	return nil
}

func (m *CreateSubscriptionRequest) validateProductRatePlan(formats strfmt.Registry) error {

	if err := validate.RequiredString("productRatePlan", "body", string(m.ProductRatePlan)); err != nil {
		return err
	}

	return nil
}

var createSubscriptionRequestStateEnum []interface{}

func (m *CreateSubscriptionRequest) validateStateEnum(path, location string, value string) error {
	if createSubscriptionRequestStateEnum == nil {
		var res []string
		if err := json.Unmarshal([]byte(`["Trial","Provisioned","Paid","AwaitingPayment","Cancelled","Failed","Expired"]`), &res); err != nil {
			return err
		}
		for _, v := range res {
			createSubscriptionRequestStateEnum = append(createSubscriptionRequestStateEnum, v)
		}
	}
	if err := validate.Enum(path, location, value, createSubscriptionRequestStateEnum); err != nil {
		return err
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateState(formats strfmt.Registry) error {

	if swag.IsZero(m.State) { // not required
		return nil
	}

	if err := m.validateStateEnum("state", "body", *m.State); err != nil {
		return err
	}

	return nil
}

var createSubscriptionRequestTypeEnum []interface{}

func (m *CreateSubscriptionRequest) validateTypeEnum(path, location string, value string) error {
	if createSubscriptionRequestTypeEnum == nil {
		var res []string
		if err := json.Unmarshal([]byte(`["Subscription","FixedTerm","Trial"]`), &res); err != nil {
			return err
		}
		for _, v := range res {
			createSubscriptionRequestTypeEnum = append(createSubscriptionRequestTypeEnum, v)
		}
	}
	if err := validate.Enum(path, location, value, createSubscriptionRequestTypeEnum); err != nil {
		return err
	}
	return nil
}

func (m *CreateSubscriptionRequest) validateType(formats strfmt.Registry) error {

	if swag.IsZero(m.Type) { // not required
		return nil
	}

	if err := m.validateTypeEnum("type", "body", *m.Type); err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"os"
	"os/exec"
	"testing"
)

const apigeecli = "./apigeecli"

var token = os.Getenv("APIGEE_TOKEN")
var env = os.Getenv("APIGEE_ENV")
var org = os.Getenv("APIGEE_ORG")
var email = "test@gmail.com"
var appId string

func TestMain(t *testing.T) {
	cmd := exec.Command(apigeecli)
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// orgs test
func TestListOrgs(t *testing.T) {
	cmd := exec.Command(apigeecli, "orgs", "list", "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestGetOrg(t *testing.T) {
	cmd := exec.Command(apigeecli, "orgs", "get", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// env tests
func TestListEnvs(t *testing.T) {
	cmd := exec.Command(apigeecli, "envs", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestGetEnv(t *testing.T) {
	cmd := exec.Command(apigeecli, "envs", "get", "-o", org, "-e", env, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// developers test
func TestCreateDeveloper(t *testing.T) {
	first := "frstname"
	last := "lastname"
	user := "username"
	attrs := "\"foo1=bar1,foo2=bar2\""

	cmd := exec.Command(apigeecli, "developers", "create", "-o", org, "-n", email, "-f", first, "-s", last, "-u", user, "--attrs", attrs, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestGetDeveloper(t *testing.T) {

	cmd := exec.Command(apigeecli, "developers", "get", "-o", org, "-n", email, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListDeveloper(t *testing.T) {

	cmd := exec.Command(apigeecli, "developers", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListExpandDeveloper(t *testing.T) {
	expand := "true"

	cmd := exec.Command(apigeecli, "developers", "list", "-o", org, "-x", expand, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// kvm test
func TestCreateKVM(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListKVM(t *testing.T) {

	cmd := exec.Command(apigeecli, "kvms", "list", "-o", org, "-e", env, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// sync tests
func TestGetSync(t *testing.T) {

	cmd := exec.Command(apigeecli, "sync", "get", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestSetSync(t *testing.T) {
	ity := "test@gmail.com"
	cmd := exec.Command(apigeecli, "sync", "set", "-o", org, "-i", ity, "-t", token, "-l")
	err := cmd.Run()
	if err == nil {
		t.Fatal("Invalid identity test should have failed")
	}
}

func TestCreateProxy(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "apis", "create", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestCreateProduct(t *testing.T) {
	name := "test"
	envs := "test"
	proxy := "test"
	approval := "auto"
	attrs := "\"foo1=bar1,foo2=bar2\""

	cmd := exec.Command(apigeecli, "products", "create", "-o", org, "-n", name, "-e", envs, "-p", proxy, "-f", approval, "--attrs", attrs, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestCreateApp(t *testing.T) {
	name := "test"
	product := "test"
	attrs := "\"foo1=bar1,foo2=bar2\""

	cmd := exec.Command(apigeecli, "apps", "create", "-o", org, "-n", name, "-e", email, "-p", product, "--attrs", attrs, "-t", token, "-l")

	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

	var outputMap map[string]string
	_ = json.Unmarshal([]byte(out.Bytes()), &outputMap)
	appId = outputMap["appId"]

}

func TestListApp(t *testing.T) {

	cmd := exec.Command(apigeecli, "apps", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestGetProduct(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "products", "get", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListProduct(t *testing.T) {

	cmd := exec.Command(apigeecli, "products", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestDeleteDeveloper(t *testing.T) {

	cmd := exec.Command(apigeecli, "developers", "delete", "-o", org, "-n", email, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestCreateTS(t *testing.T) {
	name := "test"
	host := "example.com"

	cmd := exec.Command(apigeecli, "targetservers", "create", "-o", org, "-n", name, "-e", env, "-s", host, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestGetTS(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "targetservers", "get", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestListTS(t *testing.T) {

	cmd := exec.Command(apigeecli, "targetservers", "list", "-o", org, "-e", env, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestDeleteTS(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "targetservers", "delete", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

//get requires an app id. run list and get an app id or get it from create
func TestGetApp(t *testing.T) {
	cmd := exec.Command(apigeecli, "apps", "get", "-o", org, "-i", appId, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

/*func TestSetMart(t *testing.T) {
	mart := os.Getenv("MART")
	if mart == "" {
		t.Log("MART not set, skipping")
	} else {
		cmd := exec.Command(apigeecli, "orgs", "setmart", "-o", org, "-m", mart, "-t", token, "-l")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestSetMartWhiteList(t *testing.T) {
	mart := os.Getenv("MART")
	if mart == "" {
		t.Log("MART not set, skipping")
	} else {
		cmd := exec.Command(apigeecli, "orgs", "setmart", "-o", org, "-m", mart, "-w", "false", "-t", token, "-l")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
	}
}*/

/*func TestCreateEncKVM(t *testing.T) {
	name := "testEnc"
	enc := "true"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-c", enc, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}*/

/*func TestDeleteKVM(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestDeleteEncKVM(t *testing.T) {
	name := "testEnc"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}*/

/*func TestDeleteApp(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "apps", "delete", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}*/

/*func TestDeleteProduct(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}*/
<commit_msg>remove getapp<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"os"
	"os/exec"
	"testing"
)

const apigeecli = "./apigeecli"

var token = os.Getenv("APIGEE_TOKEN")
var env = os.Getenv("APIGEE_ENV")
var org = os.Getenv("APIGEE_ORG")
var email = "test@gmail.com"
var appId string

func TestMain(t *testing.T) {
	cmd := exec.Command(apigeecli)
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// orgs test
func TestListOrgs(t *testing.T) {
	cmd := exec.Command(apigeecli, "orgs", "list", "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestGetOrg(t *testing.T) {
	cmd := exec.Command(apigeecli, "orgs", "get", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// env tests
func TestListEnvs(t *testing.T) {
	cmd := exec.Command(apigeecli, "envs", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestGetEnv(t *testing.T) {
	cmd := exec.Command(apigeecli, "envs", "get", "-o", org, "-e", env, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// developers test
func TestCreateDeveloper(t *testing.T) {
	first := "frstname"
	last := "lastname"
	user := "username"
	attrs := "\"foo1=bar1,foo2=bar2\""

	cmd := exec.Command(apigeecli, "developers", "create", "-o", org, "-n", email, "-f", first, "-s", last, "-u", user, "--attrs", attrs, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestGetDeveloper(t *testing.T) {

	cmd := exec.Command(apigeecli, "developers", "get", "-o", org, "-n", email, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListDeveloper(t *testing.T) {

	cmd := exec.Command(apigeecli, "developers", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListExpandDeveloper(t *testing.T) {
	expand := "true"

	cmd := exec.Command(apigeecli, "developers", "list", "-o", org, "-x", expand, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// kvm test
func TestCreateKVM(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListKVM(t *testing.T) {

	cmd := exec.Command(apigeecli, "kvms", "list", "-o", org, "-e", env, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

// sync tests
func TestGetSync(t *testing.T) {

	cmd := exec.Command(apigeecli, "sync", "get", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestSetSync(t *testing.T) {
	ity := "test@gmail.com"
	cmd := exec.Command(apigeecli, "sync", "set", "-o", org, "-i", ity, "-t", token, "-l")
	err := cmd.Run()
	if err == nil {
		t.Fatal("Invalid identity test should have failed")
	}
}

func TestCreateProxy(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "apis", "create", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestCreateProduct(t *testing.T) {
	name := "test"
	envs := "test"
	proxy := "test"
	approval := "auto"
	attrs := "\"foo1=bar1,foo2=bar2\""

	cmd := exec.Command(apigeecli, "products", "create", "-o", org, "-n", name, "-e", envs, "-p", proxy, "-f", approval, "--attrs", attrs, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestCreateApp(t *testing.T) {
	name := "test"
	product := "test"
	attrs := "\"foo1=bar1,foo2=bar2\""

	cmd := exec.Command(apigeecli, "apps", "create", "-o", org, "-n", name, "-e", email, "-p", product, "--attrs", attrs, "-t", token, "-l")

	var out bytes.Buffer
	cmd.Stdout = &out

	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

	var outputMap map[string]string
	_ = json.Unmarshal([]byte(out.Bytes()), &outputMap)
	appId = outputMap["appId"]
}

func TestListApp(t *testing.T) {

	cmd := exec.Command(apigeecli, "apps", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestGetProduct(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "products", "get", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestListProduct(t *testing.T) {

	cmd := exec.Command(apigeecli, "products", "list", "-o", org, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestDeleteDeveloper(t *testing.T) {

	cmd := exec.Command(apigeecli, "developers", "delete", "-o", org, "-n", email, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestCreateTS(t *testing.T) {
	name := "test"
	host := "example.com"

	cmd := exec.Command(apigeecli, "targetservers", "create", "-o", org, "-n", name, "-e", env, "-s", host, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestGetTS(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "targetservers", "get", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestListTS(t *testing.T) {

	cmd := exec.Command(apigeecli, "targetservers", "list", "-o", org, "-e", env, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

func TestDeleteTS(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "targetservers", "delete", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}

//get requires an app id. run list and get an app id or get it from create
/*func TestGetApp(t *testing.T) {
	cmd := exec.Command(apigeecli, "apps", "get", "-o", org, "-i", appId, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}*/

/*func TestSetMart(t *testing.T) {
	mart := os.Getenv("MART")
	if mart == "" {
		t.Log("MART not set, skipping")
	} else {
		cmd := exec.Command(apigeecli, "orgs", "setmart", "-o", org, "-m", mart, "-t", token, "-l")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestSetMartWhiteList(t *testing.T) {
	mart := os.Getenv("MART")
	if mart == "" {
		t.Log("MART not set, skipping")
	} else {
		cmd := exec.Command(apigeecli, "orgs", "setmart", "-o", org, "-m", mart, "-w", "false", "-t", token, "-l")
		err := cmd.Run()
		if err != nil {
			t.Fatal(err)
		}
	}
}*/

/*func TestCreateEncKVM(t *testing.T) {
	name := "testEnc"
	enc := "true"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-c", enc, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}*/

/*func TestDeleteKVM(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}

func TestDeleteEncKVM(t *testing.T) {
	name := "testEnc"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-e", env, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}*/

/*func TestDeleteApp(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "apps", "delete", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}

}*/

/*func TestDeleteProduct(t *testing.T) {
	name := "test"

	cmd := exec.Command(apigeecli, "kvms", "create", "-o", org, "-n", name, "-t", token, "-l")
	err := cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
}*/
<|endoftext|>


<commit_before>package config

import (
	"log"
	"reflect"
	"testing"
)

func TestParseConfig(t *testing.T) {
	input := `
  queue "test" {
    type = "test_type"
    host = "localhost"
    port = 1234
  }
`
	expect := config{
		Queues: []*Queue{
			&Queue{
				Driver:  "test_type",
				Host:    "localhost",
				Port:    1234,
				Timeout: 2,
			},
		},
	}
	out, err := Parse(input)
	if err != nil {
		log.Println(err)
	}
	if !reflect.DeepEqual(out, expect) {
		t.Fatalf("bad: %#v !== %#v", out, expect)
	}
}
<commit_msg>Fix Timeout test struct value<commit_after>package config

import (
	"log"
	"reflect"
	"testing"
	"time"
)

func TestParseConfig(t *testing.T) {
	input := `
  queue "test" {
    type = "test_type"
    host = "localhost"
    port = 1234
  }
`
	expect := config{
		Queues: []*Queue{
			&Queue{
				Driver:  "test_type",
				Host:    "localhost",
				Port:    1234,
				Timeout: 2 * time.Second,
			},
		},
	}
	out, err := Parse(input)
	if err != nil {
		log.Println(err)
	}
	if !reflect.DeepEqual(out, expect) {
		t.Fatalf("bad: %#v !== %#v", out, expect)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path"
	"syscall"
	"testing"
	"time"
)

const servAddr = "127.0.0.1:8181"
const servWaitListen = 10000 // milliseconds to wait for server to start listening
const servWaitSleep = 100    // milliseconds sleep interval
const scratchDir = "test/scratch"
const testRepoRoot = "test/data"

func TestAllowedClone(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, `{"GL_ID":"user-123"}`)
	}))
	defer ts.Close()
	cmd, err := startServer(ts)
	if err != nil {
		t.Fatal(err)
	}
	defer cleanUpProcessGroup(cmd)
	if err := os.RemoveAll(scratchDir); err != nil {
		t.Fatal(err)
	}
	cloneCmd := exec.Command("git", "clone", fmt.Sprintf("http://%s/test.git", servAddr), path.Join(scratchDir, "test"))
	if out, err := cloneCmd.CombinedOutput(); err != nil {
		t.Logf("%s", out)
		t.Fatal(err)
	}
}

func startServer(ts *httptest.Server) (cmd *exec.Cmd, err error) {
	var conn net.Conn

	// Start our server process
	cmd = exec.Command("go", "run", "main.go", fmt.Sprintf("-authBackend=%s", ts.URL), fmt.Sprintf("-listenAddr=%s", servAddr), testRepoRoot)
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
	err = cmd.Start()
	if err != nil {
		return
	}

	// Wait for the server to start accepting TCP connections
	for i := 0; i < servWaitListen/servWaitSleep; i++ {
		conn, err = net.Dial("tcp", servAddr)
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(servWaitSleep * time.Millisecond)
	}
	return
}
<commit_msg>Clean up if the caller won't<commit_after>package main

import (
	"fmt"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path"
	"syscall"
	"testing"
	"time"
)

const servAddr = "127.0.0.1:8181"
const servWaitListen = 10000 // milliseconds to wait for server to start listening
const servWaitSleep = 100    // milliseconds sleep interval
const scratchDir = "test/scratch"
const testRepoRoot = "test/data"

func TestAllowedClone(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, `{"GL_ID":"user-123"}`)
	}))
	defer ts.Close()
	cmd, err := startServer(ts)
	if err != nil {
		t.Fatal(err)
	}
	defer cleanUpProcessGroup(cmd)
	if err := os.RemoveAll(scratchDir); err != nil {
		t.Fatal(err)
	}
	cloneCmd := exec.Command("git", "clone", fmt.Sprintf("http://%s/test.git", servAddr), path.Join(scratchDir, "test"))
	if out, err := cloneCmd.CombinedOutput(); err != nil {
		t.Logf("%s", out)
		t.Fatal(err)
	}
}

func startServer(ts *httptest.Server) (cmd *exec.Cmd, err error) {
	var conn net.Conn

	// Start our server process
	cmd = exec.Command("go", "run", "main.go", fmt.Sprintf("-authBackend=%s", ts.URL), fmt.Sprintf("-listenAddr=%s", servAddr), testRepoRoot)
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
	err = cmd.Start()
	if err != nil {
		return
	}

	// Wait for the server to start accepting TCP connections
	for i := 0; i < servWaitListen/servWaitSleep; i++ {
		conn, err = net.Dial("tcp", servAddr)
		if err == nil {
			conn.Close()
			break
		}
		time.Sleep(servWaitSleep * time.Millisecond)
	}
	if err != nil {
		cleanUpProcessGroup(cmd)
	}

	return
}
<|endoftext|>


<commit_before>package jsonpath

import (
	"encoding/json"
	"testing"
)

// Simple test case from json_path website:
var jsonBooksBlob = []byte(`
{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}
`)
var bookstore interface{}
var bs Object

func init() {
	// set up the fixtures
	json.Unmarshal(jsonBooksBlob, &bookstore)
	bs = Object(bookstore)
}

func helperTestStringPath(t *testing.T, o Object, path, eResponse, desc string) {
	v, err := Value(path, o)
	if err != nil {
		t.Errorf("We got an error trying to %s [ %s]", desc, err)
	}
	s, found := v.(string)
	if !found {
		t.Error("Did not get a string back for path %s", path)
	}
	if s != eResponse {
		t.Errorf("Did not get the expected string '%s' got '%s' instead ", eResponse, s)
	}
}
func TestGetValue(t *testing.T) {

	helperTestStringPath(t, bs, `$['store']['book'][0]['title']`, "Sayings of the Century", "title of the first book")
	helperTestStringPath(t, bs, `$['store']['book'][1]['title']`, "Sword of Honour", "title of the second book")
	helperTestStringPath(t, bs, `$['store']['bicycle']['color']`, "red", "color of the bicycle")
}

/*
func TestParsePath(t *testing.T) {
	p, err := ParsePath(`$`)
	if err != nil {
		t.Error("Did not expect to recieve an error: ", err)
	}
	if len(p) != 0 {
		t.Error("For a root element expected path to be empty")
	}
	p, err = ParsePath(`$['store']`)
	if err != nil {
		t.Error("Did not expect to recieve an error: ", err)
	}
	if len(p) != 1 {
		t.Error("Expected path to contain one element")
	}
	e := p[0]
	if e.Type != MapType {
		t.Error("Expected first element to be a MapKey")
	}
	if e.MapKey != "store" {
		t.Error("Expected key to be `store` go ", e.MapKey)
	}
}
*/
func hlperTestNormalizePath(t *testing.T, path, expectedPath string) {
	p, err := normalize(path)
	if err != nil {
		t.Errorf("Did not expect error normalizing `%s` error: `%v`", path, err)
	}
	if p != expectedPath {
		t.Errorf("Normalizing `%s` should be `%s` got `%s`", path, expectedPath, p)
	}

}
func TestNormalizePath(t *testing.T) {
	_, err := normalize(`store`)
	if err == nil {
		t.Errorf("Expected normalize to return error.")
	}
	fix := map[string]string{
		`  $  `:                               `$`,
		`$`:                                   `$`,
		`  $.book`:                            `$['book']`,
		`$.store  `:                           `$['store']`,
		`$['book']`:                           `$['book']`,
		`$['store']`:                          `$['store']`,
		`$['book'][0]`:                        `$['book'][0]`,
		`$.store[0]`:                          `$['store'][0]`,
		`$.store..price`:                      `$['store'][..]['price']`,
		`$.store[0]..price`:                   `$['store'][0][..]['price']`,
		`$.store..*`:                          `$['store'][..][*]`,
		`$.store[..][*]`:                      `$['store'][..][*]`,
		`$['store'][..][*]`:                   `$['store'][..][*]`,
		`$..book[?(@.isbn)]`:                  `$[..]['book'][?(@.isbn)]`,
		`$..book[(@.length-1)]`:               `$[..]['book'][(@.length-1)]`,
		`$..book[(@.bar[@.foo[1]].length-1)]`: `$[..]['book'][(@.bar[@.foo[1]].length-1)]`,
		`$..book['bar[]']`:                    `$[..]['book']['bar[]']`,
		`$.book['bar()']`:                     `$['book']['bar()']`,
		`$.['store','price']..*`:              `$['store','price'][..][*]`,
		`$['book'][0:-1]`:                     `$['book'][0:-1]`,
		`$['book'][:2]`:                       `$['book'][:2]`,
		`$.book.[0:-1:2]`:                     `$['book'][0:-1:2]`,
		`$.book.0`:                            `$['book'][0]`,
		`$.book'\''.0`:                        `$['book'\'''][0]`,
		`$.book.10`:                           `$['book'][10]`,
		`$.book.0day`:                         `$['book']['0day']`,
		`$.book.10day4Nov2014`:                `$['book']['10day4Nov2014']`,
		`$.book.10day.4Nov.'2014'`:            `$['book']['10day']['4Nov']['2014']`,
		`$..`:       `$[..]`,
		`$..*`:      `$[..][*]`,
		`$.'foo\'s`: `$['foo\'']`,
	}
	for k, v := range fix {
		hlperTestNormalizePath(t, k, v)
	}
}
<commit_msg>Fixed test.<commit_after>package jsonpath

import (
	"encoding/json"
	"testing"
)

// Simple test case from json_path website:
var jsonBooksBlob = []byte(`
{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}
`)
var bookstore interface{}
var bs Object

func init() {
	// set up the fixtures
	json.Unmarshal(jsonBooksBlob, &bookstore)
	bs = Object(bookstore)
}

func helperTestStringPath(t *testing.T, o Object, path, eResponse, desc string) {
	v, err := Value(path, o)
	if err != nil {
		t.Errorf("We got an error trying to %s [ %s]", desc, err)
	}
	s, found := v.(string)
	if !found {
		t.Error("Did not get a string back for path %s", path)
	}
	if s != eResponse {
		t.Errorf("Did not get the expected string '%s' got '%s' instead ", eResponse, s)
	}
}
func TestGetValue(t *testing.T) {

	helperTestStringPath(t, bs, `$['store']['book'][0]['title']`, "Sayings of the Century", "title of the first book")
	helperTestStringPath(t, bs, `$['store']['book'][1]['title']`, "Sword of Honour", "title of the second book")
	helperTestStringPath(t, bs, `$['store']['bicycle']['color']`, "red", "color of the bicycle")
}

/*
func TestParsePath(t *testing.T) {
	p, err := ParsePath(`$`)
	if err != nil {
		t.Error("Did not expect to recieve an error: ", err)
	}
	if len(p) != 0 {
		t.Error("For a root element expected path to be empty")
	}
	p, err = ParsePath(`$['store']`)
	if err != nil {
		t.Error("Did not expect to recieve an error: ", err)
	}
	if len(p) != 1 {
		t.Error("Expected path to contain one element")
	}
	e := p[0]
	if e.Type != MapType {
		t.Error("Expected first element to be a MapKey")
	}
	if e.MapKey != "store" {
		t.Error("Expected key to be `store` go ", e.MapKey)
	}
}
*/
func hlperTestNormalizePath(t *testing.T, path, expectedPath string) {
	p, err := normalize(path)
	if err != nil {
		t.Errorf("Did not expect error normalizing `%s` error: `%v`", path, err)
	}
	if p != expectedPath {
		t.Errorf("Normalizing `%s` should be `%s` got `%s`", path, expectedPath, p)
	}

}
func TestNormalizePath(t *testing.T) {
	_, err := normalize(`store`)
	if err == nil {
		t.Errorf("Expected normalize to return error.")
	}
	fix := map[string]string{
		`  $  `:                               `$`,
		`$`:                                   `$`,
		`  $.book`:                            `$['book']`,
		`$.store  `:                           `$['store']`,
		`$['book']`:                           `$['book']`,
		`$['store']`:                          `$['store']`,
		`$['book'][0]`:                        `$['book'][0]`,
		`$.store[0]`:                          `$['store'][0]`,
		`$.store..price`:                      `$['store'][..]['price']`,
		`$.store[0]..price`:                   `$['store'][0][..]['price']`,
		`$.store..*`:                          `$['store'][..][*]`,
		`$.store[..][*]`:                      `$['store'][..][*]`,
		`$['store'][..][*]`:                   `$['store'][..][*]`,
		`$..book[?(@.isbn)]`:                  `$[..]['book'][?(@.isbn)]`,
		`$..book[(@.length-1)]`:               `$[..]['book'][(@.length-1)]`,
		`$..book[(@.bar[@.foo[1]].length-1)]`: `$[..]['book'][(@.bar[@.foo[1]].length-1)]`,
		`$..book['bar[]']`:                    `$[..]['book']['bar[]']`,
		`$.book['bar()']`:                     `$['book']['bar()']`,
		`$.['store','price']..*`:              `$['store','price'][..][*]`,
		`$['book'][0:-1]`:                     `$['book'][0:-1]`,
		`$['book'][:2]`:                       `$['book'][:2]`,
		`$.book.[0:-1:2]`:                     `$['book'][0:-1:2]`,
		`$.book.0`:                            `$['book'][0]`,
		`$.book'\''.0`:                        `$['book'\'''][0]`,
		`$.book.10`:                           `$['book'][10]`,
		`$.book.0day`:                         `$['book']['0day']`,
		`$.book.10day4Nov2014`:                `$['book']['10day4Nov2014']`,
		`$.book.10day.4Nov.'2014'`:            `$['book']['10day']['4Nov']['2014']`,
		`$..`:       `$[..]`,
		`$..*`:      `$[..][*]`,
		`$.'foo\'s`: `$['foo\'s']`,
	}
	for k, v := range fix {
		hlperTestNormalizePath(t, k, v)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"testing"
	"time"
)

const tmpDir = "main_test_tmp/"
const plainDir = tmpDir + "plain/"
const cipherDir = tmpDir + "cipher/"

func TestMain(m *testing.M) {

	fu := exec.Command("fusermount", "-u", plainDir)
	fu.Stdout = os.Stdout
	fu.Stderr = os.Stderr
	fu.Run()
	os.RemoveAll(tmpDir)

	err := os.MkdirAll(plainDir, 0777)
	if err != nil {
		panic("Could not create plainDir")
	}

	err = os.MkdirAll(cipherDir, 0777)
	if err != nil {
		panic("Could not create cipherDir")
	}

	c := exec.Command("./gocryptfs", "--zerokey", cipherDir, plainDir)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	go c.Run()

	time.Sleep(3 * time.Second)

	r := m.Run()

	fu.Run()
	os.Exit(r)
}

func testWriteN(t *testing.T, fn string, n int) string {
	file, err := os.Create(plainDir + fn)
	if err != nil {
		t.FailNow()
	}

	d := make([]byte, n)
	written, err := file.Write(d)
	if err != nil || written != len(d) {
		fmt.Printf("err=\"%s\", written=%d\n", err, written)
		t.Fail()
	}
	file.Close()

	buf, err := ioutil.ReadFile(plainDir + fn)
	if err != nil {
		t.Fail()
	}

	raw := md5.Sum(d)
	hashWant := hex.EncodeToString(raw[:])

	raw = md5.Sum(buf)
	hashActual := hex.EncodeToString(raw[:])
	if hashActual != hashWant {
		fmt.Printf("hashWant=%s hashActual=%s\n", hashWant, hashActual)
		t.Fail()
	}

	return hashActual
}

func TestWrite10(t *testing.T) {
	testWriteN(t, "10", 10)
}

func TestWrite100(t *testing.T) {
	testWriteN(t, "100", 100)
}

func TestWrite1M(t *testing.T) {
	testWriteN(t, "1M", 1024*1024)
}

func TestWrite1Mx100(t *testing.T) {
	hashWant := testWriteN(t, "1Mx100", 1024*1024)
	// Read and check 100 times to catch race conditions
	var i int
	for i = 0; i < 100; i++ {
		buf, err := ioutil.ReadFile(plainDir + "1M")
		if err != nil {
			t.Fail()
		}
		rawHash := md5.Sum(buf)
		hashActual := hex.EncodeToString(rawHash[:])
		if hashActual != hashWant {
			fmt.Printf("Read corruption in loop # %d\n", i)
			t.FailNow()
		} else {
			//fmt.Print(".")
		}
	}
}

func BenchmarkStreamWrite(t *testing.B) {
	buf := make([]byte, 1024*1024)
	t.SetBytes(int64(len(buf)))

	file, err := os.Create(plainDir + "BenchmarkWrite")
	if err != nil {
		t.FailNow()
	}

	t.ResetTimer()
	var i int
	for i = 0; i < t.N; i++ {
		written, err := file.Write(buf)
		if err != nil {
			fmt.Printf("err=\"%s\", written=%d\n", err.Error(), written)
			t.FailNow()
		}
	}
	file.Close()
}

func BenchmarkStreamRead(t *testing.B) {
	buf := make([]byte, 1024*1024)
	t.SetBytes(int64(len(buf)))

	if t.N > 100 {
		// Grow file so we can satisfy the test
		f2, err := os.OpenFile(plainDir + "BenchmarkWrite", os.O_WRONLY | os.O_APPEND, 0666)
		if err != nil {
			fmt.Println(err)
			t.FailNow()
		}
		for h := 0; h < t.N - 100 ; h++ {
			_, err = f2.Write(buf)
			if err != nil {
				fmt.Println(err)
				t.FailNow()
			}
		}
		f2.Close()
	}

	file, err := os.Open(plainDir + "BenchmarkWrite")
	if err != nil {
		t.FailNow()
	}
	t.ResetTimer()
	var i int
	for i = 0; i < t.N; i++ {
		_, err := file.Read(buf)
		if err == io.EOF {
			fmt.Printf("Test file too small\n")
			t.SkipNow()
		} else if err != nil {
			fmt.Println(err)
			t.FailNow()
		}
	}
	file.Close()
}
<commit_msg>Make read benchmark smarter when extending file<commit_after>package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"testing"
	"time"
)

const tmpDir = "main_test_tmp/"
const plainDir = tmpDir + "plain/"
const cipherDir = tmpDir + "cipher/"

func TestMain(m *testing.M) {

	fu := exec.Command("fusermount", "-u", plainDir)
	fu.Stdout = os.Stdout
	fu.Stderr = os.Stderr
	fu.Run()
	os.RemoveAll(tmpDir)

	err := os.MkdirAll(plainDir, 0777)
	if err != nil {
		panic("Could not create plainDir")
	}

	err = os.MkdirAll(cipherDir, 0777)
	if err != nil {
		panic("Could not create cipherDir")
	}

	c := exec.Command("./gocryptfs", "--zerokey", cipherDir, plainDir)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	go c.Run()

	time.Sleep(3 * time.Second)

	r := m.Run()

	fu.Run()
	os.Exit(r)
}

func testWriteN(t *testing.T, fn string, n int) string {
	file, err := os.Create(plainDir + fn)
	if err != nil {
		t.FailNow()
	}

	d := make([]byte, n)
	written, err := file.Write(d)
	if err != nil || written != len(d) {
		fmt.Printf("err=\"%s\", written=%d\n", err, written)
		t.Fail()
	}
	file.Close()

	buf, err := ioutil.ReadFile(plainDir + fn)
	if err != nil {
		t.Fail()
	}

	raw := md5.Sum(d)
	hashWant := hex.EncodeToString(raw[:])

	raw = md5.Sum(buf)
	hashActual := hex.EncodeToString(raw[:])
	if hashActual != hashWant {
		fmt.Printf("hashWant=%s hashActual=%s\n", hashWant, hashActual)
		t.Fail()
	}

	return hashActual
}

func TestWrite10(t *testing.T) {
	testWriteN(t, "10", 10)
}

func TestWrite100(t *testing.T) {
	testWriteN(t, "100", 100)
}

func TestWrite1M(t *testing.T) {
	testWriteN(t, "1M", 1024*1024)
}

func TestWrite1Mx100(t *testing.T) {
	hashWant := testWriteN(t, "1Mx100", 1024*1024)
	// Read and check 100 times to catch race conditions
	var i int
	for i = 0; i < 100; i++ {
		buf, err := ioutil.ReadFile(plainDir + "1M")
		if err != nil {
			t.Fail()
		}
		rawHash := md5.Sum(buf)
		hashActual := hex.EncodeToString(rawHash[:])
		if hashActual != hashWant {
			fmt.Printf("Read corruption in loop # %d\n", i)
			t.FailNow()
		} else {
			//fmt.Print(".")
		}
	}
}

func BenchmarkStreamWrite(t *testing.B) {
	buf := make([]byte, 1024*1024)
	t.SetBytes(int64(len(buf)))

	file, err := os.Create(plainDir + "BenchmarkWrite")
	if err != nil {
		t.FailNow()
	}

	t.ResetTimer()
	var i int
	for i = 0; i < t.N; i++ {
		written, err := file.Write(buf)
		if err != nil {
			fmt.Printf("err=\"%s\", written=%d\n", err.Error(), written)
			t.FailNow()
		}
	}
	file.Close()
}

func BenchmarkStreamRead(t *testing.B) {
	buf := make([]byte, 1024*1024)
	t.SetBytes(int64(len(buf)))

	fn := plainDir + "BenchmarkWrite"
	fi, _ := os.Stat(fn)
	mb := int(fi.Size() / 1024 / 1024)

	if t.N > mb {
		// Grow file so we can satisfy the test
		fmt.Printf("Growing file to %d MB\n", t.N)
		f2, err := os.OpenFile(fn, os.O_WRONLY | os.O_APPEND, 0666)
		if err != nil {
			fmt.Println(err)
			t.FailNow()
		}
		for h := 0; h < t.N - mb ; h++ {
			_, err = f2.Write(buf)
			if err != nil {
				fmt.Println(err)
				t.FailNow()
			}
		}
		f2.Close()
	}

	file, err := os.Open(plainDir + "BenchmarkWrite")
	if err != nil {
		t.FailNow()
	}
	t.ResetTimer()
	var i int
	for i = 0; i < t.N; i++ {
		_, err := file.Read(buf)
		if err == io.EOF {
			fmt.Printf("Test file too small\n")
			t.SkipNow()
		} else if err != nil {
			fmt.Println(err)
			t.FailNow()
		}
	}
	file.Close()
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"compress/gzip"
	"io"
	"io/ioutil"
	"log"
	"os"
	"testing"
)

var goodOutput = `Package: vim-tiny
Source: vim
Version: 2:7.4.052-1ubuntu3
Architecture: amd64
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Installed-Size: 931
Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5
Suggests: indent
Provides: editor
Section: editors
Priority: important
Homepage: http://www.vim.org/
Description: Vi IMproved - enhanced vi editor - compact version
 Vim is an almost compatible version of the UNIX editor Vi.
 .
 Many new features have been added: multi level undo, syntax
 highlighting, command line history, on-line help, filename
 completion, block operations, folding, Unicode support, etc.
 .
 This package contains a minimal version of vim compiled with no
 GUI and a small subset of features in order to keep small the
 package size. This package does not depend on the vim-runtime
 package, but installing it you will get its additional benefits
 (online documentation, plugins, ...).
Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org>
`

var goodPkgGzOutput = `Package: vim-tiny
Source: vim
Version: 2:7.4.052-1ubuntu3
Architecture: amd64
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Installed-Size: 931
Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5
Suggests: indent
Provides: editor
Section: editors
Priority: important
Homepage: http://www.vim.org/
Description: Vi IMproved - enhanced vi editor - compact version
 Vim is an almost compatible version of the UNIX editor Vi.
 .
 Many new features have been added: multi level undo, syntax
 highlighting, command line history, on-line help, filename
 completion, block operations, folding, Unicode support, etc.
 .
 This package contains a minimal version of vim compiled with no
 GUI and a small subset of features in order to keep small the
 package size. This package does not depend on the vim-runtime
 package, but installing it you will get its additional benefits
 (online documentation, plugins, ...).
Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org>
Filename: dists/stable/main/binary-cats/test.deb
Size: 391240
MD5sum: 0ec79417129746ff789fcff0976730c5
SHA1: b2ac976af80f0f50a8336402d5a29c67a2880b9b
SHA256: 9938ec82a8c882ebc2d59b64b0bf2ac01e9cbc5a235be4aa268d4f8484e75eab

`

func TestCreateDirs(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Errorf("Unable to get current working directory: %s", err)
	}
	config := &Conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, EnableSSL: false}
	// sanity check...
	if config.RootRepoPath != pwd+"/testing" {
		t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing")
	}
	log.Println("creating temp dirs in ", config.RootRepoPath)
	dirSuccess := createDirs(*config)
	if !dirSuccess {
		t.Errorf("createDirs() failed ")
	}
	for _, archDir := range config.SupportArch {
		if _, err := os.Stat(config.RootRepoPath + "/dists/stable/main/binary-" + archDir); err != nil {
			if os.IsNotExist(err) {
				t.Errorf("Directory for %s does not exist", archDir)
			}
		}
	}

	// cleanup
	if err := os.RemoveAll(config.RootRepoPath); err != nil {
		t.Errorf("error cleaning up after createDirs(): ", err)
	}
}

func TestInspectPackageControl(t *testing.T) {
	sampleDeb, err := ioutil.ReadFile("samples/control.tar.gz")
	if err != nil {
		t.Errorf("error opening sample deb file: %s", err)
	}
	var controlBuf bytes.Buffer
	cfReader := bytes.NewReader(sampleDeb)
	io.Copy(&controlBuf, cfReader)
	parsedControl := inspectPackageControl(controlBuf)
	if parsedControl != goodOutput {
		t.Errorf("control file does not match")
	}

}

func TestInspectPackage(t *testing.T) {
	parsedControl := inspectPackage("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	if parsedControl != goodOutput {
		t.Errorf("control file does not match")
	}
}

func TestCreatePackagesGz(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Errorf("Unable to get current working directory: %s", err)
	}
	config := &Conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, EnableSSL: false}
	// sanity check...
	if config.RootRepoPath != pwd+"/testing" {
		t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing")
	}
	// copy sample deb to repo location (assuming it exists)
	origDeb, err := os.Open("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	if err != nil {
		t.Errorf("error opening up sample deb: ", err)
	}
	defer origDeb.Close()
	for _, archDir := range config.SupportArch {
		// do not use the built-in createDirs() in case it is broken
		dirErr := os.MkdirAll(config.RootRepoPath+"/dists/stable/main/binary-"+archDir, 0755)
		if dirErr != nil {
			log.Printf("error creating directory for %s: %s\n", archDir, dirErr)
		}
		copyDeb, err := os.Create(config.RootRepoPath + "/dists/stable/main/binary-" + archDir + "/test.deb")
		if err != nil {
			t.Errorf("error creating copy of deb: ", err)
		}
		_, err = io.Copy(copyDeb, origDeb)
		err = copyDeb.Close()
		if err != nil {
			t.Errorf("error saving copy of deb: ", err)
		}
	}
	if !createPackagesGz(config, "cats") {
		t.Errorf("error creating packages gzip for cats")
	}
	pkgGzip, err := ioutil.ReadFile(config.RootRepoPath + "/dists/stable/main/binary-cats/Packages.gz")
	if err != nil {
		t.Errorf("error reading Packages.gz: ", err)
	}
	pkgReader, err := gzip.NewReader(bytes.NewReader(pkgGzip))
	if err != nil {
		t.Errorf("error reading existing Packages.gz: ", err)
	}
	buf := bytes.NewBuffer(nil)
	io.Copy(buf, pkgReader)
	if goodPkgGzOutput != string(buf.Bytes()) {
		t.Errorf("Packages.gz does not match, returned value is: %s", string(buf.Bytes()))
	}

}
<commit_msg>tests for uploadHandler<commit_after>package main

import (
	"bytes"
	"compress/gzip"
	"crypto/md5"
	"encoding/hex"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
)

var goodOutput = `Package: vim-tiny
Source: vim
Version: 2:7.4.052-1ubuntu3
Architecture: amd64
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Installed-Size: 931
Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5
Suggests: indent
Provides: editor
Section: editors
Priority: important
Homepage: http://www.vim.org/
Description: Vi IMproved - enhanced vi editor - compact version
 Vim is an almost compatible version of the UNIX editor Vi.
 .
 Many new features have been added: multi level undo, syntax
 highlighting, command line history, on-line help, filename
 completion, block operations, folding, Unicode support, etc.
 .
 This package contains a minimal version of vim compiled with no
 GUI and a small subset of features in order to keep small the
 package size. This package does not depend on the vim-runtime
 package, but installing it you will get its additional benefits
 (online documentation, plugins, ...).
Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org>
`

var goodPkgGzOutput = `Package: vim-tiny
Source: vim
Version: 2:7.4.052-1ubuntu3
Architecture: amd64
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Installed-Size: 931
Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5
Suggests: indent
Provides: editor
Section: editors
Priority: important
Homepage: http://www.vim.org/
Description: Vi IMproved - enhanced vi editor - compact version
 Vim is an almost compatible version of the UNIX editor Vi.
 .
 Many new features have been added: multi level undo, syntax
 highlighting, command line history, on-line help, filename
 completion, block operations, folding, Unicode support, etc.
 .
 This package contains a minimal version of vim compiled with no
 GUI and a small subset of features in order to keep small the
 package size. This package does not depend on the vim-runtime
 package, but installing it you will get its additional benefits
 (online documentation, plugins, ...).
Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org>
Filename: dists/stable/main/binary-cats/test.deb
Size: 391240
MD5sum: 0ec79417129746ff789fcff0976730c5
SHA1: b2ac976af80f0f50a8336402d5a29c67a2880b9b
SHA256: 9938ec82a8c882ebc2d59b64b0bf2ac01e9cbc5a235be4aa268d4f8484e75eab

`

func TestCreateDirs(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Errorf("Unable to get current working directory: %s", err)
	}
	config := &Conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, EnableSSL: false}
	// sanity check...
	if config.RootRepoPath != pwd+"/testing" {
		t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing")
	}
	log.Println("creating temp dirs in ", config.RootRepoPath)
	dirSuccess := createDirs(*config)
	if !dirSuccess {
		t.Errorf("createDirs() failed ")
	}
	for _, archDir := range config.SupportArch {
		if _, err := os.Stat(config.RootRepoPath + "/dists/stable/main/binary-" + archDir); err != nil {
			if os.IsNotExist(err) {
				t.Errorf("Directory for %s does not exist", archDir)
			}
		}
	}

	// cleanup
	if err := os.RemoveAll(config.RootRepoPath); err != nil {
		t.Errorf("error cleaning up after createDirs(): ", err)
	}
}

func TestInspectPackage(t *testing.T) {
	parsedControl := inspectPackage("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	if parsedControl != goodOutput {
		t.Errorf("control file does not match")
	}
}

func TestInspectPackageControl(t *testing.T) {
	sampleDeb, err := ioutil.ReadFile("samples/control.tar.gz")
	if err != nil {
		t.Errorf("error opening sample deb file: %s", err)
	}
	var controlBuf bytes.Buffer
	cfReader := bytes.NewReader(sampleDeb)
	io.Copy(&controlBuf, cfReader)
	parsedControl := inspectPackageControl(controlBuf)
	if parsedControl != goodOutput {
		t.Errorf("control file does not match")
	}

}

func TestCreatePackagesGz(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Errorf("Unable to get current working directory: %s", err)
	}
	config := &Conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, EnableSSL: false}
	// sanity check...
	if config.RootRepoPath != pwd+"/testing" {
		t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing")
	}
	// copy sample deb to repo location (assuming it exists)
	origDeb, err := os.Open("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	if err != nil {
		t.Errorf("error opening up sample deb: ", err)
	}
	defer origDeb.Close()
	for _, archDir := range config.SupportArch {
		// do not use the built-in createDirs() in case it is broken
		dirErr := os.MkdirAll(config.RootRepoPath+"/dists/stable/main/binary-"+archDir, 0755)
		if dirErr != nil {
			log.Printf("error creating directory for %s: %s\n", archDir, dirErr)
		}
		copyDeb, err := os.Create(config.RootRepoPath + "/dists/stable/main/binary-" + archDir + "/test.deb")
		if err != nil {
			t.Errorf("error creating copy of deb: ", err)
		}
		_, err = io.Copy(copyDeb, origDeb)
		err = copyDeb.Close()
		if err != nil {
			t.Errorf("error saving copy of deb: ", err)
		}
	}
	if !createPackagesGz(config, "cats") {
		t.Errorf("error creating packages gzip for cats")
	}
	pkgGzip, err := ioutil.ReadFile(config.RootRepoPath + "/dists/stable/main/binary-cats/Packages.gz")
	if err != nil {
		t.Errorf("error reading Packages.gz: ", err)
	}
	pkgReader, err := gzip.NewReader(bytes.NewReader(pkgGzip))
	if err != nil {
		t.Errorf("error reading existing Packages.gz: ", err)
	}
	buf := bytes.NewBuffer(nil)
	io.Copy(buf, pkgReader)
	if goodPkgGzOutput != string(buf.Bytes()) {
		t.Errorf("Packages.gz does not match, returned value is: %s", string(buf.Bytes()))
	}

	// cleanup
	if err := os.RemoveAll(config.RootRepoPath); err != nil {
		t.Errorf("error cleaning up after createPackagesGz(): ", err)
	}

}

func TestUploadHandler(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Errorf("Unable to get current working directory: %s", err)
	}
	config := &Conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, EnableSSL: false}
	// sanity check...
	if config.RootRepoPath != pwd+"/testing" {
		t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing")
	}
	uploadHandle := uploadHandler(*config)
	// GET
	req, _ := http.NewRequest("GET", "", nil)
	w := httptest.NewRecorder()
	uploadHandle.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("uploadHandler GET returned %v, should be %v", w.Code, http.StatusOK)
	}

	// POST
	// create "all" arch as it's the default
	dirErr := os.MkdirAll(config.RootRepoPath+"/dists/stable/main/binary-all", 0755)
	if dirErr != nil {
		log.Printf("error creating directory for POST testing")
	}
	sampleDeb, err := os.Open("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	if err != nil {
		t.Errorf("error opening sample deb file: %s", err)
	}
	defer sampleDeb.Close()
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", "vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	if err != nil {
		t.Errorf("error FormFile: %s", err)
	}
	_, err = io.Copy(part, sampleDeb)
	if err != nil {
		t.Errorf("error copying sampleDeb to FormFile: %s", err)
	}
	err = writer.Close()
	if err != nil {
		t.Errorf("error closing form writer: %s", err)
	}
	req, _ = http.NewRequest("POST", "", body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	w = httptest.NewRecorder()
	uploadHandle.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("uploadHandler POST returned %v, should be %v", w.Code, http.StatusOK)
	}
	// verify uploaded file matches sample
	uploadFile, _ := ioutil.ReadFile(config.RootRepoPath + "/dists/stable/main/binary-all/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	uploadmd5hash := md5.New()
	io.WriteString(uploadmd5hash, string(uploadFile[:]))
	uploadFilemd5 := hex.EncodeToString(uploadmd5hash.Sum(nil))

	sampleFile, _ := ioutil.ReadFile(config.RootRepoPath + "/dists/stable/main/binary-all/vim-tiny_7.4.052-1ubuntu3_amd64.deb")
	samplemd5hash := md5.New()
	io.WriteString(samplemd5hash, string(sampleFile[:]))
	sampleFilemd5 := hex.EncodeToString(samplemd5hash.Sum(nil))
	if uploadFilemd5 != sampleFilemd5 {
		t.Errorf("uploaded file MD5 is %s, should be %s", uploadFilemd5, sampleFilemd5)
	}

	// cleanup
	if err := os.RemoveAll(config.RootRepoPath); err != nil {
		t.Errorf("error cleaning up after uploadHandler(): ", err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 Mitchell Kember. Subject to the MIT License.

package main

import (
	"bytes"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"testing"
)

func Test_display200(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	w := httptest.NewRecorder()

	display(w, "index", "HELLO")
	if w.Code != http.StatusOK {
		t.Errorf("got %d, want http.StatusOK", w.Code)
	}
	if !bytes.Contains(w.Body.Bytes(), []byte("HELLO")) {
		t.Error("index page should include string 'HELLO'")
	}
	if buf.Len() != 0 {
		t.Errorf("should not log anything: %q", buf.String())
	}
}

func Test_display500(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	w := httptest.NewRecorder()

	display(w, "nonexistent", nil)
	if w.Code != http.StatusInternalServerError {
		t.Errorf("got %d, want http.StatusInternalServerError", w.Code)
	}
	if w.Body.Len() != 0 {
		t.Error("should not render a body: %q", w.Body.String())
	}
	if !bytes.Contains(buf.Bytes(), []byte("500")) {
		t.Error("should have logged the 500")
	}
	if !bytes.Contains(buf.Bytes(), []byte("nonexistent")) {
		t.Error("should complain about the 'nonexistent' template")
	}
}

func Test_fail(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	w := httptest.NewRecorder()

	fail(w, "REASON")
	if w.Code != http.StatusNotFound {
		t.Errorf("got %d, want http.StatusNotFound", w.Code)
	}
	if !bytes.Contains(w.Body.Bytes(), []byte("404")) {
		t.Error("404 page should include string '404'")
	}
	if !bytes.Contains(buf.Bytes(), []byte("REASON")) {
		t.Error("should have logged the failure reason")
	}
}

func Test_splitPath(t *testing.T) {
	table := []struct {
		path string
		segs []string
	}{
		{"", []string{}},
		{"/", []string{}},
		{"//", []string{""}},
		{"foo/bar/baz", []string{"foo", "bar", "baz"}},
		{"/foo/bar/baz", []string{"foo", "bar", "baz"}},
		{"foo/bar/baz/", []string{"foo", "bar", "baz"}},
		{"/foo/bar/baz/", []string{"foo", "bar", "baz"}},
	}
	for i, test := range table {
		result := splitPath(test.path)
		if !reflect.DeepEqual(result, test.segs) {
			t.Errorf("[%d] got %#v, want %#v", i, result, test.segs)
		}
	}
}

func Test_parseParams(t *testing.T) {
	d := defaultParams
	table := []struct {
		rawurl string
		params parameters
	}{
		{"/", d},
		{"/abc", parameters{
			name:      "abc",
			depth:     d.depth,
			thickness: d.thickness,
			color:     d.color,
			precision: d.precision,
		}},
		{"/abc/3", parameters{
			name:      "abc",
			depth:     "3",
			thickness: d.thickness,
			color:     d.color,
			precision: d.precision,
		}},
		{"/?t=4&c=red&p=9", parameters{
			name:      d.name,
			depth:     d.depth,
			thickness: "4",
			color:     "red",
			precision: "9",
		}},
	}
	for i, test := range table {
		href, err := url.Parse(test.rawurl)
		if err != nil {
			t.Errorf("[%d] could not parse %q", i, test.rawurl)
			continue
		}

		params := parseParams(href)
		if !reflect.DeepEqual(params, test.params) {
			t.Errorf("[%d] got %#v, want %#v", i, params, test.params)
		}
	}
}

func Test_renderSVG(t *testing.T) {
	table := []struct {
		params parameters
		good   bool
	}{
		{defaultParams, true},
		{parameters{"koch", "1", "1", "black", "1"}, true},
		{parameters{"", "1", "1", "black", "1"}, false},
		{parameters{"koch", "", "1", "black", "1"}, false},
		{parameters{"koch", "1", "1", "", "1"}, false},
		{parameters{"koch", "1", "", "black", "1"}, false},
		{parameters{"koch", "1", "1", "black", ""}, false},
		{parameters{"!@#$", "1", "1", "black", "1"}, false},
		{parameters{"koch", "-1", "1", "black", "1"}, false},
		{parameters{"koch", "1", "-1", "red", "1"}, false},
		{parameters{"koch", "1", "1", "black", "-1"}, false},
	}
	for i, test := range table {
		svg, err := renderSVG(test.params)
		if test.good {
			if err != nil {
				t.Errorf("[%d] unexpected error: %q", i, err)
			} else if svg == "" {
				t.Errorf("[%d] got %q, want SVG data", i, svg)
			}
		} else {
			if err == nil {
				t.Errorf("[%d] expected error", i)
			}
		}
	}
}

func Test_mainHandlerGet(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	server := httptest.NewServer(http.HandlerFunc(mainHandler))
	defer server.Close()

	resp, err := http.Get(server.URL)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	if !bytes.Contains(body, []byte("Lindenmayer")) {
		t.Error("index page should include title 'Lindenmayer'")
	}
	if !bytes.Contains(buf.Bytes(), []byte("koch")) {
		t.Error("should log about rendering koch curve")
	}
}

func Test_mainHandlerPost(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	server := httptest.NewServer(http.HandlerFunc(mainHandler))
	defer server.Close()

	resp, err := http.Post(server.URL, "application/json", nil)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	if !bytes.Contains(body, []byte("404 Not Found")) {
		t.Error("should render a 404 page")
	}
	if !bytes.Contains(buf.Bytes(), []byte("POST")) {
		t.Error("should complain about POST request")
	}
}
<commit_msg>Update tests so that they pass<commit_after>// Copyright 2015 Mitchell Kember. Subject to the MIT License.

package main

import (
	"bytes"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"testing"
)

func Test_display200(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	w := httptest.NewRecorder()

	page := pageData{
		Name:       "koch",
		Thickness:  "3",
		Color:      "black",
		Query:      "",
		Depth:      5,
		MaxDepth:   10,
		StepFactor: 500,
		PadFactor:  1.2,
		SVG:        template.HTML("<svg>HELLO</svg>"),
		Systems:    []string{},
	}

	display(w, "index", page)
	if w.Code != http.StatusOK {
		t.Errorf("got %d, want http.StatusOK", w.Code)
	}
	if !bytes.Contains(w.Body.Bytes(), []byte("HELLO")) {
		t.Error("index page should include string 'HELLO'")
	}
	if buf.Len() != 0 {
		t.Errorf("should not log anything: %q", buf.String())
	}
}

func Test_display500(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	w := httptest.NewRecorder()

	display(w, "nonexistent", nil)
	if w.Code != http.StatusInternalServerError {
		t.Errorf("got %d, want http.StatusInternalServerError", w.Code)
	}
	if w.Body.Len() != 0 {
		t.Error("should not render a body: %q", w.Body.String())
	}
	if !bytes.Contains(buf.Bytes(), []byte("500")) {
		t.Error("should have logged the 500")
	}
	if !bytes.Contains(buf.Bytes(), []byte("nonexistent")) {
		t.Error("should complain about the 'nonexistent' template")
	}
}

func Test_fail(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	w := httptest.NewRecorder()

	fail(w, "REASON")
	if w.Code != http.StatusNotFound {
		t.Errorf("got %d, want http.StatusNotFound", w.Code)
	}
	if !bytes.Contains(w.Body.Bytes(), []byte("404")) {
		t.Error("404 page should include string '404'")
	}
	if !bytes.Contains(buf.Bytes(), []byte("REASON")) {
		t.Error("should have logged the failure reason")
	}
}

func Test_splitPath(t *testing.T) {
	table := []struct {
		path string
		segs []string
		ext  string
	}{
		{"", []string{}, ""},
		{"/", []string{}, ""},
		{"//", []string{""}, ""},
		{"foo/bar/baz", []string{"foo", "bar", "baz"}, ""},
		{"/foo/bar/baz", []string{"foo", "bar", "baz"}, ""},
		{"foo/bar/baz/", []string{"foo", "bar", "baz"}, ""},
		{"/foo/bar/baz/", []string{"foo", "bar", "baz"}, ""},
		{".", []string{}, ""},
		{".html", []string{}, "html"},
		{"/a/b.svg", []string{"a", "b"}, "svg"},
		{"/a/b/.svg/", []string{"a", "b"}, "svg"},
	}
	for i, test := range table {
		segs, ext := splitPath(test.path)
		if !reflect.DeepEqual(segs, test.segs) || ext != test.ext {
			t.Errorf("[%d] got (%#v, %q), want (%#v, %q)",
				i, segs, ext, test.segs, test.ext)
		}
	}
}

func Test_parseParams(t *testing.T) {
	d := defaultParams
	table := []struct {
		rawurl string
		params parameters
	}{
		{"/", d},
		{"/abc", parameters{
			name:      "abc",
			depth:     d.depth,
			thickness: d.thickness,
			color:     d.color,
			precision: d.precision,
			onlySVG:   d.onlySVG,
		}},
		{"/abc/3", parameters{
			name:      "abc",
			depth:     "3",
			thickness: d.thickness,
			color:     d.color,
			precision: d.precision,
			onlySVG:   d.onlySVG,
		}},
		{"/?t=4&c=red&p=9", parameters{
			name:      d.name,
			depth:     d.depth,
			thickness: "4",
			color:     "red",
			precision: "9",
			onlySVG:   d.onlySVG,
		}},
		{"/xyz/7.svg", parameters{
			name:      "xyz",
			depth:     "7",
			thickness: d.thickness,
			color:     d.color,
			precision: d.precision,
			onlySVG:   true,
		}},
	}
	for i, test := range table {
		href, err := url.Parse(test.rawurl)
		if err != nil {
			t.Errorf("[%d] could not parse %q", i, test.rawurl)
			continue
		}

		params := parseParams(href)
		if !reflect.DeepEqual(params, test.params) {
			t.Errorf("[%d] got %#v, want %#v", i, params, test.params)
		}
	}
}

func Test_renderSVG(t *testing.T) {
	table := []struct {
		params parameters
		good   bool
	}{
		{defaultParams, true},
		{parameters{"koch", "1", "1", "black", "1", false}, true},
		{parameters{"", "1", "1", "black", "1", false}, false},
		{parameters{"koch", "", "1", "black", "1", false}, false},
		{parameters{"koch", "1", "1", "", "1", true}, false},
		{parameters{"koch", "1", "", "black", "1", false}, false},
		{parameters{"koch", "1", "1", "black", "", false}, false},
		{parameters{"!@#$", "1", "1", "black", "1", true}, false},
		{parameters{"koch", "-1", "1", "black", "1", true}, false},
		{parameters{"koch", "1", "-1", "red", "1", false}, false},
		{parameters{"koch", "1", "1", "black", "-1", true}, false},
	}
	for i, test := range table {
		svg, err := renderSVG(test.params)
		if test.good {
			if err != nil {
				t.Errorf("[%d] unexpected error: %q", i, err)
			} else if svg == "" {
				t.Errorf("[%d] got %q, want SVG data", i, svg)
			}
		} else {
			if err == nil {
				t.Errorf("[%d] expected error", i)
			}
		}
	}
}

func Test_mainHandlerGet(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	server := httptest.NewServer(http.HandlerFunc(mainHandler))
	defer server.Close()

	resp, err := http.Get(server.URL)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	if !bytes.Contains(body, []byte("Lindenmayer")) {
		t.Error("index page should include title 'Lindenmayer'")
	}
	if !bytes.Contains(buf.Bytes(), []byte("koch")) {
		t.Error("should log about rendering koch curve")
	}
}

func Test_mainHandlerPost(t *testing.T) {
	var buf bytes.Buffer
	log.SetOutput(&buf)
	server := httptest.NewServer(http.HandlerFunc(mainHandler))
	defer server.Close()

	resp, err := http.Post(server.URL, "application/json", nil)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Errorf("unexpected error: %q", err)
	}
	if !bytes.Contains(body, []byte("404 Not Found")) {
		t.Error("should render a 404 page")
	}
	if !bytes.Contains(buf.Bytes(), []byte("POST")) {
		t.Error("should complain about POST request")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/pichuio/halftone/algorithm"
	"github.com/pichuio/halftone/common"
	"testing"
)

func TestDitherResult(t *testing.T) {
	//	worker := common.NewImageWorker()
	//	img1, _ := worker.LoadImage("images/processing/seq_result.png")
	//	img2, _ := worker.LoadImage("images/original/Michelangelo_Result.png")

	//	width1, height1 := worker.GetImageDemensions(img1)

	//	width2, height2 := worker.GetImageDemensions(img2)

	//	if width1 != width2 {
	//		t.Errorf("TestDitherResult - Width %v %v", width1, width2)
	//	}

	//	if height1 != height2 {
	//		t.Errorf("TestDitherResult - Height %v %v", height1, height2)
	//	}

	//	errCount := 0

	//	for x := 0; x < width1; x++ {
	//		for y := 0; y < height1; y++ {
	//			pixel := img1.At(x, y)
	//			red1, green1, blue1, _ := pixel.RGBA()

	//			pixel = img2.At(x, y)
	//			red2, green2, blue2, _ := pixel.RGBA()

	//			if red1 != red2 || green1 != green2 || blue1 != blue2 {
	//				//t.Errorf("TestDitherResult - Red %v %v Green %v %v Blue %v %v", red1, red2, green1, green2, blue1, blue2)
	//				errCount++
	//			}
	//		}
	//	}
	//	if errCount > 0 {
	//		t.Errorf("TestDitherResult - Count %v (%v)", errCount, height1*width1)
	//	}
}

func TestColorToGray(t *testing.T) {
	worker := common.NewImageWorker()
	img1, _ := worker.LoadImage("images/processing/seq_grayImage.png")
	img2, _ := worker.LoadImage("images/processing/seq_grayImage2.png")

	width1, height1 := worker.GetImageDemensions(img1)

	width2, height2 := worker.GetImageDemensions(img2)

	if width1 != width2 {
		t.Errorf("TestDitherResult - Width %v %v", width1, width2)
	}

	if height1 != height2 {
		t.Errorf("TestDitherResult - Height %v %v", height1, height2)
	}

	for x := 0; x < width1; x++ {
		for y := 0; y < height1; y++ {
			pixel := img1.At(x, y)
			red1, green1, blue1, _ := pixel.RGBA()

			pixel = img2.At(x, y)
			red2, green2, blue2, _ := pixel.RGBA()

			if red1 != red2 {
				t.Errorf("TestDitherResult - Red %v %v", red1, red2)
			}

			if green1 != green2 {
				t.Errorf("TestDitherResult - Green %v %v", green1, green2)
			}

			if blue1 != blue2 {
				t.Errorf("TestDitherResult - Blue %v %v", blue1, blue2)
			}
		}
	}
}

func TestDitherResult2(t *testing.T) {
	grayArr := common.NewArray(200, 100)
	for x := 0; x < grayArr.Width; x++ {
		for y := 0; y < grayArr.Height; y++ {
			grayArr.Array[x][y] = 127
		}
	}
	newArr := algorithm.DitheringMatrix2x3_2(grayArr, 1.0)
	for x := 0; x < grayArr.Width; x++ {
		for y := 0; y < grayArr.Height; y++ {
			xMod2 := x%2 == 0
			yMod2 := y%2 == 0

			if (xMod2 && !yMod2) || (!xMod2 && yMod2) {
				//BLACK
				if newArr.Array[x][newArr.Height-1-y] != 255 {
					t.Errorf("TestDitherResult2 != 255 - [%v][%v] %v", x, newArr.Height-1-y, newArr.Array[x][newArr.Height-1-y])
				}
			} else {
				if newArr.Array[x][newArr.Height-1-y] != 0 {
					t.Errorf("TestDitherResult2 != 0 - [%v][%v] %v", x, newArr.Height-1-y, newArr.Array[x][newArr.Height-1-y])
				}
			}
		}
	}

	dst := algorithm.ConvertGrayArrayToImage(newArr)

	worker := common.NewImageWorker()
	worker.SaveImage("images/testing/chessboard.png", dst)
}
<commit_msg>broken main test<commit_after>package main

import (
	"github.com/pichuio/halftone/algorithm"
	"github.com/pichuio/halftone/common"
	"testing"
)

func TestDitherResult(t *testing.T) {
	//	worker := common.NewImageWorker()
	//	img1, _ := worker.LoadImage("images/processing/seq_result.png")
	//	img2, _ := worker.LoadImage("images/original/Michelangelo_Result.png")

	//	width1, height1 := worker.GetImageDemensions(img1)

	//	width2, height2 := worker.GetImageDemensions(img2)

	//	if width1 != width2 {
	//		t.Errorf("TestDitherResult - Width %v %v", width1, width2)
	//	}

	//	if height1 != height2 {
	//		t.Errorf("TestDitherResult - Height %v %v", height1, height2)
	//	}

	//	errCount := 0

	//	for x := 0; x < width1; x++ {
	//		for y := 0; y < height1; y++ {
	//			pixel := img1.At(x, y)
	//			red1, green1, blue1, _ := pixel.RGBA()

	//			pixel = img2.At(x, y)
	//			red2, green2, blue2, _ := pixel.RGBA()

	//			if red1 != red2 || green1 != green2 || blue1 != blue2 {
	//				//t.Errorf("TestDitherResult - Red %v %v Green %v %v Blue %v %v", red1, red2, green1, green2, blue1, blue2)
	//				errCount++
	//			}
	//		}
	//	}
	//	if errCount > 0 {
	//		t.Errorf("TestDitherResult - Count %v (%v)", errCount, height1*width1)
	//	}
}

func TestColorToGray(t *testing.T) {
	//	worker := common.NewImageWorker()
	//	img1, _ := worker.LoadImage("images/processing/seq_grayImage.png")
	//	img2, _ := worker.LoadImage("images/processing/seq_grayImage2.png")

	//	width1, height1 := worker.GetImageDemensions(img1)

	//	width2, height2 := worker.GetImageDemensions(img2)

	//	if width1 != width2 {
	//		t.Errorf("TestDitherResult - Width %v %v", width1, width2)
	//	}

	//	if height1 != height2 {
	//		t.Errorf("TestDitherResult - Height %v %v", height1, height2)
	//	}

	//	for x := 0; x < width1; x++ {
	//		for y := 0; y < height1; y++ {
	//			pixel := img1.At(x, y)
	//			red1, green1, blue1, _ := pixel.RGBA()

	//			pixel = img2.At(x, y)
	//			red2, green2, blue2, _ := pixel.RGBA()

	//			if red1 != red2 {
	//				t.Errorf("TestDitherResult - Red %v %v", red1, red2)
	//			}

	//			if green1 != green2 {
	//				t.Errorf("TestDitherResult - Green %v %v", green1, green2)
	//			}

	//			if blue1 != blue2 {
	//				t.Errorf("TestDitherResult - Blue %v %v", blue1, blue2)
	//			}
	//		}
	//	}
}

func TestDitherResult2(t *testing.T) {
	//	grayArr := common.NewArray(200, 100)
	//	for x := 0; x < grayArr.Width; x++ {
	//		for y := 0; y < grayArr.Height; y++ {
	//			grayArr.Array[x][y] = 127
	//		}
	//	}
	//	newArr := algorithm.DitheringMatrix2x3_2(grayArr, 1.0)
	//	for x := 0; x < grayArr.Width; x++ {
	//		for y := 0; y < grayArr.Height; y++ {
	//			xMod2 := x%2 == 0
	//			yMod2 := y%2 == 0

	//			if (xMod2 && !yMod2) || (!xMod2 && yMod2) {
	//				//BLACK
	//				if newArr.Array[x][newArr.Height-1-y] != 255 {
	//					t.Errorf("TestDitherResult2 != 255 - [%v][%v] %v", x, newArr.Height-1-y, newArr.Array[x][newArr.Height-1-y])
	//				}
	//			} else {
	//				if newArr.Array[x][newArr.Height-1-y] != 0 {
	//					t.Errorf("TestDitherResult2 != 0 - [%v][%v] %v", x, newArr.Height-1-y, newArr.Array[x][newArr.Height-1-y])
	//				}
	//			}
	//		}
	//	}

	//	dst := algorithm.ConvertGrayArrayToImage(newArr)

	//	worker := common.NewImageWorker()
	//	worker.SaveImage("images/testing/chessboard.png", dst)
}
<|endoftext|>


<commit_before>// +build linux

package native

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path"
	"strings"
	"text/template"

	"github.com/docker/docker/pkg/aaparser"
	"github.com/opencontainers/runc/libcontainer/apparmor"
)

const (
	apparmorProfilePath = "/etc/apparmor.d/docker"
)

type data struct {
	Name         string
	ExecPath     string
	Imports      []string
	InnerImports []string
	MajorVersion int
	MinorVersion int
}

const baseTemplate = `
{{range $value := .Imports}}
{{$value}}
{{end}}

profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
{{range $value := .InnerImports}}
  {{$value}}
{{end}}

  network,
  capability,
  file,
  umount,

  deny @{PROC}/{*,**^[0-9]*,sys/kernel/shm*} wkx,
  deny @{PROC}/sysrq-trigger rwklx,
  deny @{PROC}/mem rwklx,
  deny @{PROC}/kmem rwklx,
  deny @{PROC}/kcore rwklx,

  deny mount,

  deny /sys/[^f]*/** wklx,
  deny /sys/f[^s]*/** wklx,
  deny /sys/fs/[^c]*/** wklx,
  deny /sys/fs/c[^g]*/** wklx,
  deny /sys/fs/cg[^r]*/** wklx,
  deny /sys/firmware/efi/efivars/** rwklx,
  deny /sys/kernel/security/** rwklx,

{{if ge .MajorVersion 2}}{{if ge .MinorVersion 9}}
  # docker daemon confinement requires explict allow rule for signal
  signal (receive) set=(kill,term) peer={{.ExecPath}},

  # suppress ptrace denails when using 'docker ps'
  ptrace (trace,read) peer=docker-default,
{{end}}{{end}}
}
`

func generateProfile(out io.Writer) error {
	compiled, err := template.New("apparmor_profile").Parse(baseTemplate)
	if err != nil {
		return err
	}
	data := &data{
		Name: "docker-default",
	}
	if tunablesExists() {
		data.Imports = append(data.Imports, "#include <tunables/global>")
	} else {
		data.Imports = append(data.Imports, "@{PROC}=/proc/")
	}
	if abstractionsExists() {
		data.InnerImports = append(data.InnerImports, "#include <abstractions/base>")
	}
	data.MajorVersion, data.MinorVersion, err = aaparser.GetVersion()
	if err != nil {
		return err
	}
	data.ExecPath, err = exec.LookPath("docker")
	if err != nil {
		return err
	}
	if err := compiled.Execute(out, data); err != nil {
		return err
	}
	return nil
}

// check if the tunables/global exist
func tunablesExists() bool {
	_, err := os.Stat("/etc/apparmor.d/tunables/global")
	return err == nil
}

// check if abstractions/base exist
func abstractionsExists() bool {
	_, err := os.Stat("/etc/apparmor.d/abstractions/base")
	return err == nil
}

func installAppArmorProfile() error {
	if !apparmor.IsEnabled() {
		return nil
	}

	// Make sure /etc/apparmor.d exists
	if err := os.MkdirAll(path.Dir(apparmorProfilePath), 0755); err != nil {
		return err
	}

	f, err := os.OpenFile(apparmorProfilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	if err := generateProfile(f); err != nil {
		f.Close()
		return err
	}
	f.Close()

	cmd := exec.Command("/sbin/apparmor_parser", "-r", "-W", "docker")
	// to use the parser directly we have to make sure we are in the correct
	// dir with the profile
	cmd.Dir = "/etc/apparmor.d"

	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("Error loading docker apparmor profile: %s (%s)", err, output)
	}
	return nil
}

func hasAppArmorProfileLoaded(profile string) error {
	file, err := os.Open("/sys/kernel/security/apparmor/profiles")
	if err != nil {
		return err
	}
	r := bufio.NewReader(file)
	for {
		p, err := r.ReadString('\n')
		if err != nil {
			return err
		}
		if strings.HasPrefix(p, profile+" ") {
			return nil
		}
	}
}
<commit_msg>Enable ptrace in a container on apparmor below 2.9<commit_after>// +build linux

package native

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path"
	"strings"
	"text/template"

	"github.com/docker/docker/pkg/aaparser"
	"github.com/opencontainers/runc/libcontainer/apparmor"
)

const (
	apparmorProfilePath = "/etc/apparmor.d/docker"
)

type data struct {
	Name         string
	ExecPath     string
	Imports      []string
	InnerImports []string
	MajorVersion int
	MinorVersion int
}

const baseTemplate = `
{{range $value := .Imports}}
{{$value}}
{{end}}

profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
{{range $value := .InnerImports}}
  {{$value}}
{{end}}

  network,
  capability,
  file,
  umount,

  deny @{PROC}/{*,**^[0-9]*,sys/kernel/shm*} wkx,
  deny @{PROC}/sysrq-trigger rwklx,
  deny @{PROC}/mem rwklx,
  deny @{PROC}/kmem rwklx,
  deny @{PROC}/kcore rwklx,

  deny mount,

  deny /sys/[^f]*/** wklx,
  deny /sys/f[^s]*/** wklx,
  deny /sys/fs/[^c]*/** wklx,
  deny /sys/fs/c[^g]*/** wklx,
  deny /sys/fs/cg[^r]*/** wklx,
  deny /sys/firmware/efi/efivars/** rwklx,
  deny /sys/kernel/security/** rwklx,

{{if ge .MajorVersion 2}}{{if ge .MinorVersion 8}}
  # suppress ptrace denials when using 'docker ps' or using 'ps' inside a container
  ptrace (trace,read) peer=docker-default,
{{end}}{{end}}
{{if ge .MajorVersion 2}}{{if ge .MinorVersion 9}}
  # docker daemon confinement requires explict allow rule for signal
  signal (receive) set=(kill,term) peer={{.ExecPath}},
{{end}}{{end}}
}
`

func generateProfile(out io.Writer) error {
	compiled, err := template.New("apparmor_profile").Parse(baseTemplate)
	if err != nil {
		return err
	}
	data := &data{
		Name: "docker-default",
	}
	if tunablesExists() {
		data.Imports = append(data.Imports, "#include <tunables/global>")
	} else {
		data.Imports = append(data.Imports, "@{PROC}=/proc/")
	}
	if abstractionsExists() {
		data.InnerImports = append(data.InnerImports, "#include <abstractions/base>")
	}
	data.MajorVersion, data.MinorVersion, err = aaparser.GetVersion()
	if err != nil {
		return err
	}
	data.ExecPath, err = exec.LookPath("docker")
	if err != nil {
		return err
	}
	if err := compiled.Execute(out, data); err != nil {
		return err
	}
	return nil
}

// check if the tunables/global exist
func tunablesExists() bool {
	_, err := os.Stat("/etc/apparmor.d/tunables/global")
	return err == nil
}

// check if abstractions/base exist
func abstractionsExists() bool {
	_, err := os.Stat("/etc/apparmor.d/abstractions/base")
	return err == nil
}

func installAppArmorProfile() error {
	if !apparmor.IsEnabled() {
		return nil
	}

	// Make sure /etc/apparmor.d exists
	if err := os.MkdirAll(path.Dir(apparmorProfilePath), 0755); err != nil {
		return err
	}

	f, err := os.OpenFile(apparmorProfilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}
	if err := generateProfile(f); err != nil {
		f.Close()
		return err
	}
	f.Close()

	cmd := exec.Command("/sbin/apparmor_parser", "-r", "-W", "docker")
	// to use the parser directly we have to make sure we are in the correct
	// dir with the profile
	cmd.Dir = "/etc/apparmor.d"

	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("Error loading docker apparmor profile: %s (%s)", err, output)
	}
	return nil
}

func hasAppArmorProfileLoaded(profile string) error {
	file, err := os.Open("/sys/kernel/security/apparmor/profiles")
	if err != nil {
		return err
	}
	r := bufio.NewReader(file)
	for {
		p, err := r.ReadString('\n')
		if err != nil {
			return err
		}
		if strings.HasPrefix(p, profile+" ") {
			return nil
		}
	}
}
<|endoftext|>