<commit_before>package es

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	"time"
)

const (
	OK  = '2'
	AND = "AND"
	OR  = "OR"
)

type Logger interface {
	Debug(format string, i ...interface{})
	Info(format string, i ...interface{})
	Error(format string, i ...interface{})
}

type Analysis struct {
	Analyzer Analyzer `json:"analyzer"`
}

type Analyzer struct {
	Default AnalyzerType `json:"default"`
}

type AnalyzerType struct {
	Type      string `json:"type,omitempty"`
	Tokenizer string `json:"tokenizer,omitempty"`
}

type IndexConfig struct {
	Index IndexIndexConfig `json:"index"`
}

type IndexIndexConfig struct {
	Analysis Analysis `json:"analysis"`
}

func KeywordIndex() IndexConfig {
	return IndexConfig{
		Index: IndexIndexConfig{
			Analysis: Analysis{
				Analyzer: Analyzer{
					Default: AnalyzerType{
						Tokenizer: "whitespace",
					},
				},
			},
		},
	}
}

func (index *Index) CreateIndex(config IndexConfig) (rsp *HttpResponse, e error) {
	return index.request("PUT", index.IndexUrl(), config)
}

type Term map[string]interface{}

type Terms map[string][]interface{}

type Filter struct {
	And   []*Filter         `json:"and,omitempty"`
	Term  *Term             `json:"term,omitempty"`
	Terms *Terms            `json:"term,omitempty"`
	Range map[string]*Range `json:"range,omitempty"`
}

type Range struct {
	From interface{}
	To   interface{}
}

type Filtered struct {
	Filter *Filter
}

type QueryString struct {
	Query           string `json:"query,omitempty"`
	DefaultOperator string `json:"default_operator,omitempty"`
}

type Query struct {
	Filtered    *Filtered    `json:"filtered,omitempty"`
	QueryString *QueryString `json:"query_string,omitempty"`
}

var query = Query{
	Filtered: &Filtered{
		Filter: &Filter{
			And: []*Filter{
				{
					Term: &Term{
						"Device": "Anrdoi",
					},
				},
				{
					Terms: &Terms{
						"Action": []interface{}{
							"api/v1/my/photos#create",
							"api/v1/photos#create",
						},
					},
					Range: map[string]*Range{
						"Time": {
							From: "",
						},
					},
				},
			},
		},
	},
}

type BulkIndexJob struct {
	Key    string
	Type   string
	Index  string
	Record interface{}
}

type Index struct {
	Host      string
	Port      int
	Index     string
	Type      string
	batchDocs []*Doc
	BatchSize int
	Debug     bool
	Logger    Logger
}

func (index *Index) IndexExists() (exists bool, e error) {
	if index.Index == "" {
		return false, fmt.Errorf("no index set")
	}
	rsp, e := http.Get(index.IndexUrl() + "/_status")
	if e != nil {
		return false, e
	}
	return rsp.Status[0] == '2', nil
}

func (index *Index) EnqueueDoc(doc *Doc) (indexed bool, e error) {
	if index.BatchSize == 0 {
		index.BatchSize = 100
	}
	if cap(index.batchDocs) == 0 {
		index.ResetBatch()
	}
	index.batchDocs = append(index.batchDocs, doc)
	if len(index.batchDocs) >= index.BatchSize {
		return true, index.RunBatchIndex()
	}
	return false, nil
}

func (index *Index) ResetBatch() {
	index.batchDocs = make([]*Doc, 0, index.BatchSize)
}

func (index *Index) EnqueueBulkIndex(key string, record interface{}) (bool, error) {
	return index.EnqueueDoc(&Doc{
		Id: key, Source: record,
	})
}

func (index *Index) DeleteIndex() error {
	req, e := http.NewRequest("DELETE", index.IndexUrl(), nil)
	if e != nil {
		return e
	}
	rsp, e := http.DefaultClient.Do(req)
	if e != nil {
		return e
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		return fmt.Errorf("Error delting index at %s: %s", index.TypeUrl(), rsp.Status)
	}
	return nil
}

func (index *Index) Refresh() error {
	rsp, e := index.request("POST", index.IndexUrl()+"/_refresh", nil)
	if e != nil {
		return e
	}
	if rsp.Status[0] != '2' {
		return fmt.Errorf("Error refreshing index: %s", rsp.Status)
	}
	return nil
}

func (index *Index) IndexDocs(docs []*Doc) error {
	buf := &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	for _, doc := range docs {
		if doc.Index == "" {
			doc.Index = index.Index
		}
		if doc.Type == "" {
			doc.Type = index.Type
		}
		enc.Encode(map[string]map[string]string{
			"index": doc.IndexAttributes(),
		})
		enc.Encode(doc.Source)
	}
	rsp, e := http.Post(index.BaseUrl()+"/_bulk", "application/json", buf)
	if e != nil {
		return e
	}
	defer rsp.Body.Close()
	b, _ := ioutil.ReadAll(rsp.Body)
	if rsp.Status[0] != OK {
		return fmt.Errorf("Error sending bulk request: %s %s", rsp.Status, string(b))
	}
	return nil
}

func (index *Index) RunBatchIndex() error {
	if len(index.batchDocs) == 0 {
		return nil
	}
	started := time.Now()
	e := index.IndexDocs(index.batchDocs)
	if e != nil {
		return e
	}
	perSecond := float64(len(index.batchDocs)) / time.Now().Sub(started).Seconds()
	index.LogDebug("indexed %d, %.1f/second\n", len(index.batchDocs), perSecond)
	index.ResetBatch()
	return nil
}

type Status struct {
	Ok     bool    `json:"ok"`
	Shards *Shards `json:"_shards"`
}

type Shards struct {
	Total      int `json:"total"`
	Successful int `json:"successful"`
	Failed     int `json:"failed"`
}

func (index *Index) Status() (status *Status, e error) {
	rsp, e := http.Get(index.BaseUrl() + "/_status")
	if e != nil {
		return nil, e
	}
	defer rsp.Body.Close()
	b, e := ioutil.ReadAll(rsp.Body)
	if e != nil {
		return nil, e
	}
	if rsp.Status[0] != '2' {
		return nil, fmt.Errorf("Status: %d, Response: %s", rsp.StatusCode, string(b))
	}
	status = &Status{}
	e = json.Unmarshal(b, status)
	return status, e
}

func init() {
	log.SetFlags(0)
}

func (index *Index) LogDebug(format string, i ...interface{}) {
	if index.Logger != nil {
		index.Logger.Debug(format, i...)
	}
}

func (index *Index) LogInfo(format string, i ...interface{}) {
	if index.Logger != nil {
		index.Logger.Info(format, i...)
	}
}

func (index *Index) GlobalMapping() (m *Mapping, e error) {
	m = &Mapping{}
	u := index.BaseUrl() + "/_mapping"
	index.LogInfo("checking for url %s", u)
	rsp, e := index.request("GET", u, m)
	if rsp != nil && rsp.StatusCode == 404 {
		return nil, nil
	} else if e != nil {
		return nil, e
	}
	e = json.Unmarshal(rsp.Body, m)
	if e != nil {
		return nil, e
	}
	return m, nil
}

func (index *Index) Stats() (*Stats, error) {
	rsp, e := http.Get(index.IndexUrl() + "/_stats")
	if e != nil {
		return nil, e
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		return nil, fmt.Errorf("expected status 2xx, got %s", rsp.Status)
	}
	stats := &Stats{}
	e = json.NewDecoder(rsp.Body).Decode(stats)
	return stats, e
}

func (index *Index) Mapping() (i interface{}, e error) {
	u := index.IndexUrl() + "/_mapping"
	rsp, e := index.request("GET", u, i)
	if rsp != nil && rsp.StatusCode == 404 {
		return nil, nil
	} else if e != nil {
		return nil, e
	}
	e = json.Unmarshal(rsp.Body, &i)
	if e != nil {
		return nil, e
	}
	return i, nil
}

func (index *Index) PutMapping(mapping interface{}) (rsp *HttpResponse, e error) {
	return index.request("PUT", index.IndexUrl()+"/", mapping)
}

func (index *Index) BaseUrl() string {
	if index.Port == 0 {
		index.Port = 9200
	}
	return fmt.Sprintf("http://%s:%d", index.Host, index.Port)
}

func (index *Index) IndexUrl() string {
	if index.Index == "" {
		return index.BaseUrl()
	} else {
		return index.BaseUrl() + "/" + index.Index
	}
}

func (index *Index) TypeUrl() string {
	if index.Type == "" {
		return index.IndexUrl()
	} else if idx := index.IndexUrl(); idx != "" {
		return idx + "/" + index.Type
	} else {
		return ""
	}
}

func (index *Index) DeleteByQuery(query string) (b []byte, e error) {
	q := &url.Values{}
	q.Add("q", query)
	rsp, e := index.request("DELETE", index.TypeUrl()+"/_query?"+q.Encode(), nil)
	if e != nil {
		return b, e
	}
	if rsp.Status[0] != '2' {
		return b, fmt.Errorf("error deleting with query: %s", rsp.Status)
	}
	return rsp.Body, nil
}

func (index *Index) Search(req *Request) (rsp *Response, e error) {
	u := index.TypeUrl()
	if !strings.HasSuffix(u, "/") {
		u += "/"
	}
	u += "/_search"
	httpRequest, e := http.NewRequest("POST", u, nil)
	if e != nil {
		return nil, e
	}
	if req != nil {
		writer := &bytes.Buffer{}
		js := json.NewEncoder(writer)
		e = js.Encode(req)
		if e != nil {
			return nil, e
		}
		httpRequest.Body = ioutil.NopCloser(writer)
	}
	httpResponse, e := http.DefaultClient.Do(httpRequest)
	if e != nil {
		return nil, e
	}
	defer httpResponse.Body.Close()
	dec := json.NewDecoder(httpResponse.Body)
	rsp = &Response{}
	e = dec.Decode(rsp)
	if e != nil {
		return nil, e
	}
	return rsp, nil
}

func (index *Index) Post(u string, i interface{}) (*HttpResponse, error) {
	return index.request("POST", u, i)
}

func (index *Index) PostObject(i interface{}) (*HttpResponse, error) {
	return index.request("POST", index.TypeUrl(), i)
}

func (index *Index) PutObject(id string, i interface{}) (*HttpResponse, error) {
	return index.request("PUT", index.TypeUrl()+"/"+id, i)
}

func (index *Index) Put(u string, i interface{}) (*HttpResponse, error) {
	return index.request("PUT", u, i)
}

type HttpResponse struct {
	*http.Response
	Body []byte
}

func (index *Index) request(method string, u string, i interface{}) (httpResponse *HttpResponse, e error) {
	var req *http.Request
	if i != nil {
		buf := &bytes.Buffer{}
		encoder := json.NewEncoder(buf)
		if e := encoder.Encode(i); e != nil {
			return nil, e
		}
		req, e = http.NewRequest(method, u, buf)
	} else {
		req, e = http.NewRequest(method, u, nil)
	}
	if e != nil {
		return nil, e
	}
	rsp, e := http.DefaultClient.Do(req)
	if e != nil {
		return nil, e
	}
	defer rsp.Body.Close()
	b, e := ioutil.ReadAll(rsp.Body)
	if e != nil {
		return nil, e
	}
	httpResponse = &HttpResponse{
		Response: rsp,
		Body:     b,
	}
	if e != nil {
		return httpResponse, e
	}
	if rsp.Status[0] != OK {
		return httpResponse, fmt.Errorf("error indexing: %s %s", rsp.Status, string(b))
	}
	return httpResponse, nil
}
<commit_msg>change json unmarshalling<commit_after>package es

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"
	"time"
)

const (
	OK  = '2'
	AND = "AND"
	OR  = "OR"
)

type Logger interface {
	Debug(format string, i ...interface{})
	Info(format string, i ...interface{})
	Error(format string, i ...interface{})
}

type Analysis struct {
	Analyzer Analyzer `json:"analyzer"`
}

type Analyzer struct {
	Default AnalyzerType `json:"default"`
}

type AnalyzerType struct {
	Type      string `json:"type,omitempty"`
	Tokenizer string `json:"tokenizer,omitempty"`
}

type IndexConfig struct {
	Index IndexIndexConfig `json:"index"`
}

type IndexIndexConfig struct {
	Analysis Analysis `json:"analysis"`
}

func KeywordIndex() IndexConfig {
	return IndexConfig{
		Index: IndexIndexConfig{
			Analysis: Analysis{
				Analyzer: Analyzer{
					Default: AnalyzerType{
						Tokenizer: "whitespace",
					},
				},
			},
		},
	}
}

func (index *Index) CreateIndex(config IndexConfig) (rsp *HttpResponse, e error) {
	return index.request("PUT", index.IndexUrl(), config)
}

type Term map[string]interface{}

type Terms map[string][]interface{}

type Filter struct {
	And   []*Filter         `json:"and,omitempty"`
	Term  *Term             `json:"term,omitempty"`
	Terms *Terms            `json:"term,omitempty"`
	Range map[string]*Range `json:"range,omitempty"`
}

type Range struct {
	From interface{}
	To   interface{}
}

type Filtered struct {
	Filter *Filter
}

