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

package template

import (
	"fmt"
	"reflect"
)

// Strings of content from a trusted source.
type (
	// CSS encapsulates known safe content that matches any of:
	//   1. The CSS3 stylesheet production, such as `p { color: purple }`.
	//   2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
	//   3. CSS3 declaration productions, such as `color: red; margin: 2px`.
	//   4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.
	// See http://www.w3.org/TR/css3-syntax/#style
	CSS string

	// HTML encapsulates a known safe HTML document fragment.
	// It should not be used for HTML from a third-party, or HTML with
	// unclosed tags or comments. The outputs of a sound HTML sanitizer
	// and a template escaped by this package are fine for use with HTML.
	HTML string

	// HTMLAttr encapsulates an HTML attribute from a trusted source,
	// for example, ` dir="ltr"`.
	HTMLAttr string

	// JS encapsulates a known safe EcmaScript5 Expression, for example,
	// `(x + y * z())`.
	// Template authors are responsible for ensuring that typed expressions
	// do not break the intended precedence and that there is no
	// statement/expression ambiguity as when passing an expression like
	// "{ foo: bar() }\n['foo']()", which is both a valid Expression and a
	// valid Program with a very different meaning.
	JS string

	// JSStr encapsulates a sequence of characters meant to be embedded
	// between quotes in a JavaScript expression.
	// The string must match a series of StringCharacters:
	//   StringCharacter :: SourceCharacter but not `\` or LineTerminator
	//                    | EscapeSequence
	// Note that LineContinuations are not allowed.
	// JSStr("foo\\nbar") is fine, but JSStr("foo\\\nbar") is not.
	JSStr string

	// URL encapsulates a known safe URL as defined in RFC 3896.
	// A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()`
	// from a trusted source should go in the page, but by default dynamic
	// `javascript:` URLs are filtered out since they are a frequently
	// exploited injection vector.
	URL string
)

type contentType uint8

const (
	contentTypePlain contentType = iota
	contentTypeCSS
	contentTypeHTML
	contentTypeHTMLAttr
	contentTypeJS
	contentTypeJSStr
	contentTypeURL
	// contentTypeUnsafe is used in attr.go for values that affect how
	// embedded content and network messages are formed, vetted,
	// or interpreted; or which credentials network messages carry.
	contentTypeUnsafe
)

// indirect returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil).
func indirect(a interface{}) interface{} {
	if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
		// Avoid creating a reflect.Value if it's not a pointer.
		return a
	}
	v := reflect.ValueOf(a)
	for v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}
	return v.Interface()
}

var (
	errorType       = reflect.TypeOf((*error)(nil)).Elem()
	fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
)

// indirectToStringerOrError returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
// or error,
func indirectToStringerOrError(a interface{}) interface{} {
	v := reflect.ValueOf(a)
	for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}
	return v.Interface()
}

// stringify converts its arguments to a string and the type of the content.
// All pointers are dereferenced, as in the text/template package.
func stringify(args ...interface{}) (string, contentType) {
	if len(args) == 1 {
		switch s := indirect(args[0]).(type) {
		case string:
			return s, contentTypePlain
		case CSS:
			return string(s), contentTypeCSS
		case HTML:
			return string(s), contentTypeHTML
		case HTMLAttr:
			return string(s), contentTypeHTMLAttr
		case JS:
			return string(s), contentTypeJS
		case JSStr:
			return string(s), contentTypeJSStr
		case URL:
			return string(s), contentTypeURL
		}
	}
	for i, arg := range args {
		args[i] = indirectToStringerOrError(arg)
	}
	return fmt.Sprint(args...), contentTypePlain
}
<commit_msg>html/template: fix URL doc<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package template

import (
	"fmt"
	"reflect"
)

// Strings of content from a trusted source.
type (
	// CSS encapsulates known safe content that matches any of:
	//   1. The CSS3 stylesheet production, such as `p { color: purple }`.
	//   2. The CSS3 rule production, such as `a[href=~"https:"].foo#bar`.
	//   3. CSS3 declaration productions, such as `color: red; margin: 2px`.
	//   4. The CSS3 value production, such as `rgba(0, 0, 255, 127)`.
	// See http://www.w3.org/TR/css3-syntax/#style
	CSS string

	// HTML encapsulates a known safe HTML document fragment.
	// It should not be used for HTML from a third-party, or HTML with
	// unclosed tags or comments. The outputs of a sound HTML sanitizer
	// and a template escaped by this package are fine for use with HTML.
	HTML string

	// HTMLAttr encapsulates an HTML attribute from a trusted source,
	// for example, ` dir="ltr"`.
	HTMLAttr string

	// JS encapsulates a known safe EcmaScript5 Expression, for example,
	// `(x + y * z())`.
	// Template authors are responsible for ensuring that typed expressions
	// do not break the intended precedence and that there is no
	// statement/expression ambiguity as when passing an expression like
	// "{ foo: bar() }\n['foo']()", which is both a valid Expression and a
	// valid Program with a very different meaning.
	JS string

	// JSStr encapsulates a sequence of characters meant to be embedded
	// between quotes in a JavaScript expression.
	// The string must match a series of StringCharacters:
	//   StringCharacter :: SourceCharacter but not `\` or LineTerminator
	//                    | EscapeSequence
	// Note that LineContinuations are not allowed.
	// JSStr("foo\\nbar") is fine, but JSStr("foo\\\nbar") is not.
	JSStr string

	// URL encapsulates a known safe URL or URL substring (see RFC 3986).
	// A URL like `javascript:checkThatFormNotEditedBeforeLeavingPage()`
	// from a trusted source should go in the page, but by default dynamic
	// `javascript:` URLs are filtered out since they are a frequently
	// exploited injection vector.
	URL string
)

type contentType uint8

const (
	contentTypePlain contentType = iota
	contentTypeCSS
	contentTypeHTML
	contentTypeHTMLAttr
	contentTypeJS
	contentTypeJSStr
	contentTypeURL
	// contentTypeUnsafe is used in attr.go for values that affect how
	// embedded content and network messages are formed, vetted,
	// or interpreted; or which credentials network messages carry.
	contentTypeUnsafe
)

// indirect returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil).
func indirect(a interface{}) interface{} {
	if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
		// Avoid creating a reflect.Value if it's not a pointer.
		return a
	}
	v := reflect.ValueOf(a)
	for v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}
	return v.Interface()
}

var (
	errorType       = reflect.TypeOf((*error)(nil)).Elem()
	fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
)

// indirectToStringerOrError returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
// or error,
func indirectToStringerOrError(a interface{}) interface{} {
	v := reflect.ValueOf(a)
	for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}
	return v.Interface()
}

// stringify converts its arguments to a string and the type of the content.
// All pointers are dereferenced, as in the text/template package.
func stringify(args ...interface{}) (string, contentType) {
	if len(args) == 1 {
		switch s := indirect(args[0]).(type) {
		case string:
			return s, contentTypePlain
		case CSS:
			return string(s), contentTypeCSS
		case HTML:
			return string(s), contentTypeHTML
		case HTMLAttr:
			return string(s), contentTypeHTMLAttr
		case JS:
			return string(s), contentTypeJS
		case JSStr:
			return string(s), contentTypeJSStr
		case URL:
			return string(s), contentTypeURL
		}
	}
	for i, arg := range args {
		args[i] = indirectToStringerOrError(arg)
	}
	return fmt.Sprint(args...), contentTypePlain
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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 (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func addTeam(handler http.Handler, teamID string, t *testing.T) {
	team := Team{ID: teamID, DisplayName: teamID}
	b := new(bytes.Buffer)
	enc := json.NewEncoder(b)
	err := enc.Encode(team)
	if err != nil {
		t.Fatalf("Could not serialize team: %v", err)
	}
	req := httptest.NewRequest(http.MethodPost, "/api/team/", b)
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Expected response %v, got %v", http.StatusOK, resp.StatusCode)
	}
}

func addPeriod(handler http.Handler, teamID, periodJSON string, t *testing.T) {
	req := httptest.NewRequest(http.MethodPost, "/api/period/"+teamID+"/", strings.NewReader(periodJSON))
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusOK {
		bodyBytes, _ := ioutil.ReadAll(resp.Body)
		body := string(bodyBytes)
		t.Fatalf("Expected response %v, got %v: %v", http.StatusOK, resp.StatusCode, body)
	}
}

func TestPostPeriod(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	teamID := "myteam"
	addTeam(handler, teamID, t)
	periodJSON := `{"id":"2019q1","displayName":"2019Q1","unit":"person weeks","notesURL":"http://test","buckets":[{"displayName":"Bucket one","allocationPercentage":80,"objectives":[{"name":"Objective 1","resourceEstimate":0,"commitmentType":"Committed","assignments":[]}]}],"people":[]}`
	addPeriod(handler, teamID, periodJSON, t)

	req := httptest.NewRequest(http.MethodGet, "/api/period/"+teamID+"/2019q1", nil)
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Expected response %v, got %v", http.StatusOK, resp.StatusCode)
	}
	p := Period{}
	dec := json.NewDecoder(resp.Body)
	err := dec.Decode(&p)
	if err != nil {
		t.Fatalf("Could not decode response body: %v", err)
	}
	if p.Buckets[0].AllocationPercentage != 80 {
		t.Fatalf("Expected allocation percentage 80, found %v", p.Buckets[0].AllocationPercentage)
	}
}

func TestInvalidCommitmentType(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	teamID := "myteam"
	addTeam(handler, teamID, t)
	periodJSON := `{"id":"2019q1","displayName":"2019Q1","unit":"person weeks","notesURL":"http://test","buckets":[{"displayName":"Bucket one","allocationPercentage":80,"objectives":[{"name":"Objective 1","resourceEstimate":0,"commitmentType":"wibble","assignments":[]}]}],"people":[]}`

	req := httptest.NewRequest(http.MethodPost, "/api/period/"+teamID+"/", strings.NewReader(periodJSON))
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()

	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)

	if resp.StatusCode != http.StatusBadRequest {
		t.Fatalf("Expected status code %v, found %v: %v", http.StatusBadRequest, resp.StatusCode, body)
	}

	if !strings.Contains(body, "wibble") {
		t.Fatalf("Expected bad commitment type to appear in body, found: %v", body)
	}
}

func TestImprove(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	req := httptest.NewRequest(http.MethodGet, "/improve", nil)
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusFound {
		t.Fatalf("Expected response %c, got %v", http.StatusFound, resp.StatusCode)
	}
	expectedImproveURL := "https://github.com/google/peoplemath"
	location := resp.Header.Get("Location")
	if location != expectedImproveURL {
		t.Errorf("Expected redirect to %v, found %v", expectedImproveURL, location)
	}

	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)
	if !strings.Contains(body, expectedImproveURL) {
		t.Errorf("Expected redirect URL %v in body, found %v", expectedImproveURL, body)
	}
}
<commit_msg>Add backend test for missing commitment type Also refactor a little.<commit_after>// Copyright 2019 Google LLC
//
// 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 (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func addTeam(handler http.Handler, teamID string, t *testing.T) {
	team := Team{ID: teamID, DisplayName: teamID}
	b := new(bytes.Buffer)
	enc := json.NewEncoder(b)
	err := enc.Encode(team)
	if err != nil {
		t.Fatalf("Could not serialize team: %v", err)
	}
	req := httptest.NewRequest(http.MethodPost, "/api/team/", b)
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Expected response %v, got %v", http.StatusOK, resp.StatusCode)
	}
}

func attemptWritePeriod(handler http.Handler, teamID, periodJSON, httpMethod string, t *testing.T) *http.Response {
	req := httptest.NewRequest(httpMethod, "/api/period/"+teamID+"/", strings.NewReader(periodJSON))
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	return w.Result()
}

func addPeriod(handler http.Handler, teamID, periodJSON string, t *testing.T) {
	resp := attemptWritePeriod(handler, teamID, periodJSON, http.MethodPost, t)
	if resp.StatusCode != http.StatusOK {
		bodyBytes, _ := ioutil.ReadAll(resp.Body)
		body := string(bodyBytes)
		t.Fatalf("Expected response %v, got %v: %v", http.StatusOK, resp.StatusCode, body)
	}
}

func getPeriod(handler http.Handler, teamID, periodID string, t *testing.T) *Period {
	req := httptest.NewRequest(http.MethodGet, "/api/period/"+teamID+"/"+periodID, nil)
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Expected response %v, got %v", http.StatusOK, resp.StatusCode)
	}
	p := Period{}
	dec := json.NewDecoder(resp.Body)
	err := dec.Decode(&p)
	if err != nil {
		t.Fatalf("Could not decode response body: %v", err)
	}
	return &p
}