type QueryString struct {
	Query           string `json:"query,omitempty"`
	DefaultOperator string `json:"default_operator,omitempty"`
}

type Query struct {
	Filtered    *Filtered    `json:"filtered,omitempty"`
	QueryString *QueryString `json:"query_string,omitempty"`
}

var query = Query{
	Filtered: &Filtered{
		Filter: &Filter{
			And: []*Filter{
				{
					Term: &Term{
						"Device": "Anrdoi",
					},
				},
				{
					Terms: &Terms{
						"Action": []interface{}{
							"api/v1/my/photos#create",
							"api/v1/photos#create",
						},
					},
					Range: map[string]*Range{
						"Time": {
							From: "",
						},
					},
				},
			},
		},
	},
}

type BulkIndexJob struct {
	Key    string
	Type   string
	Index  string
	Record interface{}
}

type Index struct {
	Host      string
	Port      int
	Index     string
	Type      string
	batchDocs []*Doc
	BatchSize int
	Debug     bool
	Logger    Logger
}

func (index *Index) IndexExists() (exists bool, e error) {
	if index.Index == "" {
		return false, fmt.Errorf("no index set")
	}
	rsp, e := http.Get(index.IndexUrl() + "/_status")
	if e != nil {
		return false, e
	}
	return rsp.Status[0] == '2', nil
}

func (index *Index) EnqueueDoc(doc *Doc) (indexed bool, e error) {
	if index.BatchSize == 0 {
		index.BatchSize = 100
	}
	if cap(index.batchDocs) == 0 {
		index.ResetBatch()
	}
	index.batchDocs = append(index.batchDocs, doc)
	if len(index.batchDocs) >= index.BatchSize {
		return true, index.RunBatchIndex()
	}
	return false, nil
}

func (index *Index) ResetBatch() {
	index.batchDocs = make([]*Doc, 0, index.BatchSize)
}

func (index *Index) EnqueueBulkIndex(key string, record interface{}) (bool, error) {
	return index.EnqueueDoc(&Doc{
		Id: key, Source: record,
	})
}

func (index *Index) DeleteIndex() error {
	req, e := http.NewRequest("DELETE", index.IndexUrl(), nil)
	if e != nil {
		return e
	}
	rsp, e := http.DefaultClient.Do(req)
	if e != nil {
		return e
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		return fmt.Errorf("Error delting index at %s: %s", index.TypeUrl(), rsp.Status)
	}
	return nil
}

func (index *Index) Refresh() error {
	rsp, e := index.request("POST", index.IndexUrl()+"/_refresh", nil)
	if e != nil {
		return e
	}
	if rsp.Status[0] != '2' {
		return fmt.Errorf("Error refreshing index: %s", rsp.Status)
	}
	return nil
}

func (index *Index) IndexDocs(docs []*Doc) error {
	buf := &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	for _, doc := range docs {
		if doc.Index == "" {
			doc.Index = index.Index
		}
		if doc.Type == "" {
			doc.Type = index.Type
		}
		enc.Encode(map[string]map[string]string{
			"index": doc.IndexAttributes(),
		})
		enc.Encode(doc.Source)
	}
	rsp, e := http.Post(index.BaseUrl()+"/_bulk", "application/json", buf)
	if e != nil {
		return e
	}
	defer rsp.Body.Close()
	b, _ := ioutil.ReadAll(rsp.Body)
	if rsp.Status[0] != OK {
		return fmt.Errorf("Error sending bulk request: %s %s", rsp.Status, string(b))
	}
	return nil
}

func (index *Index) RunBatchIndex() error {
	if len(index.batchDocs) == 0 {
		return nil
	}
	started := time.Now()
	e := index.IndexDocs(index.batchDocs)
	if e != nil {
		return e
	}
	perSecond := float64(len(index.batchDocs)) / time.Now().Sub(started).Seconds()
	index.LogDebug("indexed %d, %.1f/second\n", len(index.batchDocs), perSecond)
	index.ResetBatch()
	return nil
}

type Status struct {
	Ok     bool    `json:"ok"`
	Shards *Shards `json:"_shards"`
}

type Shards struct {
	Total      int `json:"total"`
	Successful int `json:"successful"`
	Failed     int `json:"failed"`
}

func (index *Index) Status() (status *Status, e error) {
	rsp, e := http.Get(index.BaseUrl() + "/_status")
	if e != nil {
		return nil, e
	}
	defer rsp.Body.Close()
	b, e := ioutil.ReadAll(rsp.Body)
	if e != nil {
		return nil, e
	}
	if rsp.Status[0] != '2' {
		return nil, fmt.Errorf("Status: %d, Response: %s", rsp.StatusCode, string(b))
	}
	status = &Status{}
	e = json.Unmarshal(b, status)
	return status, e
}

func init() {
	log.SetFlags(0)
}

func (index *Index) LogDebug(format string, i ...interface{}) {
	if index.Logger != nil {
		index.Logger.Debug(format, i...)
	}
}

func (index *Index) LogInfo(format string, i ...interface{}) {
	if index.Logger != nil {
		index.Logger.Info(format, i...)
	}
}

func (index *Index) GlobalMapping() (m *Mapping, e error) {
	m = &Mapping{}
	u := index.BaseUrl() + "/_mapping"
	index.LogInfo("checking for url %s", u)
	rsp, e := index.request("GET", u, m)
	if rsp != nil && rsp.StatusCode == 404 {
		return nil, nil
	} else if e != nil {
		return nil, e
	}
	e = json.Unmarshal(rsp.Body, m)
	if e != nil {
		return nil, e
	}
	return m, nil
}

func (index *Index) Stats() (*Stats, error) {
	rsp, e := http.Get(index.IndexUrl() + "/_stats")
	if e != nil {
		return nil, e
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		return nil, fmt.Errorf("expected status 2xx, got %s", rsp.Status)
	}
	stats := &Stats{}
	e = json.NewDecoder(rsp.Body).Decode(stats)
	return stats, e
}

func (index *Index) Mapping() (i interface{}, e error) {
	u := index.IndexUrl() + "/_mapping"
	rsp, e := index.request("GET", u, i)
	if rsp != nil && rsp.StatusCode == 404 {
		return nil, nil
	} else if e != nil {
		return nil, e
	}
	e = json.Unmarshal(rsp.Body, &i)
	if e != nil {
		return nil, e
	}
	return i, nil
}

func (index *Index) PutMapping(mapping interface{}) (rsp *HttpResponse, e error) {
	return index.request("PUT", index.IndexUrl()+"/", mapping)
}

func (index *Index) BaseUrl() string {
	if index.Port == 0 {
		index.Port = 9200
	}
	return fmt.Sprintf("http://%s:%d", index.Host, index.Port)
}

func (index *Index) IndexUrl() string {
	if index.Index == "" {
		return index.BaseUrl()
	} else {
		return index.BaseUrl() + "/" + index.Index
	}
}

func (index *Index) TypeUrl() string {
	if index.Type == "" {
		return index.IndexUrl()
	} else if idx := index.IndexUrl(); idx != "" {
		return idx + "/" + index.Type
	} else {
		return ""
	}
}

func (index *Index) DeleteByQuery(query string) (b []byte, e error) {
	q := &url.Values{}
	q.Add("q", query)
	rsp, e := index.request("DELETE", index.TypeUrl()+"/_query?"+q.Encode(), nil)
	if e != nil {
		return b, e
	}
	if rsp.Status[0] != '2' {
		return b, fmt.Errorf("error deleting with query: %s", rsp.Status)
	}
	return rsp.Body, nil
}

func (index *Index) Search(req *Request) (rsp *Response, e error) {
	u := index.TypeUrl()
	if !strings.HasSuffix(u, "/") {
		u += "/"
	}
	u += "/_search"
	httpRequest, e := http.NewRequest("POST", u, nil)
	if e != nil {
		return nil, e
	}
	if req != nil {
		writer := &bytes.Buffer{}
		js := json.NewEncoder(writer)
		e = js.Encode(req)
		if e != nil {
			return nil, e
		}
		httpRequest.Body = ioutil.NopCloser(writer)
	}
	httpResponse, e := http.DefaultClient.Do(httpRequest)
	if e != nil {
		return nil, e
	}
	defer httpResponse.Body.Close()
	b, e := ioutil.ReadAll(httpResponse.Body)
	if e != nil {
		return nil, e
	}
	rsp = NewResponse(b)
	e = json.Unmarshal(b, rsp)
	if e != nil {
		return nil, e
	}
	return rsp, nil
}

func (index *Index) Post(u string, i interface{}) (*HttpResponse, error) {
	return index.request("POST", u, i)
}

func (index *Index) PostObject(i interface{}) (*HttpResponse, error) {
	return index.request("POST", index.TypeUrl(), i)
}

func (index *Index) PutObject(id string, i interface{}) (*HttpResponse, error) {
	return index.request("PUT", index.TypeUrl()+"/"+id, i)
}

func (index *Index) Put(u string, i interface{}) (*HttpResponse, error) {
	return index.request("PUT", u, i)
}

type HttpResponse struct {
	*http.Response
	Body []byte
}

func (index *Index) request(method string, u string, i interface{}) (httpResponse *HttpResponse, e error) {
	var req *http.Request
	if i != nil {
		buf := &bytes.Buffer{}
		encoder := json.NewEncoder(buf)
		if e := encoder.Encode(i); e != nil {
			return nil, e
		}
		req, e = http.NewRequest(method, u, buf)
	} else {
		req, e = http.NewRequest(method, u, nil)
	}
	if e != nil {
		return nil, e
	}
	rsp, e := http.DefaultClient.Do(req)
	if e != nil {
		return nil, e
	}
	defer rsp.Body.Close()
	b, e := ioutil.ReadAll(rsp.Body)
	if e != nil {
		return nil, e
	}
	httpResponse = &HttpResponse{
		Response: rsp,
		Body:     b,
	}
	if e != nil {
		return httpResponse, e
	}
	if rsp.Status[0] != OK {
		return httpResponse, fmt.Errorf("error indexing: %s %s", rsp.Status, string(b))
	}
	return httpResponse, nil
}
<|endoftext|>


<commit_before>package render

import (
	"path/filepath"
	"testing"

	"github.com/oakmound/oak/fileutil"
	"github.com/stretchr/testify/assert"
)

func TestBatchLoad(t *testing.T) {
	fileutil.BindataDir = AssetDir
	fileutil.BindataFn = Asset
	assert.Nil(t, BatchLoad(filepath.Join("assets", "images")))
	sh, err := GetSheet(filepath.Join("16", "jeremy.png"))
	assert.Nil(t, err)
	assert.Equal(t, len(sh.ToSprites()), 8)
	_, err = loadSprite("dir", "dummy.jpg")
	assert.NotNil(t, err)
	sp, err := GetSprite("dummy.gif")
	assert.Nil(t, sp)
	assert.NotNil(t, err)
	sp, err = GetSprite(filepath.Join("16", "jeremy.png"))
	assert.NotNil(t, sp)
	assert.Nil(t, err)
}
<commit_msg>Test for render loader checking custimizability.<commit_after>package render

import (
	"path/filepath"
	"testing"

	"github.com/oakmound/oak/fileutil"
	"github.com/stretchr/testify/assert"
)

func TestBatchLoad(t *testing.T) {
	fileutil.BindataDir = AssetDir
	fileutil.BindataFn = Asset
	assert.Nil(t, BatchLoad(filepath.Join("assets", "images")))
	sh, err := GetSheet(filepath.Join("16", "jeremy.png"))
	assert.Nil(t, err)
	assert.Equal(t, len(sh.ToSprites()), 8)
	_, err = loadSprite("dir", "dummy.jpg")
	assert.NotNil(t, err)
	sp, err := GetSprite("dummy.gif")
	assert.Nil(t, sp)
	assert.NotNil(t, err)
	sp, err = GetSprite(filepath.Join("16", "jeremy.png"))
	assert.NotNil(t, sp)
	assert.Nil(t, err)
}

func TestSetAssetPath(t *testing.T) {
	fileutil.BindataDir = AssetDir
	fileutil.BindataFn = Asset
	_, err := LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
	assert.Nil(t, err)
	UnloadAll()
	SetAssetPaths(wd)
	_, err = LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
	assert.NotNil(t, err)
	UnloadAll()
	SetAssetPaths(
		filepath.Join(
			wd,
			"assets",
			"images"),
	)
	_, err = LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
	assert.Nil(t, err)

}
<|endoftext|>


<commit_before>package integration_test

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"

	"github.com/cloudfoundry/bosh-bootloader/integration-test"
	"github.com/cloudfoundry/bosh-bootloader/integration-test/actors"
	"github.com/cloudfoundry/bosh-bootloader/testhelpers"
	"github.com/pivotal-cf-experimental/bosh-test/bosh"

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

const (
	ConcourseExampleManifestURL = "https://raw.githubusercontent.com/concourse/concourse/master/docs/setting-up/installing.any"
	ConcourseReleaseURL         = "https://bosh.io/d/github.com/concourse/concourse"
	GardenReleaseURL            = "https://bosh.io/d/github.com/cloudfoundry-incubator/garden-runc-release"
	GardenReleaseName           = "garden-runc"
	StemcellURL                 = "https://bosh.io/d/stemcells/bosh-aws-xen-hvm-ubuntu-trusty-go_agent"
	StemcellName                = "bosh-aws-xen-hvm-ubuntu-trusty-go_agent"
)

var _ = Describe("bosh deployment tests", func() {
	var (
		bbl   actors.BBL
		aws   actors.AWS
		state integration.State
	)

	BeforeEach(func() {
		var err error
		configuration, err := integration.LoadConfig()
		Expect(err).NotTo(HaveOccurred())

		bbl = actors.NewBBL(configuration.StateFileDir, pathToBBL, configuration)
		aws = actors.NewAWS(configuration)
		state = integration.NewState(configuration.StateFileDir)
	})

	It("is able to deploy concourse", func() {
		bbl.Up()

		certPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT)
		Expect(err).NotTo(HaveOccurred())

		keyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY)
		Expect(err).NotTo(HaveOccurred())

		bbl.CreateLB("concourse", certPath, keyPath, "")

		boshClient := bosh.NewClient(bosh.Config{
			URL:              bbl.DirectorAddress(),
			Username:         bbl.DirectorUsername(),
			Password:         bbl.DirectorPassword(),
			AllowInsecureSSL: true,
		})

		err = downloadAndUploadRelease(boshClient, ConcourseReleaseURL)
		Expect(err).NotTo(HaveOccurred())

		err = downloadAndUploadRelease(boshClient, GardenReleaseURL)
		Expect(err).NotTo(HaveOccurred())

		err = downloadAndUploadStemcell(boshClient, StemcellURL)
		Expect(err).NotTo(HaveOccurred())

		concourseExampleManifest, err := downloadConcourseExampleManifest()
		Expect(err).NotTo(HaveOccurred())

		info, err := boshClient.Info()
		Expect(err).NotTo(HaveOccurred())

		lbURL := fmt.Sprintf("http://%s", aws.LoadBalancers(state.StackName())["ConcourseLoadBalancerURL"])

		stemcell, err := boshClient.Stemcell(StemcellName)
		Expect(err).NotTo(HaveOccurred())

		concourseRelease, err := boshClient.Release("concourse")
		Expect(err).NotTo(HaveOccurred())

		gardenRelease, err := boshClient.Release(GardenReleaseName)
		Expect(err).NotTo(HaveOccurred())

		concourseManifestInputs := concourseManifestInputs{
			boshDirectorUUID:        info.UUID,
			webExternalURL:          lbURL,
			stemcellVersion:         stemcell.Latest(),
			concourseReleaseVersion: concourseRelease.Latest(),
			gardenReleaseVersion:    gardenRelease.Latest(),
		}
		concourseManifest, err := populateManifest(concourseExampleManifest, concourseManifestInputs)
		Expect(err).NotTo(HaveOccurred())

		_, err = boshClient.Deploy([]byte(concourseManifest))
		Expect(err).NotTo(HaveOccurred())

		Eventually(func() ([]bosh.VM, error) {
			return boshClient.DeploymentVMs("concourse")
		}, "1m", "10s").Should(ConsistOf([]bosh.VM{
			{JobName: "worker", Index: 0, State: "running"},
			{JobName: "db", Index: 0, State: "running"},
			{JobName: "web", Index: 0, State: "running"},
		}))

		resp, err := http.Get(lbURL)
		Expect(err).NotTo(HaveOccurred())

		Expect(resp.StatusCode).To(Equal(http.StatusOK))

		body, err := ioutil.ReadAll(resp.Body)
		Expect(err).NotTo(HaveOccurred())

		Expect(string(body)).To(ContainSubstring("no pipelines configured"))

		err = boshClient.DeleteDeployment("concourse")
		Expect(err).NotTo(HaveOccurred())

		bbl.Destroy()
	})
})

func downloadAndUploadStemcell(boshClient bosh.Client, stemcell string) error {
	file, size, err := download(stemcell)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadStemcell(bosh.NewSizeReader(file, size))
	return err
}

func downloadAndUploadRelease(boshClient bosh.Client, release string) error {
	file, size, err := download(release)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadRelease(bosh.NewSizeReader(file, size))
	return err
}

func downloadConcourseExampleManifest() (string, error) {
	resp, _, err := download(ConcourseExampleManifestURL)
	if err != nil {
		return "", err
	}

	var lines []string
	scanner := bufio.NewScanner(resp)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	startIndexOfYamlCode := -1
	endIndexOfYamlCode := -1

	for index, line := range lines {
		startMatched, startErr := regexp.MatchString(`^\s*\\codeblock{yaml}{$`, line)
		endMatched, endErr := regexp.MatchString(`^\s*}$`, line)
		if endErr != nil {
			return "", endErr
		}

		if startErr != nil {
			panic(startErr)
		}

		if startMatched && startIndexOfYamlCode < 0 {
			startIndexOfYamlCode = index + 1
		}
		if endMatched && endIndexOfYamlCode < 0 && startIndexOfYamlCode > 0 {
			endIndexOfYamlCode = index
		}
	}

	yamlDocument := lines[startIndexOfYamlCode:endIndexOfYamlCode]

	re := regexp.MustCompile(`^(\s*)---`)
	results := re.FindAllStringSubmatch(yamlDocument[0], -1)
	indentation := results[0][1]
	for index, line := range yamlDocument {
		indentationRegexp := regexp.MustCompile(fmt.Sprintf(`^%s`, indentation))
		escapesRegexp := regexp.MustCompile(`\\([{}])`)
		tlsRegexp := regexp.MustCompile("^.*(tls_key|tls_cert).*$")

		line = indentationRegexp.ReplaceAllString(line, "")
		line = escapesRegexp.ReplaceAllString(line, "$1")
		line = tlsRegexp.ReplaceAllString(line, "")

		yamlDocument[index] = line

	}

	yamlString := strings.Join(yamlDocument, "\n")
	return yamlString, nil
}

func download(location string) (io.Reader, int64, error) {
	resp, err := http.Get(location)
	if err != nil {
		return nil, 0, err
	}

	return resp.Body, resp.ContentLength, nil
}
<commit_msg>Update concourse integration test assertions<commit_after>package integration_test

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"

	"github.com/cloudfoundry/bosh-bootloader/integration-test"
	"github.com/cloudfoundry/bosh-bootloader/integration-test/actors"
	"github.com/cloudfoundry/bosh-bootloader/testhelpers"
	"github.com/pivotal-cf-experimental/bosh-test/bosh"

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

const (
	ConcourseExampleManifestURL = "https://raw.githubusercontent.com/concourse/concourse/master/docs/setting-up/installing.any"
	ConcourseReleaseURL         = "https://bosh.io/d/github.com/concourse/concourse"
	GardenReleaseURL            = "https://bosh.io/d/github.com/cloudfoundry-incubator/garden-runc-release"
	GardenReleaseName           = "garden-runc"
	StemcellURL                 = "https://bosh.io/d/stemcells/bosh-aws-xen-hvm-ubuntu-trusty-go_agent"
	StemcellName                = "bosh-aws-xen-hvm-ubuntu-trusty-go_agent"
)

var _ = Describe("bosh deployment tests", func() {
	var (
		bbl   actors.BBL
		aws   actors.AWS
		state integration.State
	)

	BeforeEach(func() {
		var err error
		configuration, err := integration.LoadConfig()
		Expect(err).NotTo(HaveOccurred())

		bbl = actors.NewBBL(configuration.StateFileDir, pathToBBL, configuration)
		aws = actors.NewAWS(configuration)
		state = integration.NewState(configuration.StateFileDir)
	})

	It("is able to deploy concourse", func() {
		bbl.Up()

		certPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT)
		Expect(err).NotTo(HaveOccurred())

		keyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY)
		Expect(err).NotTo(HaveOccurred())

		bbl.CreateLB("concourse", certPath, keyPath, "")

		boshClient := bosh.NewClient(bosh.Config{
			URL:              bbl.DirectorAddress(),
			Username:         bbl.DirectorUsername(),
			Password:         bbl.DirectorPassword(),
			AllowInsecureSSL: true,
		})

		err = downloadAndUploadRelease(boshClient, ConcourseReleaseURL)
		Expect(err).NotTo(HaveOccurred())

		err = downloadAndUploadRelease(boshClient, GardenReleaseURL)
		Expect(err).NotTo(HaveOccurred())

		err = downloadAndUploadStemcell(boshClient, StemcellURL)
		Expect(err).NotTo(HaveOccurred())

		concourseExampleManifest, err := downloadConcourseExampleManifest()
		Expect(err).NotTo(HaveOccurred())

		info, err := boshClient.Info()
		Expect(err).NotTo(HaveOccurred())

		lbURL := fmt.Sprintf("http://%s", aws.LoadBalancers(state.StackName())["ConcourseLoadBalancerURL"])

		stemcell, err := boshClient.Stemcell(StemcellName)
		Expect(err).NotTo(HaveOccurred())

		concourseRelease, err := boshClient.Release("concourse")
		Expect(err).NotTo(HaveOccurred())

		gardenRelease, err := boshClient.Release(GardenReleaseName)
		Expect(err).NotTo(HaveOccurred())

		concourseManifestInputs := concourseManifestInputs{
			boshDirectorUUID:        info.UUID,
			webExternalURL:          lbURL,
			stemcellVersion:         stemcell.Latest(),
			concourseReleaseVersion: concourseRelease.Latest(),
			gardenReleaseVersion:    gardenRelease.Latest(),
		}
		concourseManifest, err := populateManifest(concourseExampleManifest, concourseManifestInputs)
		Expect(err).NotTo(HaveOccurred())

		_, err = boshClient.Deploy([]byte(concourseManifest))
		Expect(err).NotTo(HaveOccurred())

		Eventually(func() ([]bosh.VM, error) {
			return boshClient.DeploymentVMs("concourse")
		}, "1m", "10s").Should(ConsistOf([]bosh.VM{
			{JobName: "worker", Index: 0, State: "running"},
			{JobName: "db", Index: 0, State: "running"},
			{JobName: "web", Index: 0, State: "running"},
		}))

		resp, err := http.Get(lbURL)
		Expect(err).NotTo(HaveOccurred())

		Expect(resp.StatusCode).To(Equal(http.StatusOK))

		body, err := ioutil.ReadAll(resp.Body)
		Expect(err).NotTo(HaveOccurred())

		Expect(string(body)).To(ContainSubstring("<title>Concourse</title>"))

		err = boshClient.DeleteDeployment("concourse")
		Expect(err).NotTo(HaveOccurred())

		bbl.Destroy()
	})
})

func downloadAndUploadStemcell(boshClient bosh.Client, stemcell string) error {
	file, size, err := download(stemcell)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadStemcell(bosh.NewSizeReader(file, size))
	return err
}

func downloadAndUploadRelease(boshClient bosh.Client, release string) error {
	file, size, err := download(release)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadRelease(bosh.NewSizeReader(file, size))
	return err
}

func downloadConcourseExampleManifest() (string, error) {
	resp, _, err := download(ConcourseExampleManifestURL)
	if err != nil {
		return "", err
	}

	var lines []string
	scanner := bufio.NewScanner(resp)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	startIndexOfYamlCode := -1
	endIndexOfYamlCode := -1

	for index, line := range lines {
		startMatched, startErr := regexp.MatchString(`^\s*\\codeblock{yaml}{$`, line)
		endMatched, endErr := regexp.MatchString(`^\s*}$`, line)
		if endErr != nil {
			return "", endErr
		}

		if startErr != nil {
			panic(startErr)
		}

		if startMatched && startIndexOfYamlCode < 0 {
			startIndexOfYamlCode = index + 1
		}
		if endMatched && endIndexOfYamlCode < 0 && startIndexOfYamlCode > 0 {
			endIndexOfYamlCode = index
		}
	}

	yamlDocument := lines[startIndexOfYamlCode:endIndexOfYamlCode]

	re := regexp.MustCompile(`^(\s*)---`)
	results := re.FindAllStringSubmatch(yamlDocument[0], -1)
	indentation := results[0][1]
	for index, line := range yamlDocument {
		indentationRegexp := regexp.MustCompile(fmt.Sprintf(`^%s`, indentation))
		escapesRegexp := regexp.MustCompile(`\\([{}])`)
		tlsRegexp := regexp.MustCompile("^.*(tls_key|tls_cert).*$")

		line = indentationRegexp.ReplaceAllString(line, "")
		line = escapesRegexp.ReplaceAllString(line, "$1")
		line = tlsRegexp.ReplaceAllString(line, "")

		yamlDocument[index] = line

	}

	yamlString := strings.Join(yamlDocument, "\n")
	return yamlString, nil
}

func download(location string) (io.Reader, int64, error) {
	resp, err := http.Get(location)
	if err != nil {
		return nil, 0, err
	}

	return resp.Body, resp.ContentLength, nil
}
<|endoftext|>


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

package main

import (
	"fmt"
	"os"
	"strconv"
	"testing"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/ThomasRooney/gexpect"
	"github.com/coreos/rkt/common/cgroup"
)