func TestPostPeriod(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	teamID := "myteam"
	addTeam(handler, teamID, t)
	periodJSON := `{"id":"2019q1","displayName":"2019Q1","unit":"person weeks","notesURL":"http://test","buckets":[{"displayName":"Bucket one","allocationPercentage":80,"objectives":[{"name":"Objective 1","resourceEstimate":0,"commitmentType":"Committed","assignments":[]}]}],"people":[]}`
	addPeriod(handler, teamID, periodJSON, t)

	p := getPeriod(handler, teamID, "2019q1", t)

	if p.Buckets[0].AllocationPercentage != 80 {
		t.Fatalf("Expected allocation percentage 80, found %v", p.Buckets[0].AllocationPercentage)
	}
}

func TestInvalidCommitmentType(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	teamID := "myteam"
	addTeam(handler, teamID, t)
	periodJSON := `{"id":"2019q1","displayName":"2019Q1","unit":"person weeks","notesURL":"http://test","buckets":[{"displayName":"Bucket one","allocationPercentage":80,"objectives":[{"name":"Objective 1","resourceEstimate":0,"commitmentType":"wibble","assignments":[]}]}],"people":[]}`

	resp := attemptWritePeriod(handler, teamID, periodJSON, http.MethodPost, t)

	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)

	if resp.StatusCode != http.StatusBadRequest {
		t.Fatalf("Expected status code %v, found %v: %v", http.StatusBadRequest, resp.StatusCode, body)
	}

	if !strings.Contains(body, "wibble") {
		t.Fatalf("Expected bad commitment type to appear in body, found: %v", body)
	}
}

func TestMissingCommitmentType(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	teamID := "myteam"
	addTeam(handler, teamID, t)
	periodJSON := `{"id":"2019q1","displayName":"2019Q1","unit":"person weeks","notesURL":"http://test","buckets":[{"displayName":"Bucket one","allocationPercentage":80,"objectives":[{"name":"Objective 1","resourceEstimate":0,"assignments":[]}]}],"people":[]}`
	addPeriod(handler, teamID, periodJSON, t)

	p := getPeriod(handler, teamID, "2019q1", t)

	readCommitType := p.Buckets[0].Objectives[0].CommitmentType
	if readCommitType != "" {
		t.Fatalf("Expected read objective to have empty commitment type, found %q", readCommitType)
	}
}

func TestImprove(t *testing.T) {
	server := Server{store: makeInMemStore()}
	handler := server.makeHandler()

	req := httptest.NewRequest(http.MethodGet, "/improve", nil)
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	if resp.StatusCode != http.StatusFound {
		t.Fatalf("Expected response %c, got %v", http.StatusFound, resp.StatusCode)
	}
	expectedImproveURL := "https://github.com/google/peoplemath"
	location := resp.Header.Get("Location")
	if location != expectedImproveURL {
		t.Errorf("Expected redirect to %v, found %v", expectedImproveURL, location)
	}

	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)
	if !strings.Contains(body, expectedImproveURL) {
		t.Errorf("Expected redirect URL %v in body, found %v", expectedImproveURL, body)
	}
}
<|endoftext|>


<commit_before>/*
 * conversion.go, part of gochem.
 *
 *
 * Copyright 2012 Raul Mera <rmera{at}chemDOThelsinkiDOTfi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 *
 * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry,
 * University of Helsinki, Finland.
 *
 *
 */
/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/

package chem

//This provides useful conversion factors and other constants

//Conversions
const (
	Deg2Rad = 0.0174533
	Rad2Deg = 1 / 0.0174533
	H2Kcal  = 627.509 //HArtree 2 Kcal/mol
	Kcal2H  = 1 / 627.509
	KJ2Kcal = 1 / 4.184
	Kcal2KJ = 4.184
	A2Bohr  = 1.889725989
	Bohr2A  = 1 / 1.889725989
	EV2Kcal = 23.061
	Kcal2EV = 1 / 23.061
)

//Others
const (
	CHDist = 1.098 //C(sp3)--H distance in A
)
<commit_msg>Added a couple of constants to the conversions.go file<commit_after>/*
 * conversion.go, part of gochem.
 *
 *
 * Copyright 2012 Raul Mera <rmera{at}chemDOThelsinkiDOTfi>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 *
 * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry,
 * University of Helsinki, Finland.
 *
 *
 */
/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/

package chem

//This provides useful conversion factors and other constants

//Conversions
const (
	Deg2Rad = 0.0174533
	Rad2Deg = 1 / 0.0174533
	H2Kcal  = 627.509 //HArtree 2 Kcal/mol
	Kcal2H  = 1 / 627.509
	KJ2Kcal = 1 / 4.184
	Kcal2KJ = 4.184
	A2Bohr  = 1.889725989
	Bohr2A  = 1 / 1.889725989
	EV2Kcal = 23.061
	Kcal2EV = 1 / 23.061
)

//Others
const (
	CHDist = 1.098               //C(sp3)--H distance in A
	KB     = 1.380649e-26        // Boltzmann constant kJ/K
	R      = 8.31446261815324e-3 // kJ/(K*mol)
	NA     = 6.02214076e+23
)
<|endoftext|>


<commit_before>package gorm

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"reflect"
)

type Scope struct {
	Search          *search
	Value           interface{}
	Sql             string
	SqlVars         []interface{}
	db              *DB
	indirectValue   *reflect.Value
	instanceId      string
	primaryKeyField *Field
	skipLeft        bool
	fields          map[string]*Field
	selectAttrs     *[]string
}

func (scope *Scope) IndirectValue() reflect.Value {
	if scope.indirectValue == nil {
		value := reflect.Indirect(reflect.ValueOf(scope.Value))
		if value.Kind() == reflect.Ptr {
			value = value.Elem()
		}
		scope.indirectValue = &value
	}
	return *scope.indirectValue
}

func (scope *Scope) NeedPtr() *Scope {
	reflectKind := reflect.ValueOf(scope.Value).Kind()
	if !((reflectKind == reflect.Invalid) || (reflectKind == reflect.Ptr)) {
		err := fmt.Errorf("%v %v\n", fileWithLineNum(), "using unaddressable value")
		scope.Err(err)
		fmt.Printf(err.Error())
	}
	return scope
}

// New create a new Scope without search information
func (scope *Scope) New(value interface{}) *Scope {
	return &Scope{db: scope.NewDB(), Search: &search{}, Value: value}
}

// NewDB create a new DB without search information
func (scope *Scope) NewDB() *DB {
	if scope.db != nil {
		db := scope.db.clone()
		db.search = nil
		db.Value = nil
		return db
	}
	return nil
}

func (scope *Scope) DB() *DB {
	return scope.db
}

// SqlDB return *sql.DB
func (scope *Scope) SqlDB() sqlCommon {
	return scope.db.db
}

// SkipLeft skip remaining callbacks
func (scope *Scope) SkipLeft() {
	scope.skipLeft = true
}

// Quote used to quote database column name according to database dialect
func (scope *Scope) Quote(str string) string {
	if strings.Index(str, ".") != -1 {
		newStrs := []string{}
		for _, str := range strings.Split(str, ".") {
			newStrs = append(newStrs, scope.Dialect().Quote(str))
		}
		return strings.Join(newStrs, ".")
	} else {
		return scope.Dialect().Quote(str)
	}
}

// Dialect get dialect
func (scope *Scope) Dialect() Dialect {
	return scope.db.parent.dialect
}

// Err write error
func (scope *Scope) Err(err error) error {
	if err != nil {
		scope.db.err(err)
	}
	return err
}

// Log print log message
func (scope *Scope) Log(v ...interface{}) {
	scope.db.log(v...)
}

// HasError check if there are any error
func (scope *Scope) HasError() bool {
	return scope.db.Error != nil
}

func (scope *Scope) PrimaryField() *Field {
	if primaryFields := scope.GetModelStruct().PrimaryFields; len(primaryFields) > 0 {
		if len(primaryFields) > 1 {
			if field, ok := scope.Fields()["id"]; ok {
				return field
			}
		}
		return scope.Fields()[primaryFields[0].DBName]
	}
	return nil
}

// PrimaryKey get the primary key's column name
func (scope *Scope) PrimaryKey() string {
	if field := scope.PrimaryField(); field != nil {
		return field.DBName
	}
	return ""
}

// PrimaryKeyZero check the primary key is blank or not
func (scope *Scope) PrimaryKeyZero() bool {
	field := scope.PrimaryField()
	return field == nil || field.IsBlank
}

// PrimaryKeyValue get the primary key's value
func (scope *Scope) PrimaryKeyValue() interface{} {
	if field := scope.PrimaryField(); field != nil && field.Field.IsValid() {
		return field.Field.Interface()
	}
	return 0
}

// HasColumn to check if has column
func (scope *Scope) HasColumn(column string) bool {
	for _, field := range scope.GetStructFields() {
		if field.IsNormal && (field.Name == column || field.DBName == column) {
			return true
		}
	}
	return false
}

// SetColumn to set the column's value
func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
	if field, ok := column.(*Field); ok {
		return field.Set(value)
	} else if name, ok := column.(string); ok {

		if field, ok := scope.Fields()[name]; ok {
			return field.Set(value)
		}

		dbName := ToDBName(name)
		if field, ok := scope.Fields()[dbName]; ok {
			return field.Set(value)
		}

		if field, ok := scope.FieldByName(name); ok {
			return field.Set(value)
		}
	}
	return errors.New("could not convert column to field")
}

func (scope *Scope) CallMethod(name string, checkError bool) {
	if scope.Value == nil || (checkError && scope.HasError()) {
		return
	}

	call := func(value interface{}) {
		if fm := reflect.ValueOf(value).MethodByName(name); fm.IsValid() {
			switch f := fm.Interface().(type) {
			case func():
				f()
			case func(s *Scope):
				f(scope)
			case func(s *DB):
				f(scope.NewDB())
			case func() error:
				scope.Err(f())
			case func(s *Scope) error:
				scope.Err(f(scope))
			case func(s *DB) error:
				scope.Err(f(scope.NewDB()))
			default:
				scope.Err(fmt.Errorf("unsupported function %v", name))
			}
		}
	}

	if values := scope.IndirectValue(); values.Kind() == reflect.Slice {
		for i := 0; i < values.Len(); i++ {
			call(values.Index(i).Addr().Interface())
		}
	} else {
		call(scope.Value)
	}
}

func (scope *Scope) CallMethodWithErrorCheck(name string) {
	scope.CallMethod(name, true)
}

// AddToVars add value as sql's vars, gorm will escape them
func (scope *Scope) AddToVars(value interface{}) string {
	if expr, ok := value.(*expr); ok {
		exp := expr.expr
		for _, arg := range expr.args {
			exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
		}
		return exp
	} else {
		scope.SqlVars = append(scope.SqlVars, value)
		return scope.Dialect().BinVar(len(scope.SqlVars))
	}
}

type tabler interface {
	TableName() string
}

type dbTabler interface {
	TableName(*DB) string
}

// TableName get table name
func (scope *Scope) TableName() string {
	if scope.Search != nil && len(scope.Search.tableName) > 0 {
		return scope.Search.tableName
	}

	if tabler, ok := scope.Value.(tabler); ok {
		return tabler.TableName()
	}

	if tabler, ok := scope.Value.(dbTabler); ok {
		return tabler.TableName(scope.db)
	}

	if scope.GetModelStruct().TableName != nil {
		return scope.GetModelStruct().TableName(scope.db)
	}

	scope.Err(errors.New("wrong table name"))
	return ""
}

func (scope *Scope) QuotedTableName() (name string) {
	if scope.Search != nil && len(scope.Search.tableName) > 0 {
		return scope.Quote(scope.Search.tableName)
	} else {
		return scope.Quote(scope.TableName())
	}
}

// CombinedConditionSql get combined condition sql
func (scope *Scope) CombinedConditionSql() string {
	return scope.joinsSql() + scope.whereSql() + scope.groupSql() +
		scope.havingSql() + scope.orderSql() + scope.limitSql() + scope.offsetSql()
}

func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
	for _, field := range scope.Fields() {
		if field.Name == name {
			return field, true
		}
	}
	return nil, false
}

// Raw set sql
func (scope *Scope) Raw(sql string) *Scope {
	scope.Sql = strings.Replace(sql, "$$", "?", -1)
	return scope
}