const (
	// if you change this you need to change tests/image/manifest accordingly
	maxMemoryUsage = 25 * 1024 * 1024 // 25MB
	CPUQuota       = 800              // milli-cores
)

var memoryTest = struct {
	testName     string
	aciBuildArgs []string
	rktArgs      string
}{
	`Check memory isolator`,
	[]string{"--exec=/inspect --print-memorylimit"},
	`--insecure-skip-verify run --mds-register=false rkt-inspect-isolators.aci`,
}

var cpuTest = struct {
	testName     string
	aciBuildArgs []string
	rktArgs      string
}{
	`Check CPU quota`,
	[]string{"--exec=/inspect --print-cpuquota"},
	`--insecure-skip-verify run --mds-register=false rkt-inspect-isolators.aci`,
}

func TestAppIsolatorMemory(t *testing.T) {
	ok := cgroup.IsIsolatorSupported("memory")
	if !ok {
		t.Skip("Memory isolator not supported.")
	}

	ctx := newRktRunCtx()
	defer ctx.cleanup()

	t.Logf("Running test: %v", memoryTest.testName)

	aciFileName := patchTestACI("rkt-inspect-isolators.aci", memoryTest.aciBuildArgs...)
	defer os.Remove(aciFileName)

	rktCmd := fmt.Sprintf("%s %s", ctx.cmd(), memoryTest.rktArgs)
	t.Logf("Command: %v", rktCmd)
	child, err := gexpect.Spawn(rktCmd)
	if err != nil {
		t.Fatalf("Cannot exec rkt: %v", err)
	}
	expectedLine := "Memory Limit: " + strconv.Itoa(maxMemoryUsage)
	if err := expectWithOutput(child, expectedLine); err != nil {
		t.Fatalf("Didn't receive expected output %q: %v", expectedLine, err)
	}

	err = child.Wait()
	if err != nil {
		t.Fatalf("rkt didn't terminate correctly: %v", err)
	}
}

func TestAppIsolatorCPU(t *testing.T) {
	ok := cgroup.IsIsolatorSupported("cpu")
	if !ok {
		t.Skip("CPU isolator not supported.")
	}

	ctx := newRktRunCtx()
	defer ctx.cleanup()

	t.Logf("Running test: %v", cpuTest.testName)

	aciFileName := patchTestACI("rkt-inspect-isolators.aci", cpuTest.aciBuildArgs...)
	defer os.Remove(aciFileName)

	rktCmd := fmt.Sprintf("%s %s", ctx.cmd(), cpuTest.rktArgs)
	t.Logf("Command: %v", rktCmd)
	child, err := gexpect.Spawn(rktCmd)
	if err != nil {
		t.Fatalf("Cannot exec rkt: %v", err)
	}
	expectedLine := "CPU Quota: " + strconv.Itoa(CPUQuota)
	if err := expectWithOutput(child, expectedLine); err != nil {
		t.Fatalf("Didn't receive expected output %q: %v", expectedLine, err)
	}

	err = child.Wait()
	if err != nil {
		t.Fatalf("rkt didn't terminate correctly: %v", err)
	}

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

package main

import (
	"fmt"
	"os"
	"strconv"
	"testing"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/ThomasRooney/gexpect"
	"github.com/coreos/rkt/common/cgroup"
)

const (
	// if you change this you need to change tests/image/manifest accordingly
	maxMemoryUsage = 25 * 1024 * 1024 // 25MB
	CPUQuota       = 800              // milli-cores
)

var memoryTest = struct {
	testName     string
	aciBuildArgs []string
}{
	`Check memory isolator`,
	[]string{"--exec=/inspect --print-memorylimit"},
}

var cpuTest = struct {
	testName     string
	aciBuildArgs []string
}{
	`Check CPU quota`,
	[]string{"--exec=/inspect --print-cpuquota"},
}

func TestAppIsolatorMemory(t *testing.T) {
	ok := cgroup.IsIsolatorSupported("memory")
	if !ok {
		t.Skip("Memory isolator not supported.")
	}

	ctx := newRktRunCtx()
	defer ctx.cleanup()

	t.Logf("Running test: %v", memoryTest.testName)

	aciFileName := patchTestACI("rkt-inspect-isolators.aci", memoryTest.aciBuildArgs...)
	defer os.Remove(aciFileName)

	rktCmd := fmt.Sprintf("%s --insecure-skip-verify run --mds-register=false %s", ctx.cmd(), aciFileName)
	t.Logf("Command: %v", rktCmd)
	child, err := gexpect.Spawn(rktCmd)
	if err != nil {
		t.Fatalf("Cannot exec rkt: %v", err)
	}
	expectedLine := "Memory Limit: " + strconv.Itoa(maxMemoryUsage)
	if err := expectWithOutput(child, expectedLine); err != nil {
		t.Fatalf("Didn't receive expected output %q: %v", expectedLine, err)
	}

	err = child.Wait()
	if err != nil {
		t.Fatalf("rkt didn't terminate correctly: %v", err)
	}
}

func TestAppIsolatorCPU(t *testing.T) {
	ok := cgroup.IsIsolatorSupported("cpu")
	if !ok {
		t.Skip("CPU isolator not supported.")
	}

	ctx := newRktRunCtx()
	defer ctx.cleanup()

	t.Logf("Running test: %v", cpuTest.testName)

	aciFileName := patchTestACI("rkt-inspect-isolators.aci", cpuTest.aciBuildArgs...)
	defer os.Remove(aciFileName)

	rktCmd := fmt.Sprintf("%s --insecure-skip-verify run --mds-register=false %s", ctx.cmd(), aciFileName)
	t.Logf("Command: %v", rktCmd)
	child, err := gexpect.Spawn(rktCmd)
	if err != nil {
		t.Fatalf("Cannot exec rkt: %v", err)
	}
	expectedLine := "CPU Quota: " + strconv.Itoa(CPUQuota)
	if err := expectWithOutput(child, expectedLine); err != nil {
		t.Fatalf("Didn't receive expected output %q: %v", expectedLine, err)
	}

	err = child.Wait()
	if err != nil {
		t.Fatalf("rkt didn't terminate correctly: %v", err)
	}

}
<|endoftext|>


<commit_before>package global

import (
	"fmt"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("env command", func() {
	var (
		orgName     string
		spaceName   string
		appName     string
		envVarName  string
		envVarValue string
	)

	BeforeEach(func() {
		orgName = helpers.NewOrgName()
		spaceName = helpers.NewSpaceName()
		appName = helpers.PrefixedRandomName("app")
		envVarName = "SOME_ENV_VAR"
		envVarValue = "SOME_ENV_VAR_VALUE"
	})

	Describe("help", func() {
		When("--help flag is set", func() {
			It("displays command usage to output", func() {
				session := helpers.CF("env", "--help")

				Eventually(session).Should(Say("NAME:"))
				Eventually(session).Should(Say("env - Show all env variables for an app"))
				Eventually(session).Should(Say("USAGE:"))
				Eventually(session).Should(Say("cf env APP_NAME"))
				Eventually(session).Should(Say("SEE ALSO:"))
				Eventually(session).Should(Say("app, running-environment-variable-group, set-env, staging-environment-variable-group, unset-env, v3-apps"))
				Eventually(session).Should(Exit(0))
			})
		})
	})

	When("the app name is not provided", func() {
		It("tells the user that the app name is required, prints help text, and exits 1", func() {
			session := helpers.CF("env")

			Eventually(session.Err).Should(Say("Incorrect Usage: the required argument `APP_NAME` was not provided"))
			Eventually(session).Should(Say("NAME:"))
			Eventually(session).Should(Exit(1))
		})
	})

	When("the environment is not setup correctly", func() {
		It("fails with the appropriate errors", func() {
			helpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, "env", appName)
		})
	})

	When("the environment is set up correctly", func() {
		var userName string

		BeforeEach(func() {
			helpers.SetupCF(orgName, spaceName)
			userName, _ = helpers.GetCredentials()
		})

		AfterEach(func() {
			helpers.QuickDeleteOrg(orgName)
		})

		When("the app does not exist", func() {
			It("displays app not found and exits 1", func() {
				invalidAppName := "invalid-app-name"
				session := helpers.CF("env", invalidAppName)

				Eventually(session).Should(Say(`Getting env variables for app %s in org %s / space %s as %s\.\.\.`, invalidAppName, orgName, spaceName, userName))
				Eventually(session).Should(Say("OK"))

				Eventually(session.Err).Should(Say("App %s not found", invalidAppName))
				Eventually(session).Should(Say("FAILED"))
				Eventually(session).Should(Exit(1))
			})
		})

		When("the app exists", func() {
			var (
				userProvidedServiceName string
			)
			BeforeEach(func() {
				userProvidedServiceName = helpers.PrefixedRandomName("service")
				helpers.WithHelloWorldApp(func(appDir string) {
					Eventually(helpers.CF("push", appName, "-p", appDir)).Should(Exit(0))
				})

				Eventually(helpers.CF("set-env", appName, "user-provided-env-name", "user-provided-env-value")).Should(Exit(0))
				Eventually(helpers.CF("set-env", appName, "an-out-of-order-name", "some-env-value")).Should(Exit(0))
				Eventually(helpers.CF("set-env", appName, "Capital-env-var", "some-other-env-value")).Should(Exit(0))
				Eventually(helpers.CF("create-user-provided-service", userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("bind-service", appName, userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("set-running-environment-variable-group", `{"running-env-name": "running-env-value", "number": 1, "Xstring": "X"}`)).Should(Exit(0))
				Eventually(helpers.CF("set-staging-environment-variable-group", `{"staging-env-name": "staging-env-value", "number": 2, "Ystring": "Y"}`)).Should(Exit(0))
			})

			AfterEach(func() {
				Eventually(helpers.CF("unbind-service", appName, userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("delete-service", userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("set-running-environment-variable-group", `{}`)).Should(Exit(0))
				Eventually(helpers.CF("set-staging-environment-variable-group", `{}`)).Should(Exit(0))
			})

			It("displays the environment variables", func() {
				By("displaying env variables when they are set")
				session := helpers.CF("env", appName)

				Eventually(session).Should(Say(fmt.Sprintf(`Getting env variables for app %s in org %s / space %s as %s\.\.\.`, appName, orgName, spaceName, userName)))
				Eventually(session).Should(Say("OK"))

				Eventually(session).Should(Say("System-Provided:"))
				Eventually(session).Should(Say(`VCAP_SERVICES: {\s*\n`))
				Eventually(session).Should(Say("VCAP_APPLICATION"))

				Eventually(session).Should(Say("User-Provided:"))
				Eventually(session).Should(Say(`Capital-env-var:\s+some-other-env-value`))
				Eventually(session).Should(Say(`an-out-of-order-name:\s+some-env-value`))
				Eventually(session).Should(Say(`user-provided-env-name:\s+user-provided-env-value`))

				Eventually(session).Should(Say("Running Environment Variable Groups:"))
				Eventually(session).Should(Say(`Xstring:\s+X`))
				Eventually(session).Should(Say(`number:\s+1`))
				Eventually(session).Should(Say(`running-env-name:\s+running-env-value`))

				Eventually(session).Should(Say("Staging Environment Variable Groups:"))
				Eventually(session).Should(Say(`Ystring:\s+Y`))
				Eventually(session).Should(Say(`number:\s+2`))
				Eventually(session).Should(Say(`staging-env-name:\s+staging-env-value`))

				Eventually(session).Should(Exit(0))

				By("displaying help messages when they are not set")
				Eventually(helpers.CF("unset-env", appName, "user-provided-env-name")).Should(Exit(0))
				Eventually(helpers.CF("unset-env", appName, "an-out-of-order-name")).Should(Exit(0))
				Eventually(helpers.CF("unset-env", appName, "Capital-env-var")).Should(Exit(0))
				Eventually(helpers.CF("unbind-service", appName, userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("set-running-environment-variable-group", `{}`)).Should(Exit(0))
				Eventually(helpers.CF("set-staging-environment-variable-group", `{}`)).Should(Exit(0))

				session = helpers.CF("env", appName)
				Eventually(session).Should(Say(`Getting env variables for app %s in org %s / space %s as %s\.\.\.`, appName, orgName, spaceName, userName))
				Eventually(session).Should(Say("OK"))

				Eventually(session).Should(Say("System-Provided:"))
				Eventually(session).Should(Say("VCAP_SERVICES: {}"))
				Eventually(session).Should(Say("VCAP_APPLICATION"))

				Eventually(session).Should(Say("No user-provided env variables have been set"))

				Eventually(session).Should(Say("No running env variables have been set"))

				Eventually(session).Should(Say("No staging env variables have been set"))
				Eventually(session).Should(Exit(0))
			})
		})
	})
})
<commit_msg>remove the unused variables from the test<commit_after>package global

import (
	"fmt"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("env command", func() {
	var (
		orgName   string
		spaceName string
		appName   string
	)

	BeforeEach(func() {
		orgName = helpers.NewOrgName()
		spaceName = helpers.NewSpaceName()
		appName = helpers.PrefixedRandomName("app")
	})

	Describe("help", func() {
		When("--help flag is set", func() {
			It("displays command usage to output", func() {
				session := helpers.CF("env", "--help")

				Eventually(session).Should(Say("NAME:"))
				Eventually(session).Should(Say("env - Show all env variables for an app"))
				Eventually(session).Should(Say("USAGE:"))
				Eventually(session).Should(Say("cf env APP_NAME"))
				Eventually(session).Should(Say("SEE ALSO:"))
				Eventually(session).Should(Say("app, running-environment-variable-group, set-env, staging-environment-variable-group, unset-env, v3-apps"))
				Eventually(session).Should(Exit(0))
			})
		})
	})

	When("the app name is not provided", func() {
		It("tells the user that the app name is required, prints help text, and exits 1", func() {
			session := helpers.CF("env")

			Eventually(session.Err).Should(Say("Incorrect Usage: the required argument `APP_NAME` was not provided"))
			Eventually(session).Should(Say("NAME:"))
			Eventually(session).Should(Exit(1))
		})
	})

	When("the environment is not setup correctly", func() {
		It("fails with the appropriate errors", func() {
			helpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, "env", appName)
		})
	})

	When("the environment is set up correctly", func() {
		var userName string

		BeforeEach(func() {
			helpers.SetupCF(orgName, spaceName)
			userName, _ = helpers.GetCredentials()
		})

		AfterEach(func() {
			helpers.QuickDeleteOrg(orgName)
		})

		When("the app does not exist", func() {
			It("displays app not found and exits 1", func() {
				invalidAppName := "invalid-app-name"
				session := helpers.CF("env", invalidAppName)

				Eventually(session).Should(Say(`Getting env variables for app %s in org %s / space %s as %s\.\.\.`, invalidAppName, orgName, spaceName, userName))
				Eventually(session).Should(Say("OK"))

				Eventually(session.Err).Should(Say("App %s not found", invalidAppName))
				Eventually(session).Should(Say("FAILED"))
				Eventually(session).Should(Exit(1))
			})
		})

		When("the app exists", func() {
			var (
				userProvidedServiceName string
			)
			BeforeEach(func() {
				userProvidedServiceName = helpers.PrefixedRandomName("service")
				helpers.WithHelloWorldApp(func(appDir string) {
					Eventually(helpers.CF("push", appName, "-p", appDir)).Should(Exit(0))
				})

				Eventually(helpers.CF("set-env", appName, "user-provided-env-name", "user-provided-env-value")).Should(Exit(0))
				Eventually(helpers.CF("set-env", appName, "an-out-of-order-name", "some-env-value")).Should(Exit(0))
				Eventually(helpers.CF("set-env", appName, "Capital-env-var", "some-other-env-value")).Should(Exit(0))
				Eventually(helpers.CF("create-user-provided-service", userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("bind-service", appName, userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("set-running-environment-variable-group", `{"running-env-name": "running-env-value", "number": 1, "Xstring": "X"}`)).Should(Exit(0))
				Eventually(helpers.CF("set-staging-environment-variable-group", `{"staging-env-name": "staging-env-value", "number": 2, "Ystring": "Y"}`)).Should(Exit(0))
			})

			AfterEach(func() {
				Eventually(helpers.CF("unbind-service", appName, userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("delete-service", userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("set-running-environment-variable-group", `{}`)).Should(Exit(0))
				Eventually(helpers.CF("set-staging-environment-variable-group", `{}`)).Should(Exit(0))
			})

			It("displays the environment variables", func() {
				By("displaying env variables when they are set")
				session := helpers.CF("env", appName)

				Eventually(session).Should(Say(fmt.Sprintf(`Getting env variables for app %s in org %s / space %s as %s\.\.\.`, appName, orgName, spaceName, userName)))
				Eventually(session).Should(Say("OK"))

				Eventually(session).Should(Say("System-Provided:"))
				Eventually(session).Should(Say(`VCAP_SERVICES: {\s*\n`))
				Eventually(session).Should(Say("VCAP_APPLICATION"))

				Eventually(session).Should(Say("User-Provided:"))
				Eventually(session).Should(Say(`Capital-env-var:\s+some-other-env-value`))
				Eventually(session).Should(Say(`an-out-of-order-name:\s+some-env-value`))
				Eventually(session).Should(Say(`user-provided-env-name:\s+user-provided-env-value`))

				Eventually(session).Should(Say("Running Environment Variable Groups:"))
				Eventually(session).Should(Say(`Xstring:\s+X`))
				Eventually(session).Should(Say(`number:\s+1`))
				Eventually(session).Should(Say(`running-env-name:\s+running-env-value`))

				Eventually(session).Should(Say("Staging Environment Variable Groups:"))
				Eventually(session).Should(Say(`Ystring:\s+Y`))
				Eventually(session).Should(Say(`number:\s+2`))
				Eventually(session).Should(Say(`staging-env-name:\s+staging-env-value`))

				Eventually(session).Should(Exit(0))

				By("displaying help messages when they are not set")
				Eventually(helpers.CF("unset-env", appName, "user-provided-env-name")).Should(Exit(0))
				Eventually(helpers.CF("unset-env", appName, "an-out-of-order-name")).Should(Exit(0))
				Eventually(helpers.CF("unset-env", appName, "Capital-env-var")).Should(Exit(0))
				Eventually(helpers.CF("unbind-service", appName, userProvidedServiceName)).Should(Exit(0))
				Eventually(helpers.CF("set-running-environment-variable-group", `{}`)).Should(Exit(0))
				Eventually(helpers.CF("set-staging-environment-variable-group", `{}`)).Should(Exit(0))

				session = helpers.CF("env", appName)
				Eventually(session).Should(Say(`Getting env variables for app %s in org %s / space %s as %s\.\.\.`, appName, orgName, spaceName, userName))
				Eventually(session).Should(Say("OK"))

				Eventually(session).Should(Say("System-Provided:"))
				Eventually(session).Should(Say("VCAP_SERVICES: {}"))
				Eventually(session).Should(Say("VCAP_APPLICATION"))

				Eventually(session).Should(Say("No user-provided env variables have been set"))

				Eventually(session).Should(Say("No running env variables have been set"))

				Eventually(session).Should(Say("No staging env variables have been set"))
				Eventually(session).Should(Exit(0))
			})
		})
	})
})
<|endoftext|>


<commit_before>package cli

var all_templates = map[string]string{
	"debug":          default_debug_template,
	"fields":         default_debug_template,
	"editmeta":       default_debug_template,
	"transmeta":      default_debug_template,
	"createmeta":     default_debug_template,
	"issuelinktypes": default_debug_template,
	"list":           default_list_template,
	"view":           default_view_template,
	"edit":           default_edit_template,
	"transitions":    default_transitions_template,
	"issuetypes":     default_issuetypes_template,
	"create":         default_create_template,
	"comment":        default_comment_template,
}

const default_debug_template = "{{ . | toJson}}\n"

const default_list_template = "{{ range .issues }}{{ .key | append \":\" | printf \"%-12s\"}} {{ .fields.summary }}\n{{ end }}"

const default_view_template = `issue: {{ .key }}
status: {{ .fields.status.name }}
summary: {{ .fields.summary }}
project: {{ .fields.project.key }}
components: {{ range .fields.components }}{{ .name }} {{end}}
issuetype: {{ .fields.issuetype.name }}
assignee: {{ if .fields.assignee }}{{ .fields.assignee }}{{end}}
reporter: {{ .fields.reporter.name }}
watchers: {{ range .fields.customfield_10110 }}{{ .name }} {{end}}
blockers: {{ range .fields.issuelinks }}{{if .outwardIssue}}{{ .outwardIssue.key }}[{{.outwardIssue.fields.status.name}}]{{end}}{{end}}
depends: {{ range .fields.issuelinks }}{{if .inwardIssue}}{{ .inwardIssue.key }}[{{.inwardIssue.fields.status.name}}]{{end}}{{end}}
priority: {{ .fields.priority.name }}
description: |
  {{ .fields.description | indent 2 }}

comments:
{{ range .fields.comment.comments }}  - | # {{.author.name}} at {{.created}}
    {{ .body | indent 4}}
{{end}}
`
const default_edit_template = `update:
  comment:
    - add:
        body: |
          {{ or .overrides.comment "" | indent 10 }}
fields:
  summary: {{ or .overrides.summary .fields.summary }}
  components: # {{ range .meta.fields.components.allowedValues }}{{.name}}, {{end}}{{if .overrides.components }}{{ range (split "," .overrides.components)}}
    - name: {{.}}{{end}}{{else}}{{ range .fields.components }}
    - name: {{ .name }}{{end}}{{end}}
  assignee:
    name: {{ if .overrides.assignee }}{{.overrides.assignee}}{{else}}{{if .fields.assignee }}{{ .fields.assignee.name }}{{end}}{{end}}
  reporter:
    name: {{ or .overrides.reporter .fields.reporter.name }}
  # watchers
  customfield_10110: {{ range .fields.customfield_10110 }}
    - name: {{ .name }}{{end}}{{if .overrides.watcher}}
    - name: {{ .overrides.watcher}}{{end}}
  priority: # {{ range .meta.fields.priority.allowedValues }}{{.name}}, {{end}}
    name: {{ or .overrides.priority .fields.priority.name }}
  description: |
    {{ or .overrides.description (or .fields.description "") | indent 4 }}
`
const default_transitions_template = `{{ range .transitions }}{{.id }}: {{.name}}
{{end}}`

const default_issuetypes_template = `{{ range .projects }}{{ range .issuetypes }}{{color "+bh"}}{{.name | append ":" | printf "%-13s" }}{{color "reset"}} {{.description}}
{{end}}{{end}}`

const default_create_template = `fields:
  project:
    key: {{ .overrides.project }}
  issuetype:
    name: {{ .overrides.issuetype }}
  summary: {{ or .overrides.summary "" }}
  priority: # {{ range .meta.fields.priority.allowedValues }}{{.name}}, {{end}}
    name: {{ or .overrides.priority "" }}
  components: # {{ range .meta.fields.components.allowedValues }}{{.name}}, {{end}}{{ range split "," (or .overrides.components "")}}
    - name: {{ . }}{{end}}
  description: |
    {{ or .overrides.description "" | indent 4 }}
  assignee:
    name: {{ or .overrides.assignee .overrides.user}}
  reporter:
    name: {{ or .overrides.reporter .overrides.user }}
  # watchers
  customfield_10110:
    - name:
`

const default_comment_template = `body: |
  {{ or .overrides.comment | indent 2 }}
`
<commit_msg>fix inner assignee template<commit_after>package cli

var all_templates = map[string]string{
	"debug":          default_debug_template,
	"fields":         default_debug_template,
	"editmeta":       default_debug_template,
	"transmeta":      default_debug_template,
	"createmeta":     default_debug_template,
	"issuelinktypes": default_debug_template,
	"list":           default_list_template,
	"view":           default_view_template,
	"edit":           default_edit_template,
	"transitions":    default_transitions_template,
	"issuetypes":     default_issuetypes_template,
	"create":         default_create_template,
	"comment":        default_comment_template,
}

const default_debug_template = "{{ . | toJson}}\n"

const default_list_template = "{{ range .issues }}{{ .key | append \":\" | printf \"%-12s\"}} {{ .fields.summary }}\n{{ end }}"

const default_view_template = `issue: {{ .key }}
status: {{ .fields.status.name }}
summary: {{ .fields.summary }}
project: {{ .fields.project.key }}
components: {{ range .fields.components }}{{ .name }} {{end}}
issuetype: {{ .fields.issuetype.name }}
assignee: {{ if .fields.assignee }}{{ .fields.assignee.name }}{{end}}
reporter: {{ .fields.reporter.name }}
watchers: {{ range .fields.customfield_10110 }}{{ .name }} {{end}}
blockers: {{ range .fields.issuelinks }}{{if .outwardIssue}}{{ .outwardIssue.key }}[{{.outwardIssue.fields.status.name}}]{{end}}{{end}}
depends: {{ range .fields.issuelinks }}{{if .inwardIssue}}{{ .inwardIssue.key }}[{{.inwardIssue.fields.status.name}}]{{end}}{{end}}
priority: {{ .fields.priority.name }}
description: |
  {{ .fields.description | indent 2 }}

comments:
{{ range .fields.comment.comments }}  - | # {{.author.name}} at {{.created}}
    {{ .body | indent 4}}
{{end}}
`
const default_edit_template = `update:
  comment:
    - add:
        body: |
          {{ or .overrides.comment "" | indent 10 }}
fields:
  summary: {{ or .overrides.summary .fields.summary }}
  components: # {{ range .meta.fields.components.allowedValues }}{{.name}}, {{end}}{{if .overrides.components }}{{ range (split "," .overrides.components)}}
    - name: {{.}}{{end}}{{else}}{{ range .fields.components }}
    - name: {{ .name }}{{end}}{{end}}
  assignee:
    name: {{ if .overrides.assignee }}{{.overrides.assignee}}{{else}}{{if .fields.assignee }}{{ .fields.assignee.name }}{{end}}{{end}}
  reporter:
    name: {{ or .overrides.reporter .fields.reporter.name }}
  # watchers
  customfield_10110: {{ range .fields.customfield_10110 }}
    - name: {{ .name }}{{end}}{{if .overrides.watcher}}
    - name: {{ .overrides.watcher}}{{end}}
  priority: # {{ range .meta.fields.priority.allowedValues }}{{.name}}, {{end}}
    name: {{ or .overrides.priority .fields.priority.name }}
  description: |
    {{ or .overrides.description (or .fields.description "") | indent 4 }}
`
const default_transitions_template = `{{ range .transitions }}{{.id }}: {{.name}}
{{end}}`

const default_issuetypes_template = `{{ range .projects }}{{ range .issuetypes }}{{color "+bh"}}{{.name | append ":" | printf "%-13s" }}{{color "reset"}} {{.description}}
{{end}}{{end}}`

const default_create_template = `fields:
  project:
    key: {{ .overrides.project }}
  issuetype:
    name: {{ .overrides.issuetype }}
  summary: {{ or .overrides.summary "" }}
  priority: # {{ range .meta.fields.priority.allowedValues }}{{.name}}, {{end}}
    name: {{ or .overrides.priority "" }}
  components: # {{ range .meta.fields.components.allowedValues }}{{.name}}, {{end}}{{ range split "," (or .overrides.components "")}}
    - name: {{ . }}{{end}}
  description: |
    {{ or .overrides.description "" | indent 4 }}
  assignee:
    name: {{ or .overrides.assignee .overrides.user}}
  reporter:
    name: {{ or .overrides.reporter .overrides.user }}
  # watchers
  customfield_10110:
    - name:
`

const default_comment_template = `body: |
  {{ or .overrides.comment | indent 2 }}
`
<|endoftext|>


<commit_before>package jiracli

import (
	"fmt"
	"strings"

	"github.com/coryb/figtree"
	"github.com/coryb/oreo"

	jira "gopkg.in/Netflix-Skunkworks/go-jira.v1"
	"gopkg.in/Netflix-Skunkworks/go-jira.v1/jiradata"
	kingpin "gopkg.in/alecthomas/kingpin.v2"
)

type TransitionOptions struct {
	GlobalOptions `yaml:",inline" json:",inline" figtree:",inline"`
	Overrides     map[string]string `yaml:"overrides,omitempty" json:"overrides,omitempty"`
	Transition    string            `yaml:"transition,omitempty" json:"transition,omitempty"`
	Issue         string            `yaml:"issue,omitempty" json:"issue,omitempty"`
	Resolution    string            `yaml:"resolution,omitempty" json:"resolution,omitempty"`
}

func CmdTransitionRegistry(fig *figtree.FigTree, o *oreo.Client, transition string) *CommandRegistryEntry {
	opts := TransitionOptions{
		GlobalOptions: GlobalOptions{
			Template: figtree.NewStringOption("transition"),
		},
		Overrides: map[string]string{},
	}

	help := "Transition issue to given state"
	if transition == "" {
		help = fmt.Sprintf("Transition issue to %s state", transition)
	}

	return &CommandRegistryEntry{
		help,
		func() error {
			return CmdTransition(o, &opts)
		},
		func(cmd *kingpin.CmdClause) error {
			LoadConfigs(cmd, fig, &opts)
			if opts.Transition == "" {
				opts.Transition = transition
			}
			return CmdTransitionUsage(cmd, &opts)
		},
	}
}

func CmdTransitionUsage(cmd *kingpin.CmdClause, opts *TransitionOptions) error {
	if err := GlobalUsage(cmd, &opts.GlobalOptions); err != nil {
		return err
	}
	BrowseUsage(cmd, &opts.GlobalOptions)
	TemplateUsage(cmd, &opts.GlobalOptions)
	cmd.Flag("comment", "Comment message for issue").Short('m').PreAction(func(ctx *kingpin.ParseContext) error {
		opts.Overrides["comment"] = flagValue(ctx, "comment")
		return nil
	}).String()
	cmd.Flag("override", "Set issue property").Short('o').StringMapVar(&opts.Overrides)
	if opts.Transition == "" {
		cmd.Arg("TRANSITION", "State to transition issue to").Required().StringVar(&opts.Transition)
	}
	cmd.Arg("ISSUE", "issue to transition").Required().StringVar(&opts.Issue)
	return nil
}

// CmdTransition will move state of the given issue to the given transtion
func CmdTransition(o *oreo.Client, opts *TransitionOptions) error {
	issueData, err := jira.GetIssue(o, opts.Endpoint.Value, opts.Issue, nil)
	if err != nil {
		return err
	}

	meta, err := jira.GetIssueTransitions(o, opts.Endpoint.Value, opts.Issue)
	if err != nil {
		return err
	}
	transMeta := meta.Transitions.Find(opts.Transition)

	if transMeta == nil {
		possible := []string{}
		for _, trans := range meta.Transitions {
			possible = append(possible, trans.Name)
		}

		if status, ok := issueData.Fields["status"].(map[string]interface{}); ok {
			if name, ok := status["name"].(string); ok {
				return fmt.Errorf("Invalid Transition %q from %q, Available: %s", opts.Transition, name, strings.Join(possible, ", "))
			}
		}
		return fmt.Errorf("No valid transition found matching %s", opts.Transition)
	}

	// need to default the Resolution, usually Fixed works but sometime need Done
	if opts.Resolution == "" {
		if resField, ok := transMeta.Fields["resolution"]; ok {
			for _, allowedValueRaw := range resField.AllowedValues {
				if allowedValue, ok := allowedValueRaw.(map[string]interface{}); ok {
					if allowedValue["name"] == "Fixed" {
						opts.Resolution = "Fixed"
					} else if allowedValue["name"] == "Done" {
						opts.Resolution = "Done"
					}
				}
			}
		}
	}
	opts.Overrides["resolution"] = opts.Resolution

	type templateInput struct {
		*jiradata.Issue `yaml:",inline"`
		// Yes, Meta and Transition are redundant, but this is for backwards compatibility
		// with old templates
		Meta       *jiradata.Transition `yaml:"meta,omitempty" json:"meta,omitemtpy"`
		Transition *jiradata.Transition `yaml:"transition,omitempty" json:"transition,omitempty"`
		Overrides  map[string]string    `yaml:"overrides,omitempty" json:"overrides,omitempty"`
	}

	issueUpdate := jiradata.IssueUpdate{}
	input := templateInput{
		Issue:      issueData,
		Meta:       transMeta,
		Transition: transMeta,
		Overrides:  opts.Overrides,
	}
	err = editLoop(&opts.GlobalOptions, &input, &issueUpdate, func() error {
		return jira.TransitionIssue(o, opts.Endpoint.Value, opts.Issue, &issueUpdate)
	})
	if err != nil {
		return err
	}
	fmt.Printf("OK %s %s/browse/%s\n", issueData.Key, opts.Endpoint.Value, issueData.Key)

	if opts.Browse.Value {
		return CmdBrowse(&BrowseOptions{opts.GlobalOptions, opts.Issue})
	}
	return nil
}
<commit_msg>skip editing by default for the transition alias commands (ie done, progress, etc)<commit_after>package jiracli

import (
	"fmt"
	"strings"

	"github.com/coryb/figtree"
	"github.com/coryb/oreo"

	jira "gopkg.in/Netflix-Skunkworks/go-jira.v1"
	"gopkg.in/Netflix-Skunkworks/go-jira.v1/jiradata"
	kingpin "gopkg.in/alecthomas/kingpin.v2"
)

type TransitionOptions struct {
	GlobalOptions `yaml:",inline" json:",inline" figtree:",inline"`
	Overrides     map[string]string `yaml:"overrides,omitempty" json:"overrides,omitempty"`
	Transition    string            `yaml:"transition,omitempty" json:"transition,omitempty"`
	Issue         string            `yaml:"issue,omitempty" json:"issue,omitempty"`
	Resolution    string            `yaml:"resolution,omitempty" json:"resolution,omitempty"`
}

func CmdTransitionRegistry(fig *figtree.FigTree, o *oreo.Client, transition string) *CommandRegistryEntry {
	opts := TransitionOptions{
		GlobalOptions: GlobalOptions{
			Template: figtree.NewStringOption("transition"),
		},
		Overrides: map[string]string{},
	}

	help := "Transition issue to given state"
	if transition == "" {
		help = fmt.Sprintf("Transition issue to %s state", transition)
		opts.SkipEditing = figtree.NewBoolOption(true)
	}

	return &CommandRegistryEntry{
		help,
		func() error {
			return CmdTransition(o, &opts)
		},
		func(cmd *kingpin.CmdClause) error {
			LoadConfigs(cmd, fig, &opts)
			if opts.Transition == "" {
				opts.Transition = transition
			}
			return CmdTransitionUsage(cmd, &opts)
		},
	}
}

func CmdTransitionUsage(cmd *kingpin.CmdClause, opts *TransitionOptions) error {
	if err := GlobalUsage(cmd, &opts.GlobalOptions); err != nil {
		return err
	}
	BrowseUsage(cmd, &opts.GlobalOptions)
	TemplateUsage(cmd, &opts.GlobalOptions)
	cmd.Flag("noedit", "Disable opening the editor").SetValue(&opts.SkipEditing)
	cmd.Flag("comment", "Comment message for issue").Short('m').PreAction(func(ctx *kingpin.ParseContext) error {
		opts.Overrides["comment"] = flagValue(ctx, "comment")
		return nil
	}).String()
	cmd.Flag("override", "Set issue property").Short('o').StringMapVar(&opts.Overrides)
	if opts.Transition == "" {
		cmd.Arg("TRANSITION", "State to transition issue to").Required().StringVar(&opts.Transition)
	}
	cmd.Arg("ISSUE", "issue to transition").Required().StringVar(&opts.Issue)
	return nil
}

// CmdTransition will move state of the given issue to the given transtion
func CmdTransition(o *oreo.Client, opts *TransitionOptions) error {
	issueData, err := jira.GetIssue(o, opts.Endpoint.Value, opts.Issue, nil)
	if err != nil {
		return err
	}

	meta, err := jira.GetIssueTransitions(o, opts.Endpoint.Value, opts.Issue)
	if err != nil {
		return err
	}
	transMeta := meta.Transitions.Find(opts.Transition)

	if transMeta == nil {
		possible := []string{}
		for _, trans := range meta.Transitions {
			possible = append(possible, trans.Name)
		}

		if status, ok := issueData.Fields["status"].(map[string]interface{}); ok {
			if name, ok := status["name"].(string); ok {
				return fmt.Errorf("Invalid Transition %q from %q, Available: %s", opts.Transition, name, strings.Join(possible, ", "))
			}
		}
		return fmt.Errorf("No valid transition found matching %s", opts.Transition)
	}

	// need to default the Resolution, usually Fixed works but sometime need Done
	if opts.Resolution == "" {
		if resField, ok := transMeta.Fields["resolution"]; ok {
			for _, allowedValueRaw := range resField.AllowedValues {
				if allowedValue, ok := allowedValueRaw.(map[string]interface{}); ok {
					if allowedValue["name"] == "Fixed" {
						opts.Resolution = "Fixed"
					} else if allowedValue["name"] == "Done" {
						opts.Resolution = "Done"
					}
				}
			}
		}
	}
	opts.Overrides["resolution"] = opts.Resolution

	type templateInput struct {
		*jiradata.Issue `yaml:",inline"`
		// Yes, Meta and Transition are redundant, but this is for backwards compatibility
		// with old templates
		Meta       *jiradata.Transition `yaml:"meta,omitempty" json:"meta,omitemtpy"`
		Transition *jiradata.Transition `yaml:"transition,omitempty" json:"transition,omitempty"`
		Overrides  map[string]string    `yaml:"overrides,omitempty" json:"overrides,omitempty"`
	}

	issueUpdate := jiradata.IssueUpdate{}
	input := templateInput{
		Issue:      issueData,
		Meta:       transMeta,
		Transition: transMeta,
		Overrides:  opts.Overrides,
	}
	err = editLoop(&opts.GlobalOptions, &input, &issueUpdate, func() error {
		return jira.TransitionIssue(o, opts.Endpoint.Value, opts.Issue, &issueUpdate)
	})
	if err != nil {
		return err
	}
	fmt.Printf("OK %s %s/browse/%s\n", issueData.Key, opts.Endpoint.Value, issueData.Key)

	if opts.Browse.Value {
		return CmdBrowse(&BrowseOptions{opts.GlobalOptions, opts.Issue})
	}
	return nil
}
<|endoftext|>


<commit_before>/*
Package ghttp supports testing HTTP clients by providing a test server (simply a thin wrapper around httptest's server) that supports
registering multiple handlers.  Incoming requests are not routed between the different handlers
- rather it is merely the order of the handlers that matters.  The first request is handled by the first
registered handler, the second request by the second handler, etc.

The intent here is to have each handler *verify* that the incoming request is valid.  To accomplish, ghttp
also provides a collection of bite-size handlers that each perform one aspect of request verification.  These can
be composed together and registered with a ghttp server.  The result is an expressive language for describing
the requests generated by the client under test.

Here's a simple example, note that the server handler is only defined in one BeforeEach and then modified, as required, by the nested BeforeEaches.
A more comprehensive example is available at https://onsi.github.io/gomega/#_testing_http_clients

	var _ = Describe("A Sprockets Client", func() {
		var server *ghttp.Server
		var client *SprocketClient
		BeforeEach(func() {
			server = ghttp.NewServer()
			client = NewSprocketClient(server.URL(), "skywalker", "tk427")
		})

		AfterEach(func() {
			server.Close()
		})

		Describe("fetching sprockets", func() {
			var statusCode int
			var sprockets []Sprocket
			BeforeEach(func() {
				statusCode = http.StatusOK
				sprockets = []Sprocket{}
				server.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/sprockets"),
					ghttp.VerifyBasicAuth("skywalker", "tk427"),
					ghttp.RespondWithJSONEncodedPtr(&statusCode, &sprockets),
				))
			})

			Context("when requesting all sprockets", func() {
				Context("when the response is succesful", func() {
					BeforeEach(func() {
						sprockets = []Sprocket{
							NewSprocket("Alfalfa"),
							NewSprocket("Banana"),
						}
					})

					It("should return the returned sprockets", func() {
						Expect(client.Sprockets()).Should(Equal(sprockets))
					})
				})

				Context("when the response is missing", func() {
					BeforeEach(func() {
						statusCode = http.StatusNotFound
					})

					It("should return an empty list of sprockets", func() {
						Expect(client.Sprockets()).Should(BeEmpty())
					})
				})

				Context("when the response fails to authenticate", func() {
					BeforeEach(func() {
						statusCode = http.StatusUnauthorized
					})

					It("should return an AuthenticationError error", func() {
						sprockets, err := client.Sprockets()
						Expect(sprockets).Should(BeEmpty())
						Expect(err).Should(MatchError(AuthenticationError))
					})
				})

				Context("when the response is a server failure", func() {
					BeforeEach(func() {
						statusCode = http.StatusInternalServerError
					})

					It("should return an InternalError error", func() {
						sprockets, err := client.Sprockets()
						Expect(sprockets).Should(BeEmpty())
						Expect(err).Should(MatchError(InternalError))
					})
				})
			})

			Context("when requesting some sprockets", func() {
				BeforeEach(func() {
					sprockets = []Sprocket{
						NewSprocket("Alfalfa"),
						NewSprocket("Banana"),
					}

					server.WrapHandler(0, ghttp.VerifyRequest("GET", "/sprockets", "filter=FOOD"))
				})

				It("should make the request with a filter", func() {
					Expect(client.Sprockets("food")).Should(Equal(sprockets))
				})
			})
		})
	})
*/
package ghttp

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"reflect"
	"regexp"
	"strings"
	"sync"

	. "github.com/onsi/gomega"
)

func new() *Server {
	return &Server{
		AllowUnhandledRequests:     false,
		UnhandledRequestStatusCode: http.StatusInternalServerError,
		writeLock:                  &sync.Mutex{},
	}
}

type routedHandler struct {
	method     string
	pathRegexp *regexp.Regexp
	path       string
	handler    http.HandlerFunc
}

// NewServer returns a new `*ghttp.Server` that wraps an `httptest` server.  The server is started automatically.
func NewServer() *Server {
	s := new()
	s.HTTPTestServer = httptest.NewServer(s)
	return s
}

// NewUnstartedServer return a new, unstarted, `*ghttp.Server`.  Useful for specifying a custom listener on `server.HTTPTestServer`.
func NewUnstartedServer() *Server {
	s := new()
	s.HTTPTestServer = httptest.NewUnstartedServer(s)
	return s
}

// NewTLSServer returns a new `*ghttp.Server` that wraps an `httptest` TLS server.  The server is started automatically.
func NewTLSServer() *Server {
	s := new()
	s.HTTPTestServer = httptest.NewTLSServer(s)
	return s
}

type Server struct {
	//The underlying httptest server
	HTTPTestServer *httptest.Server

	//Defaults to false.  If set to true, the Server will allow more requests than there are registered handlers.
	//Direct use of this property is deprecated and is likely to be removed, use GetAllowUnhandledRequests and SetAllowUnhandledRequests instead.
	AllowUnhandledRequests bool

	//The status code returned when receiving an unhandled request.
	//Defaults to http.StatusInternalServerError.
	//Only applies if AllowUnhandledRequests is true
	//Direct use of this property is deprecated and is likely to be removed, use GetUnhandledRequestStatusCode and SetUnhandledRequestStatusCode instead.
	UnhandledRequestStatusCode int

	//If provided, ghttp will log about each request received to the provided io.Writer
	//Defaults to nil
	//If you're using Ginkgo, set this to GinkgoWriter to get improved output during failures
	Writer io.Writer

	receivedRequests []*http.Request
	requestHandlers  []http.HandlerFunc
	routedHandlers   []routedHandler

	writeLock *sync.Mutex
	calls     int
}

//Start() starts an unstarted ghttp server.  It is a catastrophic error to call Start more than once (thanks, httptest).
func (s *Server) Start() {
	s.HTTPTestServer.Start()
}

//URL() returns a url that will hit the server
func (s *Server) URL() string {
	return s.HTTPTestServer.URL
}

//Addr() returns the address on which the server is listening.
func (s *Server) Addr() string {
	return s.HTTPTestServer.Listener.Addr().String()
}

//Close() should be called at the end of each test.  It spins down and cleans up the test server.
func (s *Server) Close() {
	s.writeLock.Lock()
	server := s.HTTPTestServer
	s.HTTPTestServer = nil
	s.writeLock.Unlock()

	if server != nil {
		server.Close()
	}
}

//ServeHTTP() makes Server an http.Handler
//When the server receives a request it handles the request in the following order:
//
//1. If the request matches a handler registered with RouteToHandler, that handler is called.
//2. Otherwise, if there are handlers registered via AppendHandlers, those handlers are called in order.
//3. If all registered handlers have been called then:
//   a) If AllowUnhandledRequests is set to true, the request will be handled with response code of UnhandledRequestStatusCode
//   b) If AllowUnhandledRequests is false, the request will not be handled and the current test will be marked as failed.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.writeLock.Lock()
	defer func() {
		e := recover()
		if e != nil {
			w.WriteHeader(http.StatusInternalServerError)
		}

		//If the handler panics GHTTP will silently succeed.  This is bad™.
		//To catch this case we need to fail the test if the handler has panicked.
		//However, if the handler is panicking because Ginkgo's causing it to panic (i.e. an assertion failed)
		//then we shouldn't double-report the error as this will confuse people.

		//So: step 1, if this is a Ginkgo panic - do nothing, Ginkgo's aware of the failure
		eAsString, ok := e.(string)
		if ok && strings.Contains(eAsString, "defer GinkgoRecover()") {
			return
		}

		//If we're here, we have to do step 2: assert that the error is nil.  This assertion will
		//allow us to fail the test suite (note: we can't call Fail since Gomega is not allowed to import Ginkgo).
		//Since a failed assertion throws a panic, and we are likely in a goroutine, we need to defer within our defer!
		defer func() {
			recover()
		}()
		Expect(e).Should(BeNil(), "Handler Panicked")
	}()

	if s.Writer != nil {
		s.Writer.Write([]byte(fmt.Sprintf("GHTTP Received Request: %s - %s\n", req.Method, req.URL)))
	}

	s.receivedRequests = append(s.receivedRequests, req)
	if routedHandler, ok := s.handlerForRoute(req.Method, req.URL.Path); ok {
		s.writeLock.Unlock()
		routedHandler(w, req)
	} else if s.calls < len(s.requestHandlers) {
		h := s.requestHandlers[s.calls]
		s.calls++
		s.writeLock.Unlock()
		h(w, req)
	} else {
		s.writeLock.Unlock()
		if s.GetAllowUnhandledRequests() {
			ioutil.ReadAll(req.Body)
			req.Body.Close()
			w.WriteHeader(s.GetUnhandledRequestStatusCode())
		} else {
			Expect(req).Should(BeNil(), "Received Unhandled Request")
		}
	}
}

//ReceivedRequests is an array containing all requests received by the server (both handled and unhandled requests)
func (s *Server) ReceivedRequests() []*http.Request {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.receivedRequests
}

//RouteToHandler can be used to register handlers that will always handle requests that match
//the passed in method and path.
//
//The path may be either a string object or a *regexp.Regexp.
func (s *Server) RouteToHandler(method string, path interface{}, handler http.HandlerFunc) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	rh := routedHandler{
		method:  method,
		handler: handler,
	}

	switch p := path.(type) {
	case *regexp.Regexp:
		rh.pathRegexp = p
	case string:
		rh.path = p
	default:
		panic("path must be a string or a regular expression")
	}

	for i, existingRH := range s.routedHandlers {
		if existingRH.method == method &&
			reflect.DeepEqual(existingRH.pathRegexp, rh.pathRegexp) &&
			existingRH.path == rh.path {
			s.routedHandlers[i] = rh
			return
		}
	}
	s.routedHandlers = append(s.routedHandlers, rh)
}

func (s *Server) handlerForRoute(method string, path string) (http.HandlerFunc, bool) {
	for _, rh := range s.routedHandlers {
		if rh.method == method {
			if rh.pathRegexp != nil {
				if rh.pathRegexp.Match([]byte(path)) {
					return rh.handler, true
				}
			} else if rh.path == path {
				return rh.handler, true
			}
		}
	}

	return nil, false
}

//AppendHandlers will appends http.HandlerFuncs to the server's list of registered handlers.  The first incoming request is handled by the first handler, the second by the second, etc...
func (s *Server) AppendHandlers(handlers ...http.HandlerFunc) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.requestHandlers = append(s.requestHandlers, handlers...)
}

//SetHandler overrides the registered handler at the passed in index with the passed in handler
//This is useful, for example, when a server has been set up in a shared context, but must be tweaked
//for a particular test.
func (s *Server) SetHandler(index int, handler http.HandlerFunc) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.requestHandlers[index] = handler
}

//GetHandler returns the handler registered at the passed in index.
func (s *Server) GetHandler(index int) http.HandlerFunc {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.requestHandlers[index]
}

func (s *Server) Reset() {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.HTTPTestServer.CloseClientConnections()
	s.calls = 0
	s.receivedRequests = nil
	s.requestHandlers = nil
	s.routedHandlers = nil
}

//WrapHandler combines the passed in handler with the handler registered at the passed in index.
//This is useful, for example, when a server has been set up in a shared context but must be tweaked
//for a particular test.
//
//If the currently registered handler is A, and the new passed in handler is B then
//WrapHandler will generate a new handler that first calls A, then calls B, and assign it to index
func (s *Server) WrapHandler(index int, handler http.HandlerFunc) {
	existingHandler := s.GetHandler(index)
	s.SetHandler(index, CombineHandlers(existingHandler, handler))
}

func (s *Server) CloseClientConnections() {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.HTTPTestServer.CloseClientConnections()
}

//SetAllowUnhandledRequests enables the server to accept unhandled requests.
func (s *Server) SetAllowUnhandledRequests(allowUnhandledRequests bool) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.AllowUnhandledRequests = allowUnhandledRequests
}

//GetAllowUnhandledRequests returns true if the server accepts unhandled requests.
func (s *Server) GetAllowUnhandledRequests() bool {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.AllowUnhandledRequests
}

//SetUnhandledRequestStatusCode status code to be returned when the server receives unhandled requests
func (s *Server) SetUnhandledRequestStatusCode(statusCode int) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.UnhandledRequestStatusCode = statusCode
}

//GetUnhandledRequestStatusCode returns the current status code being returned for unhandled requests
func (s *Server) GetUnhandledRequestStatusCode() int {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.UnhandledRequestStatusCode
}
<commit_msg>Use httputil.DumpRequest to pretty-print unhandled requests<commit_after>/*
Package ghttp supports testing HTTP clients by providing a test server (simply a thin wrapper around httptest's server) that supports
registering multiple handlers.  Incoming requests are not routed between the different handlers
- rather it is merely the order of the handlers that matters.  The first request is handled by the first
registered handler, the second request by the second handler, etc.

The intent here is to have each handler *verify* that the incoming request is valid.  To accomplish, ghttp
also provides a collection of bite-size handlers that each perform one aspect of request verification.  These can
be composed together and registered with a ghttp server.  The result is an expressive language for describing
the requests generated by the client under test.

Here's a simple example, note that the server handler is only defined in one BeforeEach and then modified, as required, by the nested BeforeEaches.
A more comprehensive example is available at https://onsi.github.io/gomega/#_testing_http_clients

	var _ = Describe("A Sprockets Client", func() {
		var server *ghttp.Server
		var client *SprocketClient
		BeforeEach(func() {
			server = ghttp.NewServer()
			client = NewSprocketClient(server.URL(), "skywalker", "tk427")
		})

		AfterEach(func() {
			server.Close()
		})

		Describe("fetching sprockets", func() {
			var statusCode int
			var sprockets []Sprocket
			BeforeEach(func() {
				statusCode = http.StatusOK
				sprockets = []Sprocket{}
				server.AppendHandlers(ghttp.CombineHandlers(
					ghttp.VerifyRequest("GET", "/sprockets"),
					ghttp.VerifyBasicAuth("skywalker", "tk427"),
					ghttp.RespondWithJSONEncodedPtr(&statusCode, &sprockets),
				))
			})

			Context("when requesting all sprockets", func() {
				Context("when the response is succesful", func() {
					BeforeEach(func() {
						sprockets = []Sprocket{
							NewSprocket("Alfalfa"),
							NewSprocket("Banana"),
						}
					})

					It("should return the returned sprockets", func() {
						Expect(client.Sprockets()).Should(Equal(sprockets))
					})
				})

				Context("when the response is missing", func() {
					BeforeEach(func() {
						statusCode = http.StatusNotFound
					})

					It("should return an empty list of sprockets", func() {
						Expect(client.Sprockets()).Should(BeEmpty())
					})
				})

				Context("when the response fails to authenticate", func() {
					BeforeEach(func() {
						statusCode = http.StatusUnauthorized
					})

					It("should return an AuthenticationError error", func() {
						sprockets, err := client.Sprockets()
						Expect(sprockets).Should(BeEmpty())
						Expect(err).Should(MatchError(AuthenticationError))
					})
				})

				Context("when the response is a server failure", func() {
					BeforeEach(func() {
						statusCode = http.StatusInternalServerError
					})

					It("should return an InternalError error", func() {
						sprockets, err := client.Sprockets()
						Expect(sprockets).Should(BeEmpty())
						Expect(err).Should(MatchError(InternalError))
					})
				})
			})

			Context("when requesting some sprockets", func() {
				BeforeEach(func() {
					sprockets = []Sprocket{
						NewSprocket("Alfalfa"),
						NewSprocket("Banana"),
					}

					server.WrapHandler(0, ghttp.VerifyRequest("GET", "/sprockets", "filter=FOOD"))
				})

				It("should make the request with a filter", func() {
					Expect(client.Sprockets("food")).Should(Equal(sprockets))
				})
			})
		})
	})
*/
package ghttp

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"reflect"
	"regexp"
	"strings"
	"sync"

	. "github.com/onsi/gomega"
)

func new() *Server {
	return &Server{
		AllowUnhandledRequests:     false,
		UnhandledRequestStatusCode: http.StatusInternalServerError,
		writeLock:                  &sync.Mutex{},
	}
}

type routedHandler struct {
	method     string
	pathRegexp *regexp.Regexp
	path       string
	handler    http.HandlerFunc
}

// NewServer returns a new `*ghttp.Server` that wraps an `httptest` server.  The server is started automatically.
func NewServer() *Server {
	s := new()
	s.HTTPTestServer = httptest.NewServer(s)
	return s
}

// NewUnstartedServer return a new, unstarted, `*ghttp.Server`.  Useful for specifying a custom listener on `server.HTTPTestServer`.
func NewUnstartedServer() *Server {
	s := new()
	s.HTTPTestServer = httptest.NewUnstartedServer(s)
	return s
}

// NewTLSServer returns a new `*ghttp.Server` that wraps an `httptest` TLS server.  The server is started automatically.
func NewTLSServer() *Server {
	s := new()
	s.HTTPTestServer = httptest.NewTLSServer(s)
	return s
}

type Server struct {
	//The underlying httptest server
	HTTPTestServer *httptest.Server

	//Defaults to false.  If set to true, the Server will allow more requests than there are registered handlers.
	//Direct use of this property is deprecated and is likely to be removed, use GetAllowUnhandledRequests and SetAllowUnhandledRequests instead.
	AllowUnhandledRequests bool

	//The status code returned when receiving an unhandled request.
	//Defaults to http.StatusInternalServerError.
	//Only applies if AllowUnhandledRequests is true
	//Direct use of this property is deprecated and is likely to be removed, use GetUnhandledRequestStatusCode and SetUnhandledRequestStatusCode instead.
	UnhandledRequestStatusCode int

	//If provided, ghttp will log about each request received to the provided io.Writer
	//Defaults to nil
	//If you're using Ginkgo, set this to GinkgoWriter to get improved output during failures
	Writer io.Writer

	receivedRequests []*http.Request
	requestHandlers  []http.HandlerFunc
	routedHandlers   []routedHandler

	writeLock *sync.Mutex
	calls     int
}

//Start() starts an unstarted ghttp server.  It is a catastrophic error to call Start more than once (thanks, httptest).
func (s *Server) Start() {
	s.HTTPTestServer.Start()
}

//URL() returns a url that will hit the server
func (s *Server) URL() string {
	return s.HTTPTestServer.URL
}

//Addr() returns the address on which the server is listening.
func (s *Server) Addr() string {
	return s.HTTPTestServer.Listener.Addr().String()
}

//Close() should be called at the end of each test.  It spins down and cleans up the test server.
func (s *Server) Close() {
	s.writeLock.Lock()
	server := s.HTTPTestServer
	s.HTTPTestServer = nil
	s.writeLock.Unlock()

	if server != nil {
		server.Close()
	}
}

//ServeHTTP() makes Server an http.Handler
//When the server receives a request it handles the request in the following order:
//
//1. If the request matches a handler registered with RouteToHandler, that handler is called.
//2. Otherwise, if there are handlers registered via AppendHandlers, those handlers are called in order.
//3. If all registered handlers have been called then:
//   a) If AllowUnhandledRequests is set to true, the request will be handled with response code of UnhandledRequestStatusCode
//   b) If AllowUnhandledRequests is false, the request will not be handled and the current test will be marked as failed.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.writeLock.Lock()
	defer func() {
		e := recover()
		if e != nil {
			w.WriteHeader(http.StatusInternalServerError)
		}

		//If the handler panics GHTTP will silently succeed.  This is bad™.
		//To catch this case we need to fail the test if the handler has panicked.
		//However, if the handler is panicking because Ginkgo's causing it to panic (i.e. an assertion failed)
		//then we shouldn't double-report the error as this will confuse people.

		//So: step 1, if this is a Ginkgo panic - do nothing, Ginkgo's aware of the failure
		eAsString, ok := e.(string)
		if ok && strings.Contains(eAsString, "defer GinkgoRecover()") {
			return
		}

		//If we're here, we have to do step 2: assert that the error is nil.  This assertion will
		//allow us to fail the test suite (note: we can't call Fail since Gomega is not allowed to import Ginkgo).
		//Since a failed assertion throws a panic, and we are likely in a goroutine, we need to defer within our defer!
		defer func() {
			recover()
		}()
		Expect(e).Should(BeNil(), "Handler Panicked")
	}()

	if s.Writer != nil {
		s.Writer.Write([]byte(fmt.Sprintf("GHTTP Received Request: %s - %s\n", req.Method, req.URL)))
	}

	s.receivedRequests = append(s.receivedRequests, req)
	if routedHandler, ok := s.handlerForRoute(req.Method, req.URL.Path); ok {
		s.writeLock.Unlock()
		routedHandler(w, req)
	} else if s.calls < len(s.requestHandlers) {
		h := s.requestHandlers[s.calls]
		s.calls++
		s.writeLock.Unlock()
		h(w, req)
	} else {
		s.writeLock.Unlock()
		if s.GetAllowUnhandledRequests() {
			ioutil.ReadAll(req.Body)
			req.Body.Close()
			w.WriteHeader(s.GetUnhandledRequestStatusCode())
		} else {
			formatted, err := httputil.DumpRequest(req, true)
			Expect(err).NotTo(HaveOccurred(), "Encountered error while dumping HTTP request")
			Expect(string(formatted)).Should(BeNil(), "Received Unhandled Request")
		}
	}
}

//ReceivedRequests is an array containing all requests received by the server (both handled and unhandled requests)
func (s *Server) ReceivedRequests() []*http.Request {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.receivedRequests
}

//RouteToHandler can be used to register handlers that will always handle requests that match
//the passed in method and path.
//
//The path may be either a string object or a *regexp.Regexp.
func (s *Server) RouteToHandler(method string, path interface{}, handler http.HandlerFunc) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	rh := routedHandler{
		method:  method,
		handler: handler,
	}

	switch p := path.(type) {
	case *regexp.Regexp:
		rh.pathRegexp = p
	case string:
		rh.path = p
	default:
		panic("path must be a string or a regular expression")
	}

	for i, existingRH := range s.routedHandlers {
		if existingRH.method == method &&
			reflect.DeepEqual(existingRH.pathRegexp, rh.pathRegexp) &&
			existingRH.path == rh.path {
			s.routedHandlers[i] = rh
			return
		}
	}
	s.routedHandlers = append(s.routedHandlers, rh)
}