// Exec invoke sql
func (scope *Scope) Exec() *Scope {
	defer scope.Trace(NowFunc())

	if !scope.HasError() {
		if result, err := scope.SqlDB().Exec(scope.Sql, scope.SqlVars...); scope.Err(err) == nil {
			if count, err := result.RowsAffected(); err == nil {
				scope.db.RowsAffected = count
			}
		}
	}
	return scope
}

// Set set value by name
func (scope *Scope) Set(name string, value interface{}) *Scope {
	scope.db.InstantSet(name, value)
	return scope
}

// Get get value by name
func (scope *Scope) Get(name string) (interface{}, bool) {
	return scope.db.Get(name)
}

// InstanceId get InstanceId for scope
func (scope *Scope) InstanceId() string {
	if scope.instanceId == "" {
		scope.instanceId = fmt.Sprintf("%v%v", &scope, &scope.db)
	}
	return scope.instanceId
}

func (scope *Scope) InstanceSet(name string, value interface{}) *Scope {
	return scope.Set(name+scope.InstanceId(), value)
}

func (scope *Scope) InstanceGet(name string) (interface{}, bool) {
	return scope.Get(name + scope.InstanceId())
}

// Trace print sql log
func (scope *Scope) Trace(t time.Time) {
	if len(scope.Sql) > 0 {
		scope.db.slog(scope.Sql, t, scope.SqlVars...)
	}
}

// Begin start a transaction
func (scope *Scope) Begin() *Scope {
	if db, ok := scope.SqlDB().(sqlDb); ok {
		if tx, err := db.Begin(); err == nil {
			scope.db.db = interface{}(tx).(sqlCommon)
			scope.InstanceSet("gorm:started_transaction", true)
		}
	}
	return scope
}

// CommitOrRollback commit current transaction if there is no error, otherwise rollback it
func (scope *Scope) CommitOrRollback() *Scope {
	if _, ok := scope.InstanceGet("gorm:started_transaction"); ok {
		if db, ok := scope.db.db.(sqlTx); ok {
			if scope.HasError() {
				db.Rollback()
			} else {
				db.Commit()
			}
			scope.db.db = scope.db.parent.db
		}
	}
	return scope
}

func (scope *Scope) SelectAttrs() []string {
	if scope.selectAttrs == nil {
		attrs := []string{}
		for _, value := range scope.Search.selects {
			if str, ok := value.(string); ok {
				attrs = append(attrs, str)
			} else if strs, ok := value.([]string); ok {
				attrs = append(attrs, strs...)
			} else if strs, ok := value.([]interface{}); ok {
				for _, str := range strs {
					attrs = append(attrs, fmt.Sprintf("%v", str))
				}
			}
		}
		scope.selectAttrs = &attrs
	}
	return *scope.selectAttrs
}

func (scope *Scope) OmitAttrs() []string {
	return scope.Search.omits
}

func (scope *Scope) changeableDBColumn(column string) bool {
	selectAttrs := scope.SelectAttrs()
	omitAttrs := scope.OmitAttrs()

	if len(selectAttrs) > 0 {
		for _, attr := range selectAttrs {
			if column == ToDBName(attr) {
				return true
			}
		}
		return false
	}

	for _, attr := range omitAttrs {
		if column == ToDBName(attr) {
			return false
		}
	}
	return true
}

func (scope *Scope) changeableField(field *Field) bool {
	selectAttrs := scope.SelectAttrs()
	omitAttrs := scope.OmitAttrs()

	if len(selectAttrs) > 0 {
		for _, attr := range selectAttrs {
			if field.Name == attr || field.DBName == attr {
				return true
			}
		}
		return false
	}

	for _, attr := range omitAttrs {
		if field.Name == attr || field.DBName == attr {
			return false
		}
	}

	return !field.IsIgnored
}

func (scope *Scope) shouldSaveAssociations() bool {
	saveAssociations, ok := scope.Get("gorm:save_associations")
	if ok && !saveAssociations.(bool) {
		return false
	}
	return true
}
<commit_msg>Fix use SQL as table name<commit_after>package gorm

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"reflect"
)

type Scope struct {
	Search          *search
	Value           interface{}
	Sql             string
	SqlVars         []interface{}
	db              *DB
	indirectValue   *reflect.Value
	instanceId      string
	primaryKeyField *Field
	skipLeft        bool
	fields          map[string]*Field
	selectAttrs     *[]string
}

func (scope *Scope) IndirectValue() reflect.Value {
	if scope.indirectValue == nil {
		value := reflect.Indirect(reflect.ValueOf(scope.Value))
		if value.Kind() == reflect.Ptr {
			value = value.Elem()
		}
		scope.indirectValue = &value
	}
	return *scope.indirectValue
}

func (scope *Scope) NeedPtr() *Scope {
	reflectKind := reflect.ValueOf(scope.Value).Kind()
	if !((reflectKind == reflect.Invalid) || (reflectKind == reflect.Ptr)) {
		err := fmt.Errorf("%v %v\n", fileWithLineNum(), "using unaddressable value")
		scope.Err(err)
		fmt.Printf(err.Error())
	}
	return scope
}

// New create a new Scope without search information
func (scope *Scope) New(value interface{}) *Scope {
	return &Scope{db: scope.NewDB(), Search: &search{}, Value: value}
}

// NewDB create a new DB without search information
func (scope *Scope) NewDB() *DB {
	if scope.db != nil {
		db := scope.db.clone()
		db.search = nil
		db.Value = nil
		return db
	}
	return nil
}

func (scope *Scope) DB() *DB {
	return scope.db
}

// SqlDB return *sql.DB
func (scope *Scope) SqlDB() sqlCommon {
	return scope.db.db
}

// SkipLeft skip remaining callbacks
func (scope *Scope) SkipLeft() {
	scope.skipLeft = true
}

// Quote used to quote database column name according to database dialect
func (scope *Scope) Quote(str string) string {
	if strings.Index(str, ".") != -1 {
		newStrs := []string{}
		for _, str := range strings.Split(str, ".") {
			newStrs = append(newStrs, scope.Dialect().Quote(str))
		}
		return strings.Join(newStrs, ".")
	} else {
		return scope.Dialect().Quote(str)
	}
}

// Dialect get dialect
func (scope *Scope) Dialect() Dialect {
	return scope.db.parent.dialect
}

// Err write error
func (scope *Scope) Err(err error) error {
	if err != nil {
		scope.db.err(err)
	}
	return err
}

// Log print log message
func (scope *Scope) Log(v ...interface{}) {
	scope.db.log(v...)
}

// HasError check if there are any error
func (scope *Scope) HasError() bool {
	return scope.db.Error != nil
}

func (scope *Scope) PrimaryField() *Field {
	if primaryFields := scope.GetModelStruct().PrimaryFields; len(primaryFields) > 0 {
		if len(primaryFields) > 1 {
			if field, ok := scope.Fields()["id"]; ok {
				return field
			}
		}
		return scope.Fields()[primaryFields[0].DBName]
	}
	return nil
}

// PrimaryKey get the primary key's column name
func (scope *Scope) PrimaryKey() string {
	if field := scope.PrimaryField(); field != nil {
		return field.DBName
	}
	return ""
}

// PrimaryKeyZero check the primary key is blank or not
func (scope *Scope) PrimaryKeyZero() bool {
	field := scope.PrimaryField()
	return field == nil || field.IsBlank
}

// PrimaryKeyValue get the primary key's value
func (scope *Scope) PrimaryKeyValue() interface{} {
	if field := scope.PrimaryField(); field != nil && field.Field.IsValid() {
		return field.Field.Interface()
	}
	return 0
}

// HasColumn to check if has column
func (scope *Scope) HasColumn(column string) bool {
	for _, field := range scope.GetStructFields() {
		if field.IsNormal && (field.Name == column || field.DBName == column) {
			return true
		}
	}
	return false
}

// SetColumn to set the column's value
func (scope *Scope) SetColumn(column interface{}, value interface{}) error {
	if field, ok := column.(*Field); ok {
		return field.Set(value)
	} else if name, ok := column.(string); ok {

		if field, ok := scope.Fields()[name]; ok {
			return field.Set(value)
		}

		dbName := ToDBName(name)
		if field, ok := scope.Fields()[dbName]; ok {
			return field.Set(value)
		}

		if field, ok := scope.FieldByName(name); ok {
			return field.Set(value)
		}
	}
	return errors.New("could not convert column to field")
}

func (scope *Scope) CallMethod(name string, checkError bool) {
	if scope.Value == nil || (checkError && scope.HasError()) {
		return
	}

	call := func(value interface{}) {
		if fm := reflect.ValueOf(value).MethodByName(name); fm.IsValid() {
			switch f := fm.Interface().(type) {
			case func():
				f()
			case func(s *Scope):
				f(scope)
			case func(s *DB):
				f(scope.NewDB())
			case func() error:
				scope.Err(f())
			case func(s *Scope) error:
				scope.Err(f(scope))
			case func(s *DB) error:
				scope.Err(f(scope.NewDB()))
			default:
				scope.Err(fmt.Errorf("unsupported function %v", name))
			}
		}
	}

	if values := scope.IndirectValue(); values.Kind() == reflect.Slice {
		for i := 0; i < values.Len(); i++ {
			call(values.Index(i).Addr().Interface())
		}
	} else {
		call(scope.Value)
	}
}

func (scope *Scope) CallMethodWithErrorCheck(name string) {
	scope.CallMethod(name, true)
}

// AddToVars add value as sql's vars, gorm will escape them
func (scope *Scope) AddToVars(value interface{}) string {
	if expr, ok := value.(*expr); ok {
		exp := expr.expr
		for _, arg := range expr.args {
			exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
		}
		return exp
	} else {
		scope.SqlVars = append(scope.SqlVars, value)
		return scope.Dialect().BinVar(len(scope.SqlVars))
	}
}

type tabler interface {
	TableName() string
}

type dbTabler interface {
	TableName(*DB) string
}

// TableName get table name
func (scope *Scope) TableName() string {
	if scope.Search != nil && len(scope.Search.tableName) > 0 {
		return scope.Search.tableName
	}

	if tabler, ok := scope.Value.(tabler); ok {
		return tabler.TableName()
	}

	if tabler, ok := scope.Value.(dbTabler); ok {
		return tabler.TableName(scope.db)
	}

	if scope.GetModelStruct().TableName != nil {
		return scope.GetModelStruct().TableName(scope.db)
	}

	scope.Err(errors.New("wrong table name"))
	return ""
}

func (scope *Scope) QuotedTableName() (name string) {
	if scope.Search != nil && len(scope.Search.tableName) > 0 {
		if strings.Index(scope.Search.tableName, " ") != -1 {
			return scope.Search.tableName
		}
		return scope.Quote(scope.Search.tableName)
	} else {
		return scope.Quote(scope.TableName())
	}
}

// CombinedConditionSql get combined condition sql
func (scope *Scope) CombinedConditionSql() string {
	return scope.joinsSql() + scope.whereSql() + scope.groupSql() +
		scope.havingSql() + scope.orderSql() + scope.limitSql() + scope.offsetSql()
}

func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
	for _, field := range scope.Fields() {
		if field.Name == name {
			return field, true
		}
	}
	return nil, false
}

// Raw set sql
func (scope *Scope) Raw(sql string) *Scope {
	scope.Sql = strings.Replace(sql, "$$", "?", -1)
	return scope
}

// Exec invoke sql
func (scope *Scope) Exec() *Scope {
	defer scope.Trace(NowFunc())

	if !scope.HasError() {
		if result, err := scope.SqlDB().Exec(scope.Sql, scope.SqlVars...); scope.Err(err) == nil {
			if count, err := result.RowsAffected(); err == nil {
				scope.db.RowsAffected = count
			}
		}
	}
	return scope
}

// Set set value by name
func (scope *Scope) Set(name string, value interface{}) *Scope {
	scope.db.InstantSet(name, value)
	return scope
}

// Get get value by name
func (scope *Scope) Get(name string) (interface{}, bool) {
	return scope.db.Get(name)
}

// InstanceId get InstanceId for scope
func (scope *Scope) InstanceId() string {
	if scope.instanceId == "" {
		scope.instanceId = fmt.Sprintf("%v%v", &scope, &scope.db)
	}
	return scope.instanceId
}

func (scope *Scope) InstanceSet(name string, value interface{}) *Scope {
	return scope.Set(name+scope.InstanceId(), value)
}

func (scope *Scope) InstanceGet(name string) (interface{}, bool) {
	return scope.Get(name + scope.InstanceId())
}