func (s *Server) handlerForRoute(method string, path string) (http.HandlerFunc, bool) {
	for _, rh := range s.routedHandlers {
		if rh.method == method {
			if rh.pathRegexp != nil {
				if rh.pathRegexp.Match([]byte(path)) {
					return rh.handler, true
				}
			} else if rh.path == path {
				return rh.handler, true
			}
		}
	}

	return nil, false
}

//AppendHandlers will appends http.HandlerFuncs to the server's list of registered handlers.  The first incoming request is handled by the first handler, the second by the second, etc...
func (s *Server) AppendHandlers(handlers ...http.HandlerFunc) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.requestHandlers = append(s.requestHandlers, handlers...)
}

//SetHandler overrides the registered handler at the passed in index with the passed in handler
//This is useful, for example, when a server has been set up in a shared context, but must be tweaked
//for a particular test.
func (s *Server) SetHandler(index int, handler http.HandlerFunc) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.requestHandlers[index] = handler
}

//GetHandler returns the handler registered at the passed in index.
func (s *Server) GetHandler(index int) http.HandlerFunc {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.requestHandlers[index]
}

func (s *Server) Reset() {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.HTTPTestServer.CloseClientConnections()
	s.calls = 0
	s.receivedRequests = nil
	s.requestHandlers = nil
	s.routedHandlers = nil
}