// Trace print sql log
func (scope *Scope) Trace(t time.Time) {
	if len(scope.Sql) > 0 {
		scope.db.slog(scope.Sql, t, scope.SqlVars...)
	}
}

// Begin start a transaction
func (scope *Scope) Begin() *Scope {
	if db, ok := scope.SqlDB().(sqlDb); ok {
		if tx, err := db.Begin(); err == nil {
			scope.db.db = interface{}(tx).(sqlCommon)
			scope.InstanceSet("gorm:started_transaction", true)
		}
	}
	return scope
}

// CommitOrRollback commit current transaction if there is no error, otherwise rollback it
func (scope *Scope) CommitOrRollback() *Scope {
	if _, ok := scope.InstanceGet("gorm:started_transaction"); ok {
		if db, ok := scope.db.db.(sqlTx); ok {
			if scope.HasError() {
				db.Rollback()
			} else {
				db.Commit()
			}
			scope.db.db = scope.db.parent.db
		}
	}
	return scope
}

func (scope *Scope) SelectAttrs() []string {
	if scope.selectAttrs == nil {
		attrs := []string{}
		for _, value := range scope.Search.selects {
			if str, ok := value.(string); ok {
				attrs = append(attrs, str)
			} else if strs, ok := value.([]string); ok {
				attrs = append(attrs, strs...)
			} else if strs, ok := value.([]interface{}); ok {
				for _, str := range strs {
					attrs = append(attrs, fmt.Sprintf("%v", str))
				}
			}
		}
		scope.selectAttrs = &attrs
	}
	return *scope.selectAttrs
}

func (scope *Scope) OmitAttrs() []string {
	return scope.Search.omits
}

func (scope *Scope) changeableDBColumn(column string) bool {
	selectAttrs := scope.SelectAttrs()
	omitAttrs := scope.OmitAttrs()

	if len(selectAttrs) > 0 {
		for _, attr := range selectAttrs {
			if column == ToDBName(attr) {
				return true
			}
		}
		return false
	}

	for _, attr := range omitAttrs {
		if column == ToDBName(attr) {
			return false
		}
	}
	return true
}

func (scope *Scope) changeableField(field *Field) bool {
	selectAttrs := scope.SelectAttrs()
	omitAttrs := scope.OmitAttrs()

	if len(selectAttrs) > 0 {
		for _, attr := range selectAttrs {
			if field.Name == attr || field.DBName == attr {
				return true
			}
		}
		return false
	}

	for _, attr := range omitAttrs {
		if field.Name == attr || field.DBName == attr {
			return false
		}
	}

	return !field.IsIgnored
}

func (scope *Scope) shouldSaveAssociations() bool {
	saveAssociations, ok := scope.Get("gorm:save_associations")
	if ok && !saveAssociations.(bool) {
		return false
	}
	return true
}
<|endoftext|>


<commit_before>package jcapi

import (
	"testing"
)

const (
	testAPIKey  string = "<your-API-key-here>"
	testUrlBase string = "https://console.jumpcloud.com/api"
	authUrlBase string = "https://auth.jumpcloud.com/authenticate"
)

func MakeTestUser() (user JCUser) {
	user = JCUser{
		UserName:          "testuser",
		FirstName:         "Test",
		LastName:          "User",
		Email:             "testuser@jumpcloud.com",
		Password:          "test!@#$ADSF",
		Activated:         true,
		Sudo:              true,
		Uid:               "2244",
		Gid:               "2244",
		EnableManagedUid:  true,
		TagList:           make([]string, 0),
		ExternallyManaged: false,
	}

	return
}

func TestSystemUsersByOne(t *testing.T) {
	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newUser := MakeTestUser()

	userId, err := jcapi.AddUpdateUser(Insert, newUser)
	if err != nil {
		t.Fatalf("Could not add new user ('%s'), err='%s'", newUser.ToString(), err)
	}

	t.Logf("Returned userId=%s", userId)

	retrievedUser, err := jcapi.GetSystemUserById(userId, true)
	if err != nil {
		t.Fatalf("Could not get the system user I just added, err='%s'", err)
	}

	if userId != retrievedUser.Id {
		t.Fatalf("Got back a different user ID than expected, this shouldn't happen! Initial userId='%s' - returned object: '%s'",
			userId, retrievedUser.ToString())
	}

	retrievedUser.Email = "newtestemail@jumpcloud.com"

	// We have to do the following because of bug: https://www.pivotaltracker.com/story/show/84876992
	retrievedUser.Uid = "2244"
	retrievedUser.Gid = "2244"

	newUserId, err := jcapi.AddUpdateUser(Update, retrievedUser)
	if err != nil {
		t.Fatalf("Could not modify email on the just-added user ('%s'), err='%s'", retrievedUser.ToString(), err)
	}

	if userId != newUserId {
		t.Fatalf("The user ID of the updated user changed across updates, this should never happen!")
	}

	err = jcapi.DeleteUser(retrievedUser)
	if err != nil {
		t.Fatalf("Could not delete user ('%s'), err='%s'", retrievedUser.ToString(), err)
	}

	return
}

func TestSystemUsers(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping potentially long test in short mode")
	}

	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newUser := MakeTestUser()

	userId, err := jcapi.AddUpdateUser(Insert, newUser)
	if err != nil {
		t.Fatalf("Could not add new user ('%s'), err='%s'", newUser.ToString(), err)
	}

	t.Logf("Returned userId=%s", userId)

	allUsers, err := jcapi.GetSystemUsers(true)
	if err != nil {
		t.Fatalf("Could not get all system users, err='%s'", err)
	}

	t.Logf("GetSystemUsers() returned %d users", len(allUsers))

	var foundUser int = -1

	for i, user := range allUsers {
		if user.Id == userId {
			foundUser = i
			t.Logf("Matched user[%d]='%s'", i, user.ToString())
		}
	}

	if foundUser == -1 {
		t.Fatalf("Could not find the user ID just added '%s', foundUser=%d", userId, foundUser)
	}

	allUsers[foundUser].Email = "newtestemail@jumpcloud.com"

	// We have to do the following because of bug: https://www.pivotaltracker.com/story/show/84876992
	allUsers[foundUser].Uid = "2244"
	allUsers[foundUser].Gid = "2244"

	newUserId, err := jcapi.AddUpdateUser(Update, allUsers[foundUser])
	if err != nil {
		t.Fatalf("Could not modify email on the just-added user ('%s'), err='%s'", allUsers[foundUser].ToString(), err)
	}

	if userId != newUserId {
		t.Fatalf("The user ID of the updated user changed across updates, this should never happen!")
	}

	err = jcapi.DeleteUser(allUsers[foundUser])
	if err != nil {
		t.Fatalf("Could not delete user ('%s'), err='%s'", allUsers[foundUser].ToString(), err)
	}

	return
}

func MakeTestTag() (tag JCTag) {
	tag = JCTag{
		Name:              "Test tag #1",
		GroupName:         "testtag1",
		Systems:           make([]string, 0),
		SystemUsers:       make([]string, 0),
		Expired:           false,
		Selected:          false,
		ExternallyManaged: false,
	}

	return
}

func TestTags(t *testing.T) {
	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newTag := MakeTestTag()

	tagId, err := jcapi.AddUpdateTag(Insert, newTag)
	if err != nil {
		t.Fatalf("Could not add new tag ('%s'), err='%s'", newTag.ToString(), err)
	}

	t.Logf("Returned tagId=%d", tagId)

	allTags, err := jcapi.GetAllTags()
	if err != nil {
		t.Fatalf("Could not GetAllTags, err='%s'", err)
	}

	var foundTag int

	for i, tag := range allTags {
		t.Logf("Tag[%d]='%s'", i, tag)
		if tag.Id == tagId {
			foundTag = i
		}
	}

	allTags[foundTag].Name = "Test tag #1 with a name change"

	newTagId, err := jcapi.AddUpdateTag(Update, allTags[foundTag])
	if err != nil {
		t.Fatalf("Could not change the test tag's name, err='%s'", err)
	}

	if tagId != newTagId {
		t.Fatalf("The ID of the tag changed during an update, this shouldn't happen.")
	}

	err = jcapi.DeleteTag(allTags[foundTag])
	if err != nil {
		t.Fatalf("Could not delete the tag I just added ('%s'), err='%s'", allTags[foundTag].ToString(), err)
	}
}

func MakeIDSource() JCIDSource {

	return JCIDSource{
		Name:           "Test Name",
		Type:           "Active Directory",
		Version:        "1.0.0",
		IpAddress:      "127.0.0.1",
		LastUpdateTime: "2014-10-14 23:34:33",
		DN:             "CN=JumpCloud;CN=Users;DC=jumpcloud;DC=com",
		Active:         true,
	}
}

func TestIDSources(t *testing.T) {

	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	e := MakeIDSource()

	result, err := jcapi.AddUpdateIDSource(Insert, e)
	if err != nil {
		t.Fatalf("Could not post a new ID Source object, err='%s'", err)
	}

	t.Logf("Post to idsources API successful, result=%U", result)

	extSourceList, err := jcapi.GetAllIDSources()
	if err != nil {
		t.Fatalf("Could not list all external sources, err='%s'", err)
	}

	for idx, source := range extSourceList {
		t.Logf("Result %d: '%s'", idx, source.ToString())
	}

	eGet, exists, err := jcapi.GetIDSourceByName(e.Name)
	if err != nil {
		t.Fatalf("Could not get an external source by name '%s', err='%s'", e.Name, err)
	} else if exists && eGet.Name != e.Name {
		t.Fatalf("Received name is different ('%s') than what was sent ('%s')", eGet.Name, e.Name)
	} else if !exists {
		t.Fatalf("Could not find the record we just put in '%c'")
	}

	//
	// If there's more than one test object with this name, let's just
	// loop over and delete them until we find no more of them...
	//
	for exists, err = true, nil; exists; eGet, exists, err = jcapi.GetIDSourceByName(e.Name) {
		if err != nil {
			t.Fatalf("ERROR: getIDSourceByName() on '%s' failed, err='%s'", eGet.ToString(), err)
		}

		err = jcapi.DeleteIDSource(eGet)
		if err != nil {
			t.Fatalf("ERROR: Delete on '%s' failed, err='%s'", eGet.ToString(), err)
		}
	}
}

func checkAuth(t *testing.T, expectedResult bool, username, password, tag string) {
	authjc := NewJCAPI(testAPIKey, authUrlBase)

	userAuth, err := authjc.AuthUser(username, password, tag)
	if err != nil {
		t.Fatalf("Could not authenticate the user '%s' with password '%s' and tag '%s' err='%s'", username, password, tag, err)
	}

	if userAuth != expectedResult {
		t.Fatalf("userAuth=%t, we expected %s for user='%s', pass='%s', tag='%s'", userAuth, expectedResult, username, password, tag)
	}
}

func TestRestAuth(t *testing.T) {
	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newUser := MakeTestUser()

	userId, err := jcapi.AddUpdateUser(Insert, newUser)
	if err != nil {
		t.Fatalf("Could not add new user ('%s'), err='%s'", newUser.ToString(), err)
	}
	newUser.Id = userId
	defer jcapi.DeleteUser(newUser)

	t.Logf("Returned userId=%s", userId)

	checkAuth(t, true, newUser.UserName, newUser.Password, "")
	checkAuth(t, false, newUser.UserName, newUser.Password, "mytesttag")
	checkAuth(t, false, newUser.UserName, "a0938mbo", "")
	checkAuth(t, false, "2309vnotauser", newUser.Password, "")
	checkAuth(t, false, "", "", "")

	//
	// Now add a tag and put the user in it, and let's try all the tag checking stuff
	//
	newTag := MakeTestTag()

	newTag.SystemUsers = append(newTag.SystemUsers, userId)

	tagId, err := jcapi.AddUpdateTag(Insert, newTag)
	if err != nil {
		t.Fatalf("Could not add new tag ('%s'), err='%s'", newTag.ToString(), err)
	}
	newTag.Id = tagId
	defer jcapi.DeleteTag(newTag)

	t.Logf("Returned tagId=%d", tagId)

	checkAuth(t, true, newUser.UserName, newUser.Password, newTag.Name)
	checkAuth(t, false, newUser.UserName, newUser.Password, "not a real tag")
	checkAuth(t, true, newUser.UserName, newUser.Password, "")
}
<commit_msg>Fixed authUrlBase<commit_after>package jcapi

import (
	"testing"
)

const (
	testAPIKey  string = "<your-API-key-here>"
	testUrlBase string = "https://console.jumpcloud.com/api"
	authUrlBase string = "https://auth.jumpcloud.com"
)

func MakeTestUser() (user JCUser) {
	user = JCUser{
		UserName:          "testuser",
		FirstName:         "Test",
		LastName:          "User",
		Email:             "testuser@jumpcloud.com",
		Password:          "test!@#$ADSF",
		Activated:         true,
		Sudo:              true,
		Uid:               "2244",
		Gid:               "2244",
		EnableManagedUid:  true,
		TagList:           make([]string, 0),
		ExternallyManaged: false,
	}

	return
}

func TestSystemUsersByOne(t *testing.T) {
	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newUser := MakeTestUser()

	userId, err := jcapi.AddUpdateUser(Insert, newUser)
	if err != nil {
		t.Fatalf("Could not add new user ('%s'), err='%s'", newUser.ToString(), err)
	}

	t.Logf("Returned userId=%s", userId)

	retrievedUser, err := jcapi.GetSystemUserById(userId, true)
	if err != nil {
		t.Fatalf("Could not get the system user I just added, err='%s'", err)
	}

	if userId != retrievedUser.Id {
		t.Fatalf("Got back a different user ID than expected, this shouldn't happen! Initial userId='%s' - returned object: '%s'",
			userId, retrievedUser.ToString())
	}

	retrievedUser.Email = "newtestemail@jumpcloud.com"

	// We have to do the following because of bug: https://www.pivotaltracker.com/story/show/84876992
	retrievedUser.Uid = "2244"
	retrievedUser.Gid = "2244"

	newUserId, err := jcapi.AddUpdateUser(Update, retrievedUser)
	if err != nil {
		t.Fatalf("Could not modify email on the just-added user ('%s'), err='%s'", retrievedUser.ToString(), err)
	}

	if userId != newUserId {
		t.Fatalf("The user ID of the updated user changed across updates, this should never happen!")
	}

	err = jcapi.DeleteUser(retrievedUser)
	if err != nil {
		t.Fatalf("Could not delete user ('%s'), err='%s'", retrievedUser.ToString(), err)
	}

	return
}

func TestSystemUsers(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping potentially long test in short mode")
	}

	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newUser := MakeTestUser()

	userId, err := jcapi.AddUpdateUser(Insert, newUser)
	if err != nil {
		t.Fatalf("Could not add new user ('%s'), err='%s'", newUser.ToString(), err)
	}

	t.Logf("Returned userId=%s", userId)

	allUsers, err := jcapi.GetSystemUsers(true)
	if err != nil {
		t.Fatalf("Could not get all system users, err='%s'", err)
	}

	t.Logf("GetSystemUsers() returned %d users", len(allUsers))

	var foundUser int = -1

	for i, user := range allUsers {
		if user.Id == userId {
			foundUser = i
			t.Logf("Matched user[%d]='%s'", i, user.ToString())
		}
	}

	if foundUser == -1 {
		t.Fatalf("Could not find the user ID just added '%s', foundUser=%d", userId, foundUser)
	}

	allUsers[foundUser].Email = "newtestemail@jumpcloud.com"

	// We have to do the following because of bug: https://www.pivotaltracker.com/story/show/84876992
	allUsers[foundUser].Uid = "2244"
	allUsers[foundUser].Gid = "2244"

	newUserId, err := jcapi.AddUpdateUser(Update, allUsers[foundUser])
	if err != nil {
		t.Fatalf("Could not modify email on the just-added user ('%s'), err='%s'", allUsers[foundUser].ToString(), err)
	}

	if userId != newUserId {
		t.Fatalf("The user ID of the updated user changed across updates, this should never happen!")
	}

	err = jcapi.DeleteUser(allUsers[foundUser])
	if err != nil {
		t.Fatalf("Could not delete user ('%s'), err='%s'", allUsers[foundUser].ToString(), err)
	}

	return
}

func MakeTestTag() (tag JCTag) {
	tag = JCTag{
		Name:              "Test tag #1",
		GroupName:         "testtag1",
		Systems:           make([]string, 0),
		SystemUsers:       make([]string, 0),
		Expired:           false,
		Selected:          false,
		ExternallyManaged: false,
	}

	return
}

func TestTags(t *testing.T) {
	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newTag := MakeTestTag()

	tagId, err := jcapi.AddUpdateTag(Insert, newTag)
	if err != nil {
		t.Fatalf("Could not add new tag ('%s'), err='%s'", newTag.ToString(), err)
	}

	t.Logf("Returned tagId=%d", tagId)

	allTags, err := jcapi.GetAllTags()
	if err != nil {
		t.Fatalf("Could not GetAllTags, err='%s'", err)
	}

	var foundTag int

	for i, tag := range allTags {
		t.Logf("Tag[%d]='%s'", i, tag)
		if tag.Id == tagId {
			foundTag = i
		}
	}

	allTags[foundTag].Name = "Test tag #1 with a name change"

	newTagId, err := jcapi.AddUpdateTag(Update, allTags[foundTag])
	if err != nil {
		t.Fatalf("Could not change the test tag's name, err='%s'", err)
	}

	if tagId != newTagId {
		t.Fatalf("The ID of the tag changed during an update, this shouldn't happen.")
	}

	err = jcapi.DeleteTag(allTags[foundTag])
	if err != nil {
		t.Fatalf("Could not delete the tag I just added ('%s'), err='%s'", allTags[foundTag].ToString(), err)
	}
}

func MakeIDSource() JCIDSource {

	return JCIDSource{
		Name:           "Test Name",
		Type:           "Active Directory",
		Version:        "1.0.0",
		IpAddress:      "127.0.0.1",
		LastUpdateTime: "2014-10-14 23:34:33",
		DN:             "CN=JumpCloud;CN=Users;DC=jumpcloud;DC=com",
		Active:         true,
	}
}

func TestIDSources(t *testing.T) {

	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	e := MakeIDSource()

	result, err := jcapi.AddUpdateIDSource(Insert, e)
	if err != nil {
		t.Fatalf("Could not post a new ID Source object, err='%s'", err)
	}

	t.Logf("Post to idsources API successful, result=%U", result)

	extSourceList, err := jcapi.GetAllIDSources()
	if err != nil {
		t.Fatalf("Could not list all external sources, err='%s'", err)
	}

	for idx, source := range extSourceList {
		t.Logf("Result %d: '%s'", idx, source.ToString())
	}

	eGet, exists, err := jcapi.GetIDSourceByName(e.Name)
	if err != nil {
		t.Fatalf("Could not get an external source by name '%s', err='%s'", e.Name, err)
	} else if exists && eGet.Name != e.Name {
		t.Fatalf("Received name is different ('%s') than what was sent ('%s')", eGet.Name, e.Name)
	} else if !exists {
		t.Fatalf("Could not find the record we just put in '%c'")
	}

	//
	// If there's more than one test object with this name, let's just
	// loop over and delete them until we find no more of them...
	//
	for exists, err = true, nil; exists; eGet, exists, err = jcapi.GetIDSourceByName(e.Name) {
		if err != nil {
			t.Fatalf("ERROR: getIDSourceByName() on '%s' failed, err='%s'", eGet.ToString(), err)
		}

		err = jcapi.DeleteIDSource(eGet)
		if err != nil {
			t.Fatalf("ERROR: Delete on '%s' failed, err='%s'", eGet.ToString(), err)
		}
	}
}

func checkAuth(t *testing.T, expectedResult bool, username, password, tag string) {
	authjc := NewJCAPI(testAPIKey, authUrlBase)

	userAuth, err := authjc.AuthUser(username, password, tag)
	if err != nil {
		t.Fatalf("Could not authenticate the user '%s' with password '%s' and tag '%s' err='%s'", username, password, tag, err)
	}

	if userAuth != expectedResult {
		t.Fatalf("userAuth=%t, we expected %s for user='%s', pass='%s', tag='%s'", userAuth, expectedResult, username, password, tag)
	}
}

func TestRestAuth(t *testing.T) {
	jcapi := NewJCAPI(testAPIKey, testUrlBase)

	newUser := MakeTestUser()

	userId, err := jcapi.AddUpdateUser(Insert, newUser)
	if err != nil {
		t.Fatalf("Could not add new user ('%s'), err='%s'", newUser.ToString(), err)
	}
	newUser.Id = userId
	defer jcapi.DeleteUser(newUser)

	t.Logf("Returned userId=%s", userId)

	checkAuth(t, true, newUser.UserName, newUser.Password, "")
	checkAuth(t, false, newUser.UserName, newUser.Password, "mytesttag")
	checkAuth(t, false, newUser.UserName, "a0938mbo", "")
	checkAuth(t, false, "2309vnotauser", newUser.Password, "")
	checkAuth(t, false, "", "", "")

	//
	// Now add a tag and put the user in it, and let's try all the tag checking stuff
	//
	newTag := MakeTestTag()

	newTag.SystemUsers = append(newTag.SystemUsers, userId)

	tagId, err := jcapi.AddUpdateTag(Insert, newTag)
	if err != nil {
		t.Fatalf("Could not add new tag ('%s'), err='%s'", newTag.ToString(), err)
	}
	newTag.Id = tagId
	defer jcapi.DeleteTag(newTag)

	t.Logf("Returned tagId=%d", tagId)

	checkAuth(t, true, newUser.UserName, newUser.Password, newTag.Name)
	checkAuth(t, false, newUser.UserName, newUser.Password, "not a real tag")
	checkAuth(t, true, newUser.UserName, newUser.Password, "")
}
<|endoftext|>


<commit_before>/*

	build is comprised of two sub-packages, api and static, that are two
	halves of building a functioning webapp given a config.json.

	api builds the server binary that handles all of the game logic. It is a
	headless binary that doesn't render any UI but serves as a REST endpoint
	for the webapp.

	static accumulates all of the various client-side resources (i.e. html,
	css, js) necessary to render the server and the specific games it uses.
	The static server output is all static; that is that the files don't
	change and it's designed to be able to upload to static file hosting
	surfaces like firebase hosting. Actually organizing all of the files on
	disk in the right configuration is a pain, so the static.Build() is a huge
	help.

	Both api and static Build() methods take a directory parameter, an
	optional directory name to store ther results of their builds in. They
	will create sub directories within that folder to store their results in a
	known location. directory is optional; "" just defaults to the current
	directory.

	Typically you don't have to use these libraries directly, but instead use
	`boardgame-util build api`, `boardgame-util build static`, `boardgame-util
	clean`, and `boardgame-util serve`.\

	This build package contains only this documentation and no code. All code
	is in the api and static sub-packages. See their package doc for more
	about each one.

*/
package build
<commit_msg>Fixed lint error in boardgame-util/lib/build. Part of #552.<commit_after>/*

Package build is comprised of two sub-packages, api and static, that are two
halves of building a functioning webapp given a config.json.

api builds the server binary that handles all of the game logic. It is a
headless binary that doesn't render any UI but serves as a REST endpoint for the
webapp.

static accumulates all of the various client-side resources (i.e. html, css, js)
necessary to render the server and the specific games it uses. The static server
output is all static; that is that the files don't change and it's designed to
be able to upload to static file hosting surfaces like firebase hosting.
Actually organizing all of the files on disk in the right configuration is a
pain, so the static.Build() is a huge help.

Both api and static Build() methods take a directory parameter, an optional
directory name to store ther results of their builds in. They will create sub
directories within that folder to store their results in a known location.
directory is optional; "" just defaults to the current directory.

Typically you don't have to use these libraries directly, but instead use
`boardgame-util build api`, `boardgame-util build static`, `boardgame-util
clean`, and `boardgame-util serve`.\

This build package contains only this documentation and no code. All code is in
the api and static sub-packages. See their package doc for more about each one.

*/
package build
<|endoftext|>


<commit_before>package jsgo_test