//WrapHandler combines the passed in handler with the handler registered at the passed in index.
//This is useful, for example, when a server has been set up in a shared context but must be tweaked
//for a particular test.
//
//If the currently registered handler is A, and the new passed in handler is B then
//WrapHandler will generate a new handler that first calls A, then calls B, and assign it to index
func (s *Server) WrapHandler(index int, handler http.HandlerFunc) {
	existingHandler := s.GetHandler(index)
	s.SetHandler(index, CombineHandlers(existingHandler, handler))
}

func (s *Server) CloseClientConnections() {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.HTTPTestServer.CloseClientConnections()
}

//SetAllowUnhandledRequests enables the server to accept unhandled requests.
func (s *Server) SetAllowUnhandledRequests(allowUnhandledRequests bool) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.AllowUnhandledRequests = allowUnhandledRequests
}

//GetAllowUnhandledRequests returns true if the server accepts unhandled requests.
func (s *Server) GetAllowUnhandledRequests() bool {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.AllowUnhandledRequests
}

//SetUnhandledRequestStatusCode status code to be returned when the server receives unhandled requests
func (s *Server) SetUnhandledRequestStatusCode(statusCode int) {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	s.UnhandledRequestStatusCode = statusCode
}

//GetUnhandledRequestStatusCode returns the current status code being returned for unhandled requests
func (s *Server) GetUnhandledRequestStatusCode() int {
	s.writeLock.Lock()
	defer s.writeLock.Unlock()

	return s.UnhandledRequestStatusCode
}
<|endoftext|>