import (
	"runtime"

	. "github.com/go-zero/jsgo"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

type CheckFunction func(JsValue) bool

var _ = Describe("JsValue", func() {
	state := NewJsState()

	It("Should return a float", func() {
		value, _ := state.DoString("182.0")
		Expect(value.Float()).To(Equal(182.0))
	})

	It("Should return an integer", func() {
		value, _ := state.DoString("42")
		Expect(value.Integer()).To(Equal(42))
	})

	It("Should return a string", func() {
		value, _ := state.DoString("'Hello World!'")
		Expect(value.String()).To(Equal("Hello World!"))
	})

	It("Should return a boolean", func() {
		value, _ := state.DoString("true")
		Expect(value.Bool()).To(BeTrue())
	})

	It("Should return a callable", func() {
		value, _ := state.DoString("new Function()")
		_, ok := value.(*JsCallable)
		Expect(ok).To(BeTrue())
	})

	It("Should return an object", func() {
		value, _ := state.DoString("new Object()")
		_, ok := value.(*JsObject)
		Expect(ok).To(BeTrue())
	})

	It("Should return an array", func() {
		value, _ := state.DoString("new Array()")
		_, ok := value.(*JsArray)
		Expect(ok).To(BeTrue())
	})

	It("Should return a regexp", func() {
		value, _ := state.DoString("new RegExp()")
		_, ok := value.(*JsRegExp)
		Expect(ok).To(BeTrue())
	})

	DescribeTable("Should identify the value type",
		func(code string, check CheckFunction) {
			value, _ := state.DoString(code)
			Expect(check(value)).To(BeTrue())
			runtime.GC() // force the unreferencing of the value
		},
		Entry("defined", "1", JsValue.IsDefined),
		Entry("undefined", "{}", JsValue.IsUndefined),
		Entry("number", "1", JsValue.IsNumber),
		Entry("string", "'hola'", JsValue.IsString),
		Entry("boolean", "true", JsValue.IsBool),
		Entry("null", "null", JsValue.IsNull),
		Entry("primitive", "false", JsValue.IsPrimitive),
		Entry("callable", "new Function()", JsValue.IsCallable),
		Entry("array", "new Array()", JsValue.IsArray),
		Entry("regexp", "new RegExp()", JsValue.IsRegExp),
		Entry("object", "new Object()", JsValue.IsObject),
	)

})
<commit_msg>better JsValue tests<commit_after>package jsgo_test

import (
	"runtime"

	. "github.com/go-zero/jsgo"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

type CheckFunction func(JsValue) bool

var _ = Describe("JsValue", func() {
	state := NewJsState()

	It("Should return a float", func() {
		value, err := state.DoString("182.0")
		Expect(err).ToNot(HaveOccurred())
		Expect(value.Float()).To(Equal(182.0))
	})

	It("Should return an integer", func() {
		value, err := state.DoString("42")
		Expect(err).ToNot(HaveOccurred())
		Expect(value.Integer()).To(Equal(42))
	})

	It("Should return a string", func() {
		value, err := state.DoString("'Hello World!'")
		Expect(err).ToNot(HaveOccurred())
		Expect(value.String()).To(Equal("Hello World!"))
	})

	It("Should return a boolean", func() {
		value, err := state.DoString("true")
		Expect(err).ToNot(HaveOccurred())
		Expect(value.Bool()).To(BeTrue())
	})

	It("Should return a callable", func() {
		value, err := state.DoString("new Function()")
		Expect(err).ToNot(HaveOccurred())
		_, ok := value.(*JsCallable)
		Expect(ok).To(BeTrue())
	})

	It("Should return an object", func() {
		value, err := state.DoString("new Object()")
		Expect(err).ToNot(HaveOccurred())
		_, ok := value.(*JsObject)
		Expect(ok).To(BeTrue())
	})

	It("Should return an array", func() {
		value, err := state.DoString("new Array()")
		Expect(err).ToNot(HaveOccurred())
		_, ok := value.(*JsArray)
		Expect(ok).To(BeTrue())
	})

	It("Should return a regexp", func() {
		value, err := state.DoString("new RegExp()")
		Expect(err).ToNot(HaveOccurred())
		_, ok := value.(*JsRegExp)
		Expect(ok).To(BeTrue())
	})

	DescribeTable("Should identify the value type",
		func(code string, check CheckFunction) {
			value, err := state.DoString(code)
			Expect(err).ToNot(HaveOccurred())
			Expect(check(value)).To(BeTrue())
			runtime.GC() // force the unreferencing of the value
		},
		Entry("defined", "1", JsValue.IsDefined),
		Entry("undefined", "{}", JsValue.IsUndefined),
		Entry("number", "1", JsValue.IsNumber),
		Entry("string", "'hola'", JsValue.IsString),
		Entry("boolean", "true", JsValue.IsBool),
		Entry("null", "null", JsValue.IsNull),
		Entry("primitive", "false", JsValue.IsPrimitive),
		Entry("callable", "new Function()", JsValue.IsCallable),
		Entry("array", "new Array()", JsValue.IsArray),
		Entry("regexp", "new RegExp()", JsValue.IsRegExp),
		Entry("object", "new Object()", JsValue.IsObject),
	)

})
<|endoftext|>


<commit_before>package dependency

import (
	"os"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestLoad(t *testing.T) {

	pwd, _ := os.Getwd()
	target := NewDependency(pwd, false)

	actual, err := target.Load()
	require.NoError(t, err)
	require.Equal(t, 3, len(actual.Dependencies))

	withBranch := actual.Dependencies[0]
	withRevision := actual.Dependencies[1]
	withIgnore := actual.Dependencies[2]

	require.Equal(t, "github.com/google/protobuf/examples", withBranch.Target)
	require.Equal(t, "master", withBranch.Branch)
	require.Equal(t, "", withBranch.Revision)

	require.Equal(t, "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb", withRevision.Target)
	require.Equal(t, "", withRevision.Branch)
	require.Equal(t, "v1.2.2", withRevision.Revision)
	require.Equal(t, "grpc-gateway/examplepb", withRevision.Path)

	require.Equal(t, "github.com/kubernetes/helm/_proto/hapi", withIgnore.Target)
	require.Equal(t, "", withIgnore.Branch)
	require.Equal(t, "v2.8.1", withIgnore.Revision)
	require.Equal(t, []string{"./release", "./rudder", "./services", "./version"}, withIgnore.Ignores)
}
<commit_msg>Fix dependency test (#33)<commit_after>package dependency

import (
	"os"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestLoad(t *testing.T) {

	pwd, _ := os.Getwd()
	target := NewDependency(pwd, false)

	actual, err := target.Load()
	require.NoError(t, err)
	require.Equal(t, 3, len(actual.Dependencies))

	withBranch := actual.Dependencies[0]
	withRevision := actual.Dependencies[1]
	withIgnore := actual.Dependencies[2]

	require.Equal(t, "github.com/protocolbuffers/protobuf/src", withBranch.Target)
	require.Equal(t, "master", withBranch.Branch)
	require.Equal(t, "", withBranch.Revision)

	require.Equal(t, "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb", withRevision.Target)
	require.Equal(t, "", withRevision.Branch)
	require.Equal(t, "v1.2.2", withRevision.Revision)
	require.Equal(t, "grpc-gateway/examplepb", withRevision.Path)

	require.Equal(t, "github.com/kubernetes/helm/_proto/hapi", withIgnore.Target)
	require.Equal(t, "", withIgnore.Branch)
	require.Equal(t, "v2.8.1", withIgnore.Revision)
	require.Equal(t, []string{"./release", "./rudder", "./services", "./version"}, withIgnore.Ignores)
}
<|endoftext|>


<commit_before>package deepcopier

import (
	"testing"
	"time"

	"github.com/guregu/null"
	"github.com/stretchr/testify/assert"
)

func TestCopyTo(t *testing.T) {
	now := time.Now()
	user := NewUser(now)
	userCopy := &UserCopy{}
	expectedCopy := NewUserCopy(now)

	err := Copy(user).WithContext(map[string]interface{}{"version": "1"}).To(userCopy)
	assert.Nil(t, err)

	assert.Equal(t, expectedCopy.Title, userCopy.Title)
	assert.Equal(t, expectedCopy.Date, userCopy.Date)
	assert.Equal(t, expectedCopy.Float32, userCopy.Float32)
	assert.Equal(t, expectedCopy.Float64, userCopy.Float64)
	assert.Equal(t, expectedCopy.Int, userCopy.Int)
	assert.Equal(t, expectedCopy.Int8, userCopy.Int8)
	assert.Equal(t, expectedCopy.Int16, userCopy.Int16)
	assert.Equal(t, expectedCopy.Int32, userCopy.Int32)
	assert.Equal(t, expectedCopy.Int64, userCopy.Int64)
	assert.Equal(t, expectedCopy.UInt, userCopy.UInt)
	assert.Equal(t, expectedCopy.UInt8, userCopy.UInt8)
	assert.Equal(t, expectedCopy.UInt16, userCopy.UInt16)
	assert.Equal(t, expectedCopy.UInt32, userCopy.UInt32)
	assert.Equal(t, expectedCopy.UInt64, userCopy.UInt64)
	assert.Equal(t, expectedCopy.StringSlice, userCopy.StringSlice)
	assert.Equal(t, expectedCopy.IntSlice, userCopy.IntSlice)
	assert.Equal(t, expectedCopy.IntMethod, userCopy.IntMethod)
	assert.Equal(t, expectedCopy.Int8Method, userCopy.Int8Method)
	assert.Equal(t, expectedCopy.Int16Method, userCopy.Int16Method)
	assert.Equal(t, expectedCopy.Int32Method, userCopy.Int32Method)
	assert.Equal(t, expectedCopy.Int64Method, userCopy.Int64Method)
	assert.Equal(t, expectedCopy.UIntMethod, userCopy.UIntMethod)
	assert.Equal(t, expectedCopy.UInt8Method, userCopy.UInt8Method)
	assert.Equal(t, expectedCopy.UInt16Method, userCopy.UInt16Method)
	assert.Equal(t, expectedCopy.UInt32Method, userCopy.UInt32Method)
	assert.Equal(t, expectedCopy.UInt64Method, userCopy.UInt64Method)
	assert.Equal(t, expectedCopy.MethodWithContext, userCopy.MethodWithContext)
	assert.Equal(t, expectedCopy.SuperMethod, userCopy.SuperMethod)
	assert.Equal(t, expectedCopy.StringSlice, userCopy.StringSlice)
	assert.Equal(t, expectedCopy.IntSlice, userCopy.IntSlice)
}

func TestCopyFrom(t *testing.T) {
	now := time.Now()
	user := &User{}
	userCopy := NewUserCopy(now)
	expected := NewUser(now)

	err := Copy(user).From(userCopy)
	assert.Nil(t, err)

	assert.Equal(t, expected.Name, user.Name)
	assert.Equal(t, expected.Date, user.Date)
	assert.Equal(t, expected.AFloat32, user.AFloat32)
	assert.Equal(t, expected.AFloat64, user.AFloat64)
	assert.Equal(t, expected.AnInt, user.AnInt)
	assert.Equal(t, expected.AnInt8, user.AnInt8)
	assert.Equal(t, expected.AnInt16, user.AnInt16)
	assert.Equal(t, expected.AnInt32, user.AnInt32)
	assert.Equal(t, expected.AnInt64, user.AnInt64)
	assert.Equal(t, expected.AnUInt, user.AnUInt)
	assert.Equal(t, expected.AnUInt8, user.AnUInt8)
	assert.Equal(t, expected.AnUInt16, user.AnUInt16)
	assert.Equal(t, expected.AnUInt32, user.AnUInt32)
	assert.Equal(t, expected.AnUInt64, user.AnUInt64)
	assert.Equal(t, expected.AStringSlice, user.AStringSlice)
	assert.Equal(t, expected.AnIntSlice, user.AnIntSlice)
}

// -----------------------------------------------------------------------------
// Fixtures
// -----------------------------------------------------------------------------

type User struct {
	Name         string
	Date         time.Time
	AFloat32     float32
	AFloat64     float64
	AnInt        int
	AnInt8       int8
	AnInt16      int16
	AnInt32      int32
	AnInt64      int64
	AnUInt       uint
	AnUInt8      uint8
	AnUInt16     uint16
	AnUInt32     uint32
	AnUInt64     uint64
	AStringSlice []string
	AnIntSlice   []int
	ANullString  null.String
}

func NewUser(now time.Time) *User {
	return &User{
		Name:         "Chuck Norris",
		Date:         now,
		AFloat32:     float32(10.0),
		AFloat64:     float64(10.0),
		AnInt:        int(10),
		AnInt8:       int8(10),
		AnInt16:      int16(10),
		AnInt32:      int32(10),
		AnInt64:      int64(10),
		AnUInt:       uint(10),
		AnUInt8:      uint8(10),
		AnUInt16:     uint16(10),
		AnUInt32:     uint32(10),
		AnUInt64:     uint64(10),
		AStringSlice: []string{"Chuck", "Norris"},
		AnIntSlice:   []int{0, 8, 15},
		ANullString:  null.StringFrom("I'm null"),
	}
}

func (u *User) Float32Method() float32 {
	return float32(10.0)
}

func (u *User) Float64Method() float64 {
	return float64(10.0)
}

func (u *User) IntMethod() int {
	return int(10)
}

func (u *User) Int8Method() int8 {
	return int8(10)
}

func (u *User) Int16Method() int16 {
	return int16(10)
}

func (u *User) Int32Method() int32 {
	return int32(10)
}

func (u *User) Int64Method() int64 {
	return int64(10)
}

func (u *User) UIntMethod() uint {
	return uint(10)
}

func (u *User) UInt8Method() uint8 {
	return uint8(10)
}

func (u *User) UInt16Method() uint16 {
	return uint16(10)
}

func (u *User) UInt32Method() uint32 {
	return uint32(10)
}

func (u *User) UInt64Method() uint64 {
	return uint64(10)
}

func (u *User) MethodWithDifferentName() string {
	return "hello"
}

func (u *User) MethodWithContext(context map[string]interface{}) string {
	return context["version"].(string)
}

type UserCopy struct {
	Date              time.Time   `json:"date"`
	Title             string      `json:"name" deepcopier:"field:Name"`
	Float32           float32     `json:"a_float32" deepcopier:"field:AFloat32"`
	Float64           float64     `json:"a_float64" deepcopier:"field:AFloat64"`
	Int               int         `json:"an_int" deepcopier:"field:AnInt"`
	Int8              int8        `json:"an_int8" deepcopier:"field:AnInt8"`
	Int16             int16       `json:"an_int16" deepcopier:"field:AnInt16"`
	Int32             int32       `json:"an_int32" deepcopier:"field:AnInt32"`
	Int64             int64       `json:"an_int64" deepcopier:"field:AnInt64"`
	UInt              uint        `json:"an_uint" deepcopier:"field:AnUInt"`
	UInt8             uint8       `json:"an_uint8" deepcopier:"field:AnUInt8"`
	UInt16            uint16      `json:"an_uint16" deepcopier:"field:AnUInt16"`
	UInt32            uint32      `json:"an_uint32" deepcopier:"field:AnUInt32"`
	UInt64            uint64      `json:"an_uint64" deepcopier:"field:AnUInt64"`
	NullString        null.String `json:"a_null_string" deepcopier:"field:ANullString"`
	StringSlice       []string    `json:"a_string_slice" deepcopier:"field:AStringSlice"`
	IntSlice          []int       `json:"an_int_slice" deepcopier:"field:AnIntSlice"`
	IntMethod         int         `json:"int_method"`
	Int8Method        int8        `json:"int8_method"`
	Int16Method       int16       `json:"int16_method"`
	Int32Method       int32       `json:"int32_method"`
	Int64Method       int64       `json:"int64_method"`
	UIntMethod        uint        `json:"uint_method"`
	UInt8Method       uint8       `json:"uint8_method"`
	UInt16Method      uint16      `json:"uint16_method"`
	UInt32Method      uint32      `json:"uint32_method"`
	UInt64Method      uint64      `json:"uint64_method"`
	MethodWithContext string      `json:"method_with_context" deepcopier:"context"`
	SuperMethod       string      `json:"super_method" deepcopier:"field:MethodWithDifferentName"`
}

func NewUserCopy(now time.Time) *UserCopy {
	return &UserCopy{
		Title:             "Chuck Norris",
		Date:              now,
		Float32:           float32(10.0),
		Float64:           float64(10.0),
		Int:               int(10),
		Int8:              int8(10),
		Int16:             int16(10),
		Int32:             int32(10),
		Int64:             int64(10),
		UInt:              uint(10),
		UInt8:             uint8(10),
		UInt16:            uint16(10),
		UInt32:            uint32(10),
		UInt64:            uint64(10),
		StringSlice:       []string{"Chuck", "Norris"},
		IntSlice:          []int{0, 8, 15},
		NullString:        null.StringFrom("I'm null"),
		IntMethod:         int(10),
		Int8Method:        int8(10),
		Int16Method:       int16(10),
		Int32Method:       int32(10),
		Int64Method:       int64(10),
		UIntMethod:        uint(10),
		UInt8Method:       uint8(10),
		UInt16Method:      uint16(10),
		UInt32Method:      uint32(10),
		UInt64Method:      uint64(10),
		MethodWithContext: "1",
		SuperMethod:       "hello",
	}
}
<commit_msg>Use assert.New() for tests.<commit_after>package deepcopier

import (
	"testing"
	"time"

	"github.com/guregu/null"
	"github.com/stretchr/testify/assert"
)

func TestCopyTo(t *testing.T) {
	is := assert.New(t)
	now := time.Now()

	user := NewUser(now)
	userCopy := &UserCopy{}
	expectedCopy := NewUserCopy(now)

	is.Nil(Copy(user).WithContext(map[string]interface{}{"version": "1"}).To(userCopy))

	is.Equal(expectedCopy.Title, userCopy.Title)
	is.Equal(expectedCopy.Date, userCopy.Date)
	is.Equal(expectedCopy.Float32, userCopy.Float32)
	is.Equal(expectedCopy.Float64, userCopy.Float64)
	is.Equal(expectedCopy.Int, userCopy.Int)
	is.Equal(expectedCopy.Int8, userCopy.Int8)
	is.Equal(expectedCopy.Int16, userCopy.Int16)
	is.Equal(expectedCopy.Int32, userCopy.Int32)
	is.Equal(expectedCopy.Int64, userCopy.Int64)
	is.Equal(expectedCopy.UInt, userCopy.UInt)
	is.Equal(expectedCopy.UInt8, userCopy.UInt8)
	is.Equal(expectedCopy.UInt16, userCopy.UInt16)
	is.Equal(expectedCopy.UInt32, userCopy.UInt32)
	is.Equal(expectedCopy.UInt64, userCopy.UInt64)
	is.Equal(expectedCopy.StringSlice, userCopy.StringSlice)
	is.Equal(expectedCopy.IntSlice, userCopy.IntSlice)
	is.Equal(expectedCopy.IntMethod, userCopy.IntMethod)
	is.Equal(expectedCopy.Int8Method, userCopy.Int8Method)
	is.Equal(expectedCopy.Int16Method, userCopy.Int16Method)
	is.Equal(expectedCopy.Int32Method, userCopy.Int32Method)
	is.Equal(expectedCopy.Int64Method, userCopy.Int64Method)
	is.Equal(expectedCopy.UIntMethod, userCopy.UIntMethod)
	is.Equal(expectedCopy.UInt8Method, userCopy.UInt8Method)
	is.Equal(expectedCopy.UInt16Method, userCopy.UInt16Method)
	is.Equal(expectedCopy.UInt32Method, userCopy.UInt32Method)
	is.Equal(expectedCopy.UInt64Method, userCopy.UInt64Method)
	is.Equal(expectedCopy.MethodWithContext, userCopy.MethodWithContext)
	is.Equal(expectedCopy.SuperMethod, userCopy.SuperMethod)
	is.Equal(expectedCopy.StringSlice, userCopy.StringSlice)
	is.Equal(expectedCopy.IntSlice, userCopy.IntSlice)
}

func TestCopyFrom(t *testing.T) {
	is := assert.New(t)
	now := time.Now()

	user := &User{}
	userCopy := NewUserCopy(now)
	expected := NewUser(now)

	is.Nil(Copy(user).From(userCopy))

	is.Equal(expected.Name, user.Name)
	is.Equal(expected.Date, user.Date)
	is.Equal(expected.AFloat32, user.AFloat32)
	is.Equal(expected.AFloat64, user.AFloat64)
	is.Equal(expected.AnInt, user.AnInt)
	is.Equal(expected.AnInt8, user.AnInt8)
	is.Equal(expected.AnInt16, user.AnInt16)
	is.Equal(expected.AnInt32, user.AnInt32)
	is.Equal(expected.AnInt64, user.AnInt64)
	is.Equal(expected.AnUInt, user.AnUInt)
	is.Equal(expected.AnUInt8, user.AnUInt8)
	is.Equal(expected.AnUInt16, user.AnUInt16)
	is.Equal(expected.AnUInt32, user.AnUInt32)
	is.Equal(expected.AnUInt64, user.AnUInt64)
	is.Equal(expected.AStringSlice, user.AStringSlice)
	is.Equal(expected.AnIntSlice, user.AnIntSlice)
}

// -----------------------------------------------------------------------------
// Fixtures
// -----------------------------------------------------------------------------

type User struct {
	Name         string
	Date         time.Time
	AFloat32     float32
	AFloat64     float64
	AnInt        int
	AnInt8       int8
	AnInt16      int16
	AnInt32      int32
	AnInt64      int64
	AnUInt       uint
	AnUInt8      uint8
	AnUInt16     uint16
	AnUInt32     uint32
	AnUInt64     uint64
	AStringSlice []string
	AnIntSlice   []int
	ANullString  null.String
}

func NewUser(now time.Time) *User {
	return &User{
		Name:         "Chuck Norris",
		Date:         now,
		AFloat32:     float32(10.0),
		AFloat64:     float64(10.0),
		AnInt:        int(10),
		AnInt8:       int8(10),
		AnInt16:      int16(10),
		AnInt32:      int32(10),
		AnInt64:      int64(10),
		AnUInt:       uint(10),
		AnUInt8:      uint8(10),
		AnUInt16:     uint16(10),
		AnUInt32:     uint32(10),
		AnUInt64:     uint64(10),
		AStringSlice: []string{"Chuck", "Norris"},
		AnIntSlice:   []int{0, 8, 15},
		ANullString:  null.StringFrom("I'm null"),
	}
}

func (u *User) Float32Method() float32 {
	return float32(10.0)
}

func (u *User) Float64Method() float64 {
	return float64(10.0)
}

func (u *User) IntMethod() int {
	return int(10)
}

func (u *User) Int8Method() int8 {
	return int8(10)
}

func (u *User) Int16Method() int16 {
	return int16(10)
}

func (u *User) Int32Method() int32 {
	return int32(10)
}

func (u *User) Int64Method() int64 {
	return int64(10)
}

func (u *User) UIntMethod() uint {
	return uint(10)
}

func (u *User) UInt8Method() uint8 {
	return uint8(10)
}

func (u *User) UInt16Method() uint16 {
	return uint16(10)
}

func (u *User) UInt32Method() uint32 {
	return uint32(10)
}

func (u *User) UInt64Method() uint64 {
	return uint64(10)
}

func (u *User) MethodWithDifferentName() string {
	return "hello"
}

func (u *User) MethodWithContext(context map[string]interface{}) string {
	return context["version"].(string)
}

type UserCopy struct {
	Date              time.Time   `json:"date"`
	Title             string      `json:"name" deepcopier:"field:Name"`
	Float32           float32     `json:"a_float32" deepcopier:"field:AFloat32"`
	Float64           float64     `json:"a_float64" deepcopier:"field:AFloat64"`
	Int               int         `json:"an_int" deepcopier:"field:AnInt"`
	Int8              int8        `json:"an_int8" deepcopier:"field:AnInt8"`
	Int16             int16       `json:"an_int16" deepcopier:"field:AnInt16"`
	Int32             int32       `json:"an_int32" deepcopier:"field:AnInt32"`
	Int64             int64       `json:"an_int64" deepcopier:"field:AnInt64"`
	UInt              uint        `json:"an_uint" deepcopier:"field:AnUInt"`
	UInt8             uint8       `json:"an_uint8" deepcopier:"field:AnUInt8"`
	UInt16            uint16      `json:"an_uint16" deepcopier:"field:AnUInt16"`
	UInt32            uint32      `json:"an_uint32" deepcopier:"field:AnUInt32"`
	UInt64            uint64      `json:"an_uint64" deepcopier:"field:AnUInt64"`
	NullString        null.String `json:"a_null_string" deepcopier:"field:ANullString"`
	StringSlice       []string    `json:"a_string_slice" deepcopier:"field:AStringSlice"`
	IntSlice          []int       `json:"an_int_slice" deepcopier:"field:AnIntSlice"`
	IntMethod         int         `json:"int_method"`
	Int8Method        int8        `json:"int8_method"`
	Int16Method       int16       `json:"int16_method"`
	Int32Method       int32       `json:"int32_method"`
	Int64Method       int64       `json:"int64_method"`
	UIntMethod        uint        `json:"uint_method"`
	UInt8Method       uint8       `json:"uint8_method"`
	UInt16Method      uint16      `json:"uint16_method"`
	UInt32Method      uint32      `json:"uint32_method"`
	UInt64Method      uint64      `json:"uint64_method"`
	MethodWithContext string      `json:"method_with_context" deepcopier:"context"`
	SuperMethod       string      `json:"super_method" deepcopier:"field:MethodWithDifferentName"`
}

func NewUserCopy(now time.Time) *UserCopy {
	return &UserCopy{
		Title:             "Chuck Norris",
		Date:              now,
		Float32:           float32(10.0),
		Float64:           float64(10.0),
		Int:               int(10),
		Int8:              int8(10),
		Int16:             int16(10),
		Int32:             int32(10),
		Int64:             int64(10),
		UInt:              uint(10),
		UInt8:             uint8(10),
		UInt16:            uint16(10),
		UInt32:            uint32(10),
		UInt64:            uint64(10),
		StringSlice:       []string{"Chuck", "Norris"},
		IntSlice:          []int{0, 8, 15},
		NullString:        null.StringFrom("I'm null"),
		IntMethod:         int(10),
		Int8Method:        int8(10),
		Int16Method:       int16(10),
		Int32Method:       int32(10),
		Int64Method:       int64(10),
		UIntMethod:        uint(10),
		UInt8Method:       uint8(10),
		UInt16Method:      uint16(10),
		UInt32Method:      uint32(10),
		UInt64Method:      uint64(10),
		MethodWithContext: "1",
		SuperMethod:       "hello",
	}
}
<|endoftext|>


<commit_before>package nbfx

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"testing"
)

func TestEncodeExample1(t *testing.T) {
	encoder := NewEncoder()
	path := "../examples/1"
	xmlBin, err := ioutil.ReadFile(path + ".xml")
	if failOn(err, "unable to open "+path+".xml", t) {
		return
	}
	expected, err := ioutil.ReadFile(path + ".bin")
	if failOn(err, "unable to open "+path+".bin", t) {
		return
	}
	actual, err := encoder.Encode(string(xmlBin))
	if err != nil {
		t.Error(err.Error())
		return
	}
	assertBinEqual(t, actual, expected)
}

func TestEncodePrefixDictionaryElementB(t *testing.T) {
	xml := "<b:Foo>"

	encoder := NewEncoderWithStrings(map[uint32]string{0x02: "Foo"})
	actual, err := encoder.Encode(xml)
	if err != nil {
		t.Error("Unexpected error: " + err.Error() + " Got: " + fmt.Sprintf("%x", actual))
		return
	}
	assertBinEqual(t, actual, []byte{0x45, 0x02})
}

func TestEncodePrefixDictionaryElementS(t *testing.T) {
	xml := "<s:Foo>"

	encoder := NewEncoderWithStrings(map[uint32]string{0x02: "Foo"})
	actual, err := encoder.Encode(xml)
	if err != nil {
		t.Error("Unexpected error: " + err.Error() + " Got: " + fmt.Sprintf("%x", actual))
		return
	}
	assertBinEqual(t, actual, []byte{0x56, 0x02})
}

func TestWriteMultiByteInt31_17(t *testing.T) {
	testWriteMultiByteInt31(t, 17, []byte{0x11})
}

func TestWriteMultiByteInt31_145(t *testing.T) {
	testWriteMultiByteInt31(t, 145, []byte{0x91, 0x01})
}

func TestWriteMultiByteInt31_5521(t *testing.T) {
	testWriteMultiByteInt31(t, 5521, []byte{0x91, 0x2B})
}

func TestWriteMultiByteInt31_16384(t *testing.T) {
	testWriteMultiByteInt31(t, 16384, []byte{0x80, 0x80, 0x01})
}

func TestWriteMultiByteInt31_2097152(t *testing.T) {
	testWriteMultiByteInt31(t, 2097152, []byte{0x80, 0x80, 0x80, 0x01})
}

func TestWriteMultiByteInt31_268435456(t *testing.T) {
	testWriteMultiByteInt31(t, 268435456, []byte{0x80, 0x80, 0x80, 0x80, 0x01})
}

func TestWriteString_abc(t *testing.T) {
	buffer := bytes.Buffer{}
	str := "abc"
	expected := []byte{0x03, 0x61, 0x62, 0x63}
	expectedLen := len(expected)
	e := &encoder{bin:&buffer}
	i, err := writeString(e, str)
	if err != nil {
		t.Error("Error: " + err.Error())
		return
	}
	if i != expectedLen {
		t.Errorf("Expected to write %d bytes but wrote %d", expected, i)
	}
	assertBinEqual(t, buffer.Bytes(), expected)
}

func testWriteMultiByteInt31(t *testing.T, num uint32, expected []byte) {
	buffer := bytes.Buffer{}
	e := &encoder{bin:&bytes.Buffer{}}
	i, err := writeMultiByteInt31(e, num)
	if err != nil {
		t.Error("Error: " + err.Error())
		return
	}
	if i != len(expected) {
		t.Errorf("Expected to write %d byte/s but wrote %d", len(expected), i)
		return
	}
	assertBinEqual(t, buffer.Bytes()[0:i], expected)
}

func assertBinEqual(t *testing.T, actual, expected []byte) {
	if len(actual) != len(expected) {
		t.Error("length of actual " + fmt.Sprint(len(actual)) + " not equal to length of expected " + fmt.Sprint(len(expected)))
	}
	for i, b := range actual {
		if b != expected[i] {
			fmt.Println("actual", actual, "expected", expected)
			t.Error(fmt.Sprintf("%x differs from expected %x at index %d", actual, expected, i))
		}
	}
}
<commit_msg>Fix testWriteMultiByteInt31<commit_after>package nbfx

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"testing"
)

func TestEncodeExample1(t *testing.T) {
	encoder := NewEncoder()
	path := "../examples/1"
	xmlBin, err := ioutil.ReadFile(path + ".xml")
	if failOn(err, "unable to open "+path+".xml", t) {
		return
	}
	expected, err := ioutil.ReadFile(path + ".bin")
	if failOn(err, "unable to open "+path+".bin", t) {
		return
	}
	actual, err := encoder.Encode(string(xmlBin))
	if err != nil {
		t.Error(err.Error())
		return
	}
	assertBinEqual(t, actual, expected)
}

func TestEncodePrefixDictionaryElementB(t *testing.T) {
	xml := "<b:Foo>"

	encoder := NewEncoderWithStrings(map[uint32]string{0x02: "Foo"})
	actual, err := encoder.Encode(xml)
	if err != nil {
		t.Error("Unexpected error: " + err.Error() + " Got: " + fmt.Sprintf("%x", actual))
		return
	}
	assertBinEqual(t, actual, []byte{0x45, 0x02})
}

func TestEncodePrefixDictionaryElementS(t *testing.T) {
	xml := "<s:Foo>"

	encoder := NewEncoderWithStrings(map[uint32]string{0x02: "Foo"})
	actual, err := encoder.Encode(xml)
	if err != nil {
		t.Error("Unexpected error: " + err.Error() + " Got: " + fmt.Sprintf("%x", actual))
		return
	}
	assertBinEqual(t, actual, []byte{0x56, 0x02})
}

func TestWriteMultiByteInt31_17(t *testing.T) {
	testWriteMultiByteInt31(t, 17, []byte{0x11})
}

func TestWriteMultiByteInt31_145(t *testing.T) {
	testWriteMultiByteInt31(t, 145, []byte{0x91, 0x01})
}

func TestWriteMultiByteInt31_5521(t *testing.T) {
	testWriteMultiByteInt31(t, 5521, []byte{0x91, 0x2B})
}

func TestWriteMultiByteInt31_16384(t *testing.T) {
	testWriteMultiByteInt31(t, 16384, []byte{0x80, 0x80, 0x01})
}

func TestWriteMultiByteInt31_2097152(t *testing.T) {
	testWriteMultiByteInt31(t, 2097152, []byte{0x80, 0x80, 0x80, 0x01})
}

func TestWriteMultiByteInt31_268435456(t *testing.T) {
	testWriteMultiByteInt31(t, 268435456, []byte{0x80, 0x80, 0x80, 0x80, 0x01})
}

func TestWriteString_abc(t *testing.T) {
	buffer := bytes.Buffer{}
	str := "abc"
	expected := []byte{0x03, 0x61, 0x62, 0x63}
	expectedLen := len(expected)
	e := &encoder{bin:&buffer}
	i, err := writeString(e, str)
	if err != nil {
		t.Error("Error: " + err.Error())
		return
	}
	if i != expectedLen {
		t.Errorf("Expected to write %d bytes but wrote %d", expected, i)
	}
	assertBinEqual(t, buffer.Bytes(), expected)
}

func testWriteMultiByteInt31(t *testing.T, num uint32, expected []byte) {
	buffer := bytes.Buffer{}
	e := &encoder{bin:&buffer}
	i, err := writeMultiByteInt31(e, num)
	if err != nil {
		t.Error("Error: " + err.Error())
		return
	}
	if i != len(expected) {
		t.Errorf("Expected to write %d byte/s but wrote %d", len(expected), i)
		return
	}
	assertBinEqual(t, buffer.Bytes()[0:i], expected)
}

func assertBinEqual(t *testing.T, actual, expected []byte) {
	if len(actual) != len(expected) {
		t.Error("length of actual " + fmt.Sprint(len(actual)) + " not equal to length of expected " + fmt.Sprint(len(expected)))
	}
	for i, b := range actual {
		if b != expected[i] {
			fmt.Println("actual", actual, "expected", expected)
			t.Error(fmt.Sprintf("%x differs from expected %x at index %d", actual, expected, i))
		}
	}
}
<|endoftext|>


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

package bytes_test

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"os"
	"sort"
)

func ExampleBuffer() {
	var b bytes.Buffer // A Buffer needs no initialization.
	b.Write([]byte("Hello "))
	fmt.Fprintf(&b, "world!")
	b.WriteTo(os.Stdout)
	// Output: Hello world!
}

func ExampleBuffer_reader() {
	// A Buffer can turn a string or a []byte into an io.Reader.
	buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
	dec := base64.NewDecoder(base64.StdEncoding, buf)
	io.Copy(os.Stdout, dec)
	// Output: Gophers rule!
}

func ExampleCompare() {
	// Interpret Compare's result by comparing it to zero.
	var a, b []byte
	if bytes.Compare(a, b) < 0 {
		// a less b
	}
	if bytes.Compare(a, b) <= 0 {
		// a less or equal b
	}
	if bytes.Compare(a, b) > 0 {
		// a greater b
	}
	if bytes.Compare(a, b) >= 0 {
		// a greater or equal b
	}

	// Prefer Equal to Compare for equality comparisons.
	if bytes.Equal(a, b) {
		// a equal b
	}
	if !bytes.Equal(a, b) {
		// a not equal b
	}
}

func ExampleCompare_search() {
	// Binary search to find a matching byte slice.
	var needle []byte
	var haystack [][]byte // Assume sorted
	i := sort.Search(len(haystack), func(i int) bool {
		// Return needle <= haystack[i].
		return bytes.Compare(needle, haystack[i]) <= 0
	})
	if i < len(haystack) && bytes.Equal(needle, haystack[i]) {
		// Found it!
	}
}
<commit_msg>bytes: Change Compare example to be consistent with sort.Search's.<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package bytes_test

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"os"
	"sort"
)

func ExampleBuffer() {
	var b bytes.Buffer // A Buffer needs no initialization.
	b.Write([]byte("Hello "))
	fmt.Fprintf(&b, "world!")
	b.WriteTo(os.Stdout)
	// Output: Hello world!
}

func ExampleBuffer_reader() {
	// A Buffer can turn a string or a []byte into an io.Reader.
	buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
	dec := base64.NewDecoder(base64.StdEncoding, buf)
	io.Copy(os.Stdout, dec)
	// Output: Gophers rule!
}

func ExampleCompare() {
	// Interpret Compare's result by comparing it to zero.
	var a, b []byte
	if bytes.Compare(a, b) < 0 {
		// a less b
	}
	if bytes.Compare(a, b) <= 0 {
		// a less or equal b
	}
	if bytes.Compare(a, b) > 0 {
		// a greater b
	}
	if bytes.Compare(a, b) >= 0 {
		// a greater or equal b
	}

	// Prefer Equal to Compare for equality comparisons.
	if bytes.Equal(a, b) {
		// a equal b
	}
	if !bytes.Equal(a, b) {
		// a not equal b
	}
}

func ExampleCompare_search() {
	// Binary search to find a matching byte slice.
	var needle []byte
	var haystack [][]byte // Assume sorted
	i := sort.Search(len(haystack), func(i int) bool {
		// Return haystack[i] >= needle.
		return bytes.Compare(haystack[i], needle) >= 0
	})
	if i < len(haystack) && bytes.Equal(haystack[i], needle) {
		// Found it!
	}
}
<|endoftext|>