<commit_before>package api

import (
	"socialapi/workers/common/handler"
	"socialapi/workers/common/mux"
)

func AddHandlers(m *mux.Mux) {
	m.AddHandler(
		handler.Request{
			Handler:  CreateLink,
			Name:     models.ModerationChannelCreateLink,
			Type:     handler.PostRequest,
			Endpoint: "/moderation/channel/{rootId}/link",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  GetLink,
			Name:     models.ModerationChannelGetLink,
			Type:     handler.GetRequest,
			Endpoint: "/moderation/channel/{rootId}/link",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Unlink,
			Name:     models.ModerationChannelDeleteLink,
			Type:     handler.DeleteRequest,
			Endpoint: "/moderation/channel/{rootId}/link/{leafId}",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Blacklist,
			Name:     models.ModerationChannelBlacklist,
			Type:     handler.DeleteRequest,
			Endpoint: "/moderation/channel/{rootId}",
		},
	)
}
<commit_msg>Socialapi: fix naming problems<commit_after>package api

import (
	"socialapi/models"
	"socialapi/workers/common/handler"
	"socialapi/workers/common/mux"
)

func AddHandlers(m *mux.Mux) {
	m.AddHandler(
		handler.Request{
			Handler:  CreateLink,
			Name:     models.ModerationChannelCreateLink,
			Type:     handler.PostRequest,
			Endpoint: "/moderation/channel/{rootId}/link",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  GetLinks,
			Name:     models.ModerationChannelGetLink,
			Type:     handler.GetRequest,
			Endpoint: "/moderation/channel/{rootId}/link",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  UnLink,
			Name:     models.ModerationChannelDeleteLink,
			Type:     handler.DeleteRequest,
			Endpoint: "/moderation/channel/{rootId}/link/{leafId}",
		},
	)

	m.AddHandler(
		handler.Request{
			Handler:  Blacklist,
			Name:     models.ModerationChannelBlacklist,
			Type:     handler.DeleteRequest,
			Endpoint: "/moderation/channel/{rootId}",
		},
	)
}
<|endoftext|>