<commit_before>package missions

import (
	"log"
	"gopkg.in/yaml.v2"
)

type Mission struct {
	Name string
	subMissions []Mission
	SubMissionStrings []string `yaml:"subMissions"`
}

func NewMission(data []byte) *Mission {
	m := Mission{}
	err := yaml.Unmarshal(data, &m)

	if err != nil {
		log.Fatalf("error: %v", err)
	}

	return &m
}

func (m *Mission) ToYaml() string {
	d, err := yaml.Marshal(m)

	if err != nil {
		log.Fatalf("error: %v", err)
	}

	return string(d)
}
<commit_msg>Add run methods<commit_after>package missions

import (
	"log"
	"gopkg.in/yaml.v2"
)

type MissionReport struct {
	Message string
}

type SubMission struct {
	RunType string
	Command string
	Mission Mission
}

type Mission struct {
	Name string

	SubMissions []SubMission
	parallel []SubMission
	serial []SubMission
	beforeAll []SubMission
	beforeEach []SubMission
	afterAll []SubMission
	afterEach []SubMission

	subMissionReports []MissionReport

	upstream chan MissionReport
	downstream chan MissionReport

	subUpstream chan MissionReport
	subDownstream chan MissionReport
}

func NewMission(data []byte) *Mission {
	m := Mission{}
	err := yaml.Unmarshal(data, &m)

	if err != nil {
		log.Fatalf("error: %v", err)
	}

	return &m
}

func (m *Mission) ToYaml() string {
	d, err := yaml.Marshal(m)

	if err != nil {
		log.Fatalf("error: %v", err)
	}

	return string(d)
}

func (m *Mission) RunSerially() {
	for _, subMission := range m.serial {
		subMission.Run(m)
	}
}

func (m *Mission) Run(upstream, downstream chan MissionReport) {
	if len(m.SubMissions) == 0 {
		log.Fatalf("Mission must have SubMissions")
	}

	for _, subMission := range m.SubMissions {
		switch subMission.RunType {
		case "parallel":
			m.parallel = append(m.parallel, subMission)
		default:
			m.serial = append(m.serial, subMission)
		}
	}

	for _, subMission := range m.parallel {
		go subMission.Run(m)
	}

	go m.RunSerially()

	select {
	case s := <-downstream:
		m.subMissionReports = append(m.subMissionReports, s)
	case s := <-m.upstream:
		log.Println(s)
	}
}

func (s *SubMission) Run(m *Mission) {
	s.Mission.Run(m.subUpstream, m.subDownstream)
}
<|endoftext|>


<commit_before>package model

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type (
	// Investments is a list of Investment(s).
	Investments []Investment

	// Investment models a single entity on the stock market searchable by
	// its symbol. It may have a group associated with it. It's fields is a
	// investment schema:
	//   /public/schema/investment.json
	Investment struct {
		Base
		Symbol string `json:"symbol" bson:"symbol" binding:"required"`
		Group  *Group `json:"group,omitempty" bson:",omitempty"`
		Fields bson.M `json:"fields"`
	}
	// InvestmentRepo is responsible for all actions on the database related to the
	// Investment model
	InvestmentRepo struct {
		Collection *mgo.Collection
	}

	// InvestmentRepository is an interface for something that can run basic crud
	// operations on an Investment model.
	InvestmentRepositor interface {
		CreateOne(toCreate Investment) (Investment, error)
	}
)

// NewInvestmentRepo acreates a new investment repository, sets the correct
// database collection and ensures any indexes on the collection. Returns
// the new repository.
func NewInvestmentRepo(sesh *mgo.Database) InvestmentRepo {
	idx := mgo.Index{
		Key:        []string{"symbol"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	r := InvestmentRepo{
		Collection: sesh.C("investments"),
	}
	r.Collection.EnsureIndex(idx)

	return r
}

// CreateOne will attempt to update the base time fields and then insert one
// Investment into the database by taking a Investment to be created. Returns
// the created investment.
func (r *InvestmentRepo) CreateOne(toCreate Investment) (Investment, error) {
	toCreate.Create()
	if toCreate.Group != nil {
		toCreate.Group.Create()
	}

	if toCreate.Fields == nil {
		toCreate.Fields = make(map[string]interface{})
	}

	err := r.Collection.Insert(toCreate)
	if err != nil {
		return Investment{}, err
	}

	return toCreate, nil
}
<commit_msg>Delete model from db<commit_after>package model

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type (
	// Investments is a list of Investment(s).
	Investments []Investment

	// Investment models a single entity on the stock market searchable by
	// its symbol. It may have a group associated with it. It's fields is a
	// investment schema:
	//   /public/schema/investment.json
	Investment struct {
		Base
		Symbol string `json:"symbol" bson:"symbol" binding:"required"`
		Group  *Group `json:"group,omitempty" bson:",omitempty"`
		Fields bson.M `json:"fields"`
	}
	// InvestmentRepo is responsible for all actions on the database related to the
	// Investment model
	InvestmentRepo struct {
		Collection *mgo.Collection
	}

	// InvestmentRepository is an interface for something that can run basic crud
	// operations on an Investment model.
	InvestmentRepositor interface {
		CreateOne(toCreate Investment) (Investment, error)
		DeleteOne(id bson.ObjectId) error
	}
)

// NewInvestmentRepo acreates a new investment repository, sets the correct
// database collection and ensures any indexes on the collection. Returns
// the new repository.
func NewInvestmentRepo(sesh *mgo.Database) InvestmentRepo {
	idx := mgo.Index{
		Key:        []string{"symbol"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	r := InvestmentRepo{
		Collection: sesh.C("investments"),
	}
	r.Collection.EnsureIndex(idx)

	return r
}

// CreateOne will attempt to update the base time fields and then insert one
// Investment into the database by taking a Investment to be created. Returns
// the created investment.
func (r *InvestmentRepo) CreateOne(toCreate Investment) (Investment, error) {
	toCreate.Create()
	if toCreate.Group != nil {
		toCreate.Group.Create()
	}

	if toCreate.Fields == nil {
		toCreate.Fields = make(map[string]interface{})
	}

	err := r.Collection.Insert(toCreate)
	if err != nil {
		return Investment{}, err
	}

	return toCreate, nil
}

// DeleteOne will delete an investment from the repo by ID. It will return an
// error if the document wasn't found or there was some other error condition.
func (r *InvestmentRepo) DeleteOne(id bson.ObjectId) error {
	err := r.Collection.RemoveId(id)
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package db

import "github.com/centurylinkcloud/clc-go-cli/errors"

type Create struct {
	InstanceType        string               `valid:"required" oneOf:"MySQL,MySQL_REPLICATION" json:"instanceType"`
	ExternalId          string               `valid:"required" json:"externalId"`
	MachineConfig       MachineConfig        `json:"machineConfig"`
	BackupRetentionDays int64                `valid:"required" json:"backupRetentionDays"`
	Users               []User               `json:"users"`
	DataCenter          string               `json:"location"`
	Destinations        []DestinationRequest `json:"destinations,omitempty"`
	Instances           []Instance           `json:"instances,omitempty"`
	BackupTime          BackupTime           `json:"backupTime"`
}

func (c *Create) Validate() error {
	if c.Users == nil || len(c.Users) == 0 {
		return errors.EmptyField("--users")
	}
	emptyConfig := MachineConfig{}
	if c.MachineConfig == emptyConfig {
		return errors.EmptyField("--machine-config")
	}
	return nil
}

type MachineConfig struct {
	Cpu     int64 `json:"cpu"`
	Memory  int64 `json:"memory"`
	Storage int64 `json:"storage"`
}

type User struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

type DestinationRequest struct {
	DestinationType string                `oneOf:"EMAIL,SMS" json:"destinationType"`
	Location        string                `json:"location"`
	Notifications   []NotificationRequest `json:"notifications"`
}

type NotificationRequest struct {
	NotificationType string `oneOf:"CPU_UTILIATION,MEMORY_UTILIZATION,STORAGE_UTILIZATION" json:"notificationType"`
}

type Instance struct {
	Name string `json:"name"`
}

type BackupTime struct {
	Hour   int64 `json:"hour"`
	Minute int64 `json:"minute"`
}

type CreateRes struct {
	Id                  int64
	Location            string
	InstanceType        string
	ExternalId          string
	Status              string
	BackupTime          string
	BackupRetentionDays int64
	OptionGroup         string
	ParameterGroup      string
	Users               []User
	Instances           []Instance
	Servers             []Server
	Host                string
	Port                int64
	Certificate         string
	Backups             []BackupResponse
}

type Server struct {
	Id          int64
	Alias       string
	Location    string
	Cpu         int64
	Memory      int64
	Storage     int64
	Attributes  map[string]string
	Connections int64
}

type BackupResponse struct {
	Id         int64
	FileName   string
	BackupTime int64
	Status     string
	Size       int64
}
<commit_msg>Express the machine config and backup props as pointers<commit_after>package db

import (
	"fmt"

	"github.com/centurylinkcloud/clc-go-cli/errors"
)

type Create struct {
	InstanceType        string               `valid:"required" oneOf:"MySQL,MySQL_REPLICATION" json:"instanceType"`
	ExternalId          string               `valid:"required" json:"externalId"`
	MachineConfig       MachineConfig        `json:"machineConfig"`
	BackupRetentionDays int64                `valid:"required" json:"backupRetentionDays"`
	Users               []User               `json:"users"`
	DataCenter          string               `json:"location"`
	Destinations        []DestinationRequest `json:"destinations,omitempty"`
	Instances           []Instance           `json:"instances,omitempty"`
	BackupTime          BackupTime           `json:"-"`
	BackupTimeValue     *BackupTime          `json:"backupTime,omitempty" argument:ignore`
}

func (c *Create) Validate() error {
	if c.Users == nil || len(c.Users) == 0 {
		return errors.EmptyField("--users")
	}
	emptyConfig := MachineConfig{}
	if c.MachineConfig == emptyConfig {
		return errors.EmptyField("--machine-config")
	}

	m := c.MachineConfig
	if m.Cpu == nil || m.Memory == nil || m.Storage == nil {
		return fmt.Errorf("All of the cpu, memory, and storage have to be set")
	}

	emptyBackup := BackupTime{}
	if c.BackupTime != emptyBackup {
		b := c.BackupTime
		if b.Hour == nil || b.Minute == nil {
			return fmt.Errorf("Both hour and minute have to be set")
		}
		c.BackupTimeValue = &b
	}
	return nil
}

type MachineConfig struct {
	Cpu     *int64 `json:"cpu,omitempty"`
	Memory  *int64 `json:"memory,omitempty"`
	Storage *int64 `json:"storage,omitempty"`
}

type User struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

type DestinationRequest struct {
	DestinationType string                `oneOf:"EMAIL,SMS" json:"destinationType"`
	Location        string                `json:"location"`
	Notifications   []NotificationRequest `json:"notifications"`
}

type NotificationRequest struct {
	NotificationType string `oneOf:"CPU_UTILIATION,MEMORY_UTILIZATION,STORAGE_UTILIZATION" json:"notificationType"`
}

type Instance struct {
	Name string `json:"name"`
}

type BackupTime struct {
	Hour   *int64 `json:"hour,omitempty"`
	Minute *int64 `json:"minute,omitempty"`
}

type CreateRes struct {
	Id                  int64
	Location            string
	InstanceType        string
	ExternalId          string
	Status              string
	BackupTime          string
	BackupRetentionDays int64
	OptionGroup         string
	ParameterGroup      string
	Users               []User
	Instances           []Instance
	Servers             []Server
	Host                string
	Port                int64
	Certificate         string
	Backups             []BackupResponse
}

type Server struct {
	Id          int64
	Alias       string
	Location    string
	Cpu         int64
	Memory      int64
	Storage     int64
	Attributes  map[string]string
	Connections int64
}

type BackupResponse struct {
	Id         int64
	FileName   string
	BackupTime int64
	Status     string
	Size       int64
}
<|endoftext|>


<commit_before>package models

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"github.com/taironas/gonawin/helpers"

	"appengine/aetest"
)

type testTeam struct {
	name        string
	description string
	adminId     int64
	private     bool
}

// TestCreateTeam tests that you can create a team.
//
func TestCreateTeam(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title string
		team  testTeam
	}{
		{
			title: "can create public team",
			team:  testTeam{"my team", "description", 10, false},
		},
		{
			title: "can create private team",
			team:  testTeam{"my other team", "description", 0, true},
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		var got *Team
		if got, err = CreateTeam(c, test.team.name, test.team.description, test.team.adminId, test.team.private); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
		if err = checkTeam(got, test.team); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
		if err = checkTeamInvertedIndex(t, c, got, test.team); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
	}
}

// TestDestroyTeam test that you can destroy a team.
//
func TestDestroyTeam(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title      string
		team       testTeam
		overrideId bool
		newId      int64
		err        string
	}{
		{
			title: "can destroy team",
			team:  testTeam{"my team", "description", 10, false},
		},
		{
			title:      "cannot destroy team",
			team:       testTeam{"my team other team", "description", 10, false},
			overrideId: true,
			newId:      11,
			err:        "Cannot find team with Id",
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		var got *Team
		if got, err = CreateTeam(c, test.team.name, test.team.description, test.team.adminId, test.team.private); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}

		if test.overrideId {
			got.Id = test.newId
		}

		if err = got.Destroy(c); err != nil {
			if len(test.err) == 0 {
				t.Errorf("test %v - Error: %v", i, err)
			} else if !strings.Contains(errString(err), test.err) {
				t.Errorf("test %v - Error: %v expected %v", i, err, test.err)
			}
		}

		var team *Team
		if team, err = TeamById(c, got.Id); team != nil {
			t.Errorf("test %v - Error: team found, not properly destroyed - %v", i, err)
		}

		if err = checkTeamInvertedIndex(t, c, got, test.team); err == nil {
			t.Errorf("test %v - Error: team found in database", i)
		}
	}
}

// TestFindTeams tests that you can find teams.
//
func TestFindTeams(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title string
		teams []testTeam
		query string
		want  int
	}{
		{
			title: "can find team",
			teams: []testTeam{
				testTeam{"my team", "description", 10, false},
				testTeam{"my other team", "description", 10, false},
			},
			query: "my team",
			want:  1,
		},
		{
			title: "cannot find teams",
			teams: []testTeam{
				testTeam{"real", "description", 10, false},
				testTeam{"barça", "description", 10, false},
			},
			query: "something else",
			want:  0,
		},
		{
			title: "can find multiple teams",
			teams: []testTeam{
				testTeam{"lakers", "description", 10, false},
				testTeam{"lakers", "description", 10, false},
				testTeam{"lakers", "description", 10, false},
			},
			query: "lakers",
			want:  3,
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		for _, team := range test.teams {
			if _, err = CreateTeam(c, team.name, team.description, team.adminId, team.private); err != nil {
				t.Errorf("test %v - Error: %v", i, err)
			}
		}

		var got []*Team
		if got = FindTeams(c, "Name", test.query); len(got) != test.want {
			t.Errorf("test %v - found %v teams expected %v with query %v by Name", i, test.want, len(got), test.query)
		}
	}
}

// checkTeam checks that the team passed has the same fields as the testTeam object.
//
func checkTeam(got *Team, want testTeam) error {
	var s string
	if got.Name != want.name {
		s = fmt.Sprintf("want name == %s, got %s", want.name, got.Name)
	} else if got.Description != want.description {
		s = fmt.Sprintf("want Description == %s, got %s", want.description, got.Description)
	} else if got.AdminIds[0] != want.adminId {
		s = fmt.Sprintf("want AdminId == %s, got %s", want.adminId, got.AdminIds[0])
	} else if got.Private != want.private {
		s = fmt.Sprintf("want Private == %s, got %s", want.private, got.Private)
	} else {
		return nil
	}
	return errors.New(s)
}

// checkTeamInvertedIndex checks that the team is present in the datastore when
// performing a search.
//
func checkTeamInvertedIndex(t *testing.T, c aetest.Context, got *Team, want testTeam) error {

	var ids []int64
	var err error
	words := helpers.SetOfStrings(want.name)
	if ids, err = GetTeamInvertedIndexes(c, words); err != nil {
		return errors.New(fmt.Sprintf("failed calling GetTeamInvertedIndexes %v", err))
	}
	for _, id := range ids {
		if id == got.Id {
			return nil
		}
	}

	return errors.New("team not found")
}

// errString returns the string representation of an error.
func errString(err error) string {
	if err != nil {
		return err.Error()
	}
	return ""
}
<commit_msg>first draft of test for TestTeamById<commit_after>package models

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"github.com/taironas/gonawin/helpers"

	"appengine/aetest"
)

type testTeam struct {
	name        string
	description string
	adminId     int64
	private     bool
}

// TestCreateTeam tests that you can create a team.
//
func TestCreateTeam(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title string
		team  testTeam
	}{
		{
			title: "can create public team",
			team:  testTeam{"my team", "description", 10, false},
		},
		{
			title: "can create private team",
			team:  testTeam{"my other team", "description", 0, true},
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		var got *Team
		if got, err = CreateTeam(c, test.team.name, test.team.description, test.team.adminId, test.team.private); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
		if err = checkTeam(got, test.team); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
		if err = checkTeamInvertedIndex(t, c, got, test.team); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
	}
}

// TestDestroyTeam test that you can destroy a team.
//
func TestDestroyTeam(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title      string
		team       testTeam
		overrideId bool
		newId      int64
		err        string
	}{
		{
			title: "can destroy team",
			team:  testTeam{"my team", "description", 10, false},
		},
		{
			title:      "cannot destroy team",
			team:       testTeam{"my team other team", "description", 10, false},
			overrideId: true,
			newId:      11,
			err:        "Cannot find team with Id",
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		var got *Team
		if got, err = CreateTeam(c, test.team.name, test.team.description, test.team.adminId, test.team.private); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}

		if test.overrideId {
			got.Id = test.newId
		}

		if err = got.Destroy(c); err != nil {
			if len(test.err) == 0 {
				t.Errorf("test %v - Error: %v", i, err)
			} else if !strings.Contains(errString(err), test.err) {
				t.Errorf("test %v - Error: %v expected %v", i, err, test.err)
			}
		}

		var team *Team
		if team, err = TeamById(c, got.Id); team != nil {
			t.Errorf("test %v - Error: team found, not properly destroyed - %v", i, err)
		}

		if err = checkTeamInvertedIndex(t, c, got, test.team); err == nil {
			t.Errorf("test %v - Error: team found in database", i)
		}
	}
}

// TestFindTeams tests that you can find teams.
//
func TestFindTeams(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title string
		teams []testTeam
		query string
		want  int
	}{
		{
			title: "can find team",
			teams: []testTeam{
				testTeam{"my team", "description", 10, false},
				testTeam{"my other team", "description", 10, false},
			},
			query: "my team",
			want:  1,
		},
		{
			title: "cannot find teams",
			teams: []testTeam{
				testTeam{"real", "description", 10, false},
				testTeam{"barça", "description", 10, false},
			},
			query: "something else",
			want:  0,
		},
		{
			title: "can find multiple teams",
			teams: []testTeam{
				testTeam{"lakers", "description", 10, false},
				testTeam{"lakers", "description", 10, false},
				testTeam{"lakers", "description", 10, false},
			},
			query: "lakers",
			want:  3,
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		for _, team := range test.teams {
			if _, err = CreateTeam(c, team.name, team.description, team.adminId, team.private); err != nil {
				t.Errorf("test %v - Error: %v", i, err)
			}
		}

		var got []*Team
		if got = FindTeams(c, "Name", test.query); len(got) != test.want {
			t.Errorf("test %v - found %v teams expected %v with query %v by Name", i, test.want, len(got), test.query)
		}
	}
}

// TestTeamById tests TeamById function.
//
func TestTeamById(t *testing.T) {
	var c aetest.Context
	var err error
	options := aetest.Options{StronglyConsistentDatastore: true}

	if c, err = aetest.NewContext(&options); err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	tests := []struct {
		title string
		team  testTeam
	}{
		{
			title: "can get team by Id",
			team:  testTeam{"my team", "description", 10, false},
		},
	}

	for i, test := range tests {
		t.Log(test.title)
		var team *Team
		if team, err = CreateTeam(c, test.team.name, test.team.description, test.team.adminId, test.team.private); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}

		var got *Team
		if got, err = TeamById(c, team.Id); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}
		if err = checkTeam(got, test.team); err != nil {
			t.Errorf("test %v - Error: %v", i, err)
		}

	}
}

// checkTeam checks that the team passed has the same fields as the testTeam object.
//
func checkTeam(got *Team, want testTeam) error {
	var s string
	if got.Name != want.name {
		s = fmt.Sprintf("want name == %s, got %s", want.name, got.Name)
	} else if got.Description != want.description {
		s = fmt.Sprintf("want Description == %s, got %s", want.description, got.Description)
	} else if got.AdminIds[0] != want.adminId {
		s = fmt.Sprintf("want AdminId == %s, got %s", want.adminId, got.AdminIds[0])
	} else if got.Private != want.private {
		s = fmt.Sprintf("want Private == %s, got %s", want.private, got.Private)
	} else {
		return nil
	}
	return errors.New(s)
}

// checkTeamInvertedIndex checks that the team is present in the datastore when
// performing a search.
//
func checkTeamInvertedIndex(t *testing.T, c aetest.Context, got *Team, want testTeam) error {

	var ids []int64
	var err error
	words := helpers.SetOfStrings(want.name)
	if ids, err = GetTeamInvertedIndexes(c, words); err != nil {
		return errors.New(fmt.Sprintf("failed calling GetTeamInvertedIndexes %v", err))
	}
	for _, id := range ids {
		if id == got.Id {
			return nil
		}
	}

	return errors.New("team not found")
}

// errString returns the string representation of an error.
func errString(err error) string {
	if err != nil {
		return err.Error()
	}
	return ""
}
<|endoftext|>


<commit_before>package user

import (
	"time"

	ci "github.com/jim3mar/tidy/models/checkin"
	"gopkg.in/mgo.v2/bson"
)

type User struct {
	ID          bson.ObjectId `bson:"_id" json:"uid"`
	UserName    string        `bson:"user_name" json:"user_name"`
	Password    string        `bson:"password" json:"-"`
	EMail       string        `bson:"email" json:"email"`
	CreateAt    time.Time     `bson:"create_at" json:"-"`
	Timestamp   int64         `bson:"timestamp" json:"-"`
	Portrait    string        `bson:"portrait" json:"portrait"`
	Continuous  int           `bson:"continuous" json:"continuous"`
	LastCheckIn interface{}   `bson:"last_checkin" json:"last_checkin"`
	Setting     Setting       `bson:"setting" json:"setting"`
}

func (u *User) CanCheckIn() bool {
	if u.LastCheckIn == nil {
		return true
	}
	//log.Printf("Last checkin status: %s, current time: %s", u.LastCheckIn, time.Now())
	ciData := new(ci.CheckIn)
	if checkin, ok := u.LastCheckIn.(bson.M); ok {
		if bson2Struct(&checkin, ciData) {
			now := time.Now()
			if ciData.CreateYear == now.Year() &&
				ciData.CreateMonth == int(now.Month()) &&
				ciData.CreateDay == now.Day() {
				return false
			}
		}
	}
	return true
}

func (u *User) CalcContinuous() int {
	if u.LastCheckIn == nil {
		return 1
	}
	ciData := new(ci.CheckIn)
	if checkin, ok := u.LastCheckIn.(bson.M); ok {
		if bson2Struct(&checkin, ciData) {
			now := time.Now()
			if ciData.CreateYear == now.Year() &&
				ciData.CreateAt.YearDay()+1 == now.YearDay() {
				return u.Continuous + 1
			}
		}
	}
	return 1
}

func bson2Struct(bs *bson.M, st interface{}) bool {
	if cb, err := bson.Marshal(bs); err == nil {
		if err = bson.Unmarshal(cb, st); err == nil {
			return true
		}
	}
	return false
}
<commit_msg>backup<commit_after>package user

import (
	"time"

	ci "github.com/jim3mar/tidy/models/checkin"
	"gopkg.in/mgo.v2/bson"
)

type User struct {
	ID          bson.ObjectId `bson:"_id" json:"uid"`
	UserName    string        `bson:"user_name" json:"user_name"`
	Password    string        `bson:"password" json:"-"`
	EMail       string        `bson:"email" json:"email"`
	CreateAt    time.Time     `bson:"create_at" json:"-"`
	Timestamp   int64         `bson:"timestamp" json:"-"`
	Portrait    string        `bson:"portrait" json:"portrait"`
	Continuous  int           `bson:"continuous" json:"continuous"`
	LastCheckIn interface{}   `bson:"last_checkin" json:"last_checkin"`
	Setting     Setting       `bson:"setting" json:"setting"`
}

func (u *User) CanCheckIn() bool {
	if u.LastCheckIn == nil {
		return true
	}
	ciData := new(ci.CheckIn)
	if checkin, ok := u.LastCheckIn.(bson.M); ok {
		if bson2Struct(&checkin, ciData) {
			now := time.Now()
			if ciData.CreateYear == now.Year() &&
				ciData.CreateMonth == int(now.Month()) &&
				ciData.CreateDay == now.Day() {
				return false
			}
		}
	}
	return true
}

// TBD
func (u *User) CheckInStatus() (can bool, cont int) {
	if u.LastCheckIn == nil {
		can = true
		cont = 1
		return
	}
	//log.Printf("Last checkin status: %s, current time: %s", u.LastCheckIn, time.Now())
	ciData := new(ci.CheckIn)
	if checkin, ok := u.LastCheckIn.(bson.M); ok {
		if bson2Struct(&checkin, ciData) {
			now := time.Now()
			if ciData.CreateYear == now.Year() &&
				ciData.CreateAt.YearDay()+1 == now.YearDay() {
				cont = u.Continuous + 1
				can = true
				return
			} else if ciData.CreateYear == now.Year() &&
				ciData.CreateAt.YearDay() == now.YearDay() {
				cont = 1
				can = false
				return
			}
		}
	}
	can = true
	cont = 1
	return
}

func (u *User) CalcContinuous() int {
	if u.LastCheckIn == nil {
		return 1
	}
	ciData := new(ci.CheckIn)
	if checkin, ok := u.LastCheckIn.(bson.M); ok {
		if bson2Struct(&checkin, ciData) {
			now := time.Now()
			if ciData.CreateYear == now.Year() &&
				ciData.CreateAt.YearDay()+1 == now.YearDay() {
				return u.Continuous + 1
			}
		}
	}
	return 1
}

func bson2Struct(bs *bson.M, st interface{}) bool {
	if cb, err := bson.Marshal(bs); err == nil {
		if err = bson.Unmarshal(cb, st); err == nil {
			return true
		}
	}
	return false
}
<|endoftext|>


<commit_before>package core

import (
	"database/sql"
	"errors"

	_ "github.com/go-sql-driver/mysql"

	"../utils"
)

/*
	Container info
*/
type Container struct {
	ID         int
	CID        string
	ProbeID    int
	Hostname   string
	Image      string
	IPAddress  string
	MacAddress string
}

/*
	Container's stats
*/
type Stat struct {
	ContainerID int
	Time        int64
	SizeRootFs  uint64
	SizeRw      uint64
	SizeMemory  uint64
	Running     bool
}

/*
	SQL Variables
*/
var (
	// DB
	DB       *sql.DB
	ProbesID map[string]int

	// Prepared queries
	GetProbeIDStmt             *sql.Stmt
	InsertProbeStmt            *sql.Stmt
	InsertContainerStmt        *sql.Stmt
	DeleteContainerStmt        *sql.Stmt
	InsertStatStmt             *sql.Stmt
	DeleteStatStmt             *sql.Stmt
	GetContainerByCIDStmt      *sql.Stmt
	GetStatsByContainerIdStmt  *sql.Stmt
	GetStatsByContainerCIDStmt *sql.Stmt
)

func InitSQL() {
	var err error // Error handling

	// Connect DB
	sqlc := DGConfig.DockerGuard.SQLServer // SQL Config
	DB, err = sql.Open("mysql", sqlc.User+":"+sqlc.Pass+"@tcp("+sqlc.IP+":"+utils.I2S(sqlc.Port)+")/"+sqlc.DB)
	if err != nil {
		l.Critical(err)
	}
	err = DB.Ping()
	if err != nil {
		l.Critical(err)
	}
	l.Verbose("Connected to SQL database")

	// Prepare DB queries
	GetProbeIDStmt, err = DB.Prepare("SELECT id FROM probes WHERE name=?")
	if err != nil {
		l.Critical("Can't create InsertContainerStmt:", err)
	}
	InsertProbeStmt, err = DB.Prepare("INSERT INTO probes VALUES (DEFAULT,?)")
	if err != nil {
		l.Critical("Can't create InsertContainerStmt:", err)
	}
	InsertContainerStmt, err = DB.Prepare("INSERT INTO containers VALUES (DEFAULT,?,?,?,?,?,?)")
	if err != nil {
		l.Critical("Can't create InsertContainerStmt:", err)
	}
	DeleteContainerStmt, err = DB.Prepare("DELETE FROM containers WHERE containerid=?")
	if err != nil {
		l.Critical("Can't create DeleteContainerStmt:", err)
	}
	InsertStatStmt, err = DB.Prepare("INSERT INTO stats VALUES (?,?,?,?,?,?)")
	if err != nil {
		l.Critical("Can't create InsertStatStmt:", err)
	}
	DeleteStatStmt, err = DB.Prepare("DELETE FROM stats WHERE containerid=? AND time=?")
	if err != nil {
		l.Critical("Can't create DeleteStatStmt:", err)
	}
	GetContainerByCIDStmt, err = DB.Prepare("SELECT * FROM containers WHERE containerid=?")
	if err != nil {
		l.Critical("Can't create GetContainerByIdStmt:", err)
	}
	GetStatsByContainerIdStmt, err = DB.Prepare("SELECT * FROM containers WHERE id=?")
	if err != nil {
		l.Critical("Can't create GetStatsByContainerIdStmt:", err)
	}
	GetStatsByContainerCIDStmt, err = DB.Prepare("SELECT * FROM containers WHERE containerid=?")
	if err != nil {
		l.Critical("Can't create GetStatsByContainerCIDStmt:", err)
	}

	// Get probes ID
	ProbesID = make(map[string]int)
	for _, probe := range DGConfig.Probes {
		id, err := GetProbeID(probe.Name)
		if err != nil {
			l.Critical("Error GetProbeID ("+probe.Name+"):", err)
		}
		ProbesID[probe.Name] = id
	}
}

/*
	Get a probe ID from sql server
	If does not exist: create it and return the probe ID
*/
func GetProbeID(name string) (int, error) {
	var id int64  // Probe ID to return
	var err error // Error handling

	err = GetProbeIDStmt.QueryRow(name).Scan(&id)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			result, err := InsertProbeStmt.Exec(name)
			if err != nil {
				l.Error("GetProbeID:", err)
				return 0, err
			}
			id, err = result.LastInsertId()
			if err != nil {
				l.Error("GetProbeID:", err)
				return 0, err
			}
		} else {
			l.Error("GetProbeID:", err)
			return 0, err
		}
	}

	return int(id), nil
}

/*
	Insert a container
*/
func (c *Container) Insert() (int64, error) {
	var err error         // Error handling
	var result sql.Result // SQL result

	result, err = InsertContainerStmt.Exec(c.CID, c.ProbeID, c.Hostname, c.Image, c.IPAddress, c.MacAddress)

	if err == nil {
		id, err := result.LastInsertId()
		if err != nil {
			return 0, err
		} else {
			return id, nil
		}
	}

	return 0, err
}

/*
	Delete a container
*/
func (c *Container) Delete() error {
	var err error // Error handling

	_, err = DeleteContainerStmt.Exec(c.CID)

	return err
}

/*
	Get containers by $field
*/
func GetContainersBy(field string, value interface{}) ([]Container, error) {
	var containers []Container // Containers to return
	var rows *sql.Rows         // SQL Rows
	var err error              // Error handling

	// Protection against SQL injection
	var fieldExists bool = false
	for _, i := range []string{"id", "containerid", "probeid", "hostname", "image", "ip", "mac"} {
		if field == i {
			fieldExists = true
		}
	}
	if !fieldExists {
		l.Error("GetContainersBy: Field (" + field + ") does not exist.")
		return containers, errors.New("GetContainersBy: Field (" + field + ") does not exist.")
	}

	// Get containers
	rows, err = DB.Query("SELECT * FROM containers WHERE "+field+"=?", value)
	if err != nil {
		l.Error("GetContainersBy: Can't get rows:", err)
		return containers, err
	}
	defer rows.Close()
	for rows.Next() {
		var tmpContainer Container

		if err = rows.Scan(&tmpContainer.ID,
			&tmpContainer.CID,
			&tmpContainer.ProbeID,
			&tmpContainer.Hostname,
			&tmpContainer.Image,
			&tmpContainer.IPAddress,
			&tmpContainer.MacAddress); err != nil {
			l.Error("GetContainersBy: Can't scan row:", err)
			return containers, err
		}

		containers = append(containers, tmpContainer)
	}
	if err = rows.Err(); err != nil {
		l.Error("GetContainersBy: Rows error:", err)
		return containers, err
	}

	return containers, nil
}

/*
	Get a container by id
*/
func GetContainerByID(id int) (Container, error) {
	var container Container // Container to return
	var err error           // Error handling

	err = GetContainerByCIDStmt.QueryRow(id).Scan(&container.ID, &container.CID, &container.ProbeID, &container.Hostname, &container.Image, &container.IPAddress, &container.MacAddress)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			return container, err
		} else {
			l.Error("GetContainerByID:", err)
			return container, err
		}
	}

	return container, nil
}

/*
	Get a container by cid
*/
func GetContainerByCID(cid string) (Container, error) {
	var container Container // Container to return
	var err error           // Error handling

	err = GetContainerByCIDStmt.QueryRow(cid).Scan(&container.ID, &container.CID, &container.ProbeID, &container.Hostname, &container.Image, &container.IPAddress, &container.MacAddress)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			return container, err
		} else {
			l.Error("GetContainerByCID:", err)
			return container, err
		}
	}

	return container, nil
}

/*
	Insert a stat
*/
func (s *Stat) Insert() error {
	var err error // Error handling

	if s.ContainerID == 0 {
		panic("")
	}

	_, err = InsertStatStmt.Exec(s.ContainerID, s.Time, s.SizeRootFs, s.SizeRw, s.SizeMemory, s.Running)

	return err
}

/*
	Delete a stat
*/
func (s *Stat) Delete() error {
	var err error // Error handling

	_, err = DeleteStatStmt.Exec(s.ContainerID, s.Time)

	return err
}

/*
	Get stats by container id
*/
func GetStatsByContainerID(containerID string) ([]Stat, error) {
	var stats []Stat   // List of stats to return
	var err error      // Erro handling
	var tmpStat Stat   // Temporary stat
	var rows *sql.Rows // Temporary sql rows

	rows, err = GetStatsByContainerIdStmt.Query(containerID)
	if err != nil {
		l.Error("GetStatsByContainerID:", err)
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		err = rows.Scan(&tmpStat.ContainerID, &tmpStat.Time, &tmpStat.SizeRootFs, &tmpStat.SizeRw, &tmpStat.SizeMemory, &tmpStat.Running)
		if err != nil {
			l.Error("GetStatsByContainerID:", err)
			return nil, err
		}
		stats = append(stats, tmpStat)
	}
	err = rows.Err()
	if err != nil {
		l.Error("GetStatsByContainerID:", err)
		return nil, err
	}

	return stats, nil
}
<commit_msg>Fix time insert<commit_after>package core

import (
	"database/sql"
	"errors"
	"time"

	_ "github.com/go-sql-driver/mysql"

	"../utils"
)

/*
	Container info
*/
type Container struct {
	ID         int
	CID        string
	ProbeID    int
	Hostname   string
	Image      string
	IPAddress  string
	MacAddress string
}

/*
	Container's stats
*/
type Stat struct {
	ContainerID int
	Time        int64
	SizeRootFs  uint64
	SizeRw      uint64
	SizeMemory  uint64
	Running     bool
}

/*
	SQL Variables
*/
var (
	// DB
	DB       *sql.DB
	ProbesID map[string]int

	// Prepared queries
	GetProbeIDStmt             *sql.Stmt
	InsertProbeStmt            *sql.Stmt
	InsertContainerStmt        *sql.Stmt
	DeleteContainerStmt        *sql.Stmt
	InsertStatStmt             *sql.Stmt
	DeleteStatStmt             *sql.Stmt
	GetContainerByCIDStmt      *sql.Stmt
	GetStatsByContainerIdStmt  *sql.Stmt
	GetStatsByContainerCIDStmt *sql.Stmt
)

func InitSQL() {
	var err error // Error handling

	// Connect DB
	sqlc := DGConfig.DockerGuard.SQLServer // SQL Config
	DB, err = sql.Open("mysql", sqlc.User+":"+sqlc.Pass+"@tcp("+sqlc.IP+":"+utils.I2S(sqlc.Port)+")/"+sqlc.DB)
	if err != nil {
		l.Critical(err)
	}
	err = DB.Ping()
	if err != nil {
		l.Critical(err)
	}
	l.Verbose("Connected to SQL database")

	// Prepare DB queries
	GetProbeIDStmt, err = DB.Prepare("SELECT id FROM probes WHERE name=?")
	if err != nil {
		l.Critical("Can't create InsertContainerStmt:", err)
	}
	InsertProbeStmt, err = DB.Prepare("INSERT INTO probes VALUES (DEFAULT,?)")
	if err != nil {
		l.Critical("Can't create InsertContainerStmt:", err)
	}
	InsertContainerStmt, err = DB.Prepare("INSERT INTO containers VALUES (DEFAULT,?,?,?,?,?,?)")
	if err != nil {
		l.Critical("Can't create InsertContainerStmt:", err)
	}
	DeleteContainerStmt, err = DB.Prepare("DELETE FROM containers WHERE containerid=?")
	if err != nil {
		l.Critical("Can't create DeleteContainerStmt:", err)
	}
	InsertStatStmt, err = DB.Prepare("INSERT INTO stats VALUES (?,?,?,?,?,?)")
	if err != nil {
		l.Critical("Can't create InsertStatStmt:", err)
	}
	DeleteStatStmt, err = DB.Prepare("DELETE FROM stats WHERE containerid=? AND time=?")
	if err != nil {
		l.Critical("Can't create DeleteStatStmt:", err)
	}
	GetContainerByCIDStmt, err = DB.Prepare("SELECT * FROM containers WHERE containerid=?")
	if err != nil {
		l.Critical("Can't create GetContainerByIdStmt:", err)
	}
	GetStatsByContainerIdStmt, err = DB.Prepare("SELECT * FROM containers WHERE id=?")
	if err != nil {
		l.Critical("Can't create GetStatsByContainerIdStmt:", err)
	}
	GetStatsByContainerCIDStmt, err = DB.Prepare("SELECT * FROM containers WHERE containerid=?")
	if err != nil {
		l.Critical("Can't create GetStatsByContainerCIDStmt:", err)
	}

	// Get probes ID
	ProbesID = make(map[string]int)
	for _, probe := range DGConfig.Probes {
		id, err := GetProbeID(probe.Name)
		if err != nil {
			l.Critical("Error GetProbeID ("+probe.Name+"):", err)
		}
		ProbesID[probe.Name] = id
	}
}

/*
	Get a probe ID from sql server
	If does not exist: create it and return the probe ID
*/
func GetProbeID(name string) (int, error) {
	var id int64  // Probe ID to return
	var err error // Error handling

	err = GetProbeIDStmt.QueryRow(name).Scan(&id)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			result, err := InsertProbeStmt.Exec(name)
			if err != nil {
				l.Error("GetProbeID:", err)
				return 0, err
			}
			id, err = result.LastInsertId()
			if err != nil {
				l.Error("GetProbeID:", err)
				return 0, err
			}
		} else {
			l.Error("GetProbeID:", err)
			return 0, err
		}
	}

	return int(id), nil
}

/*
	Insert a container
*/
func (c *Container) Insert() (int64, error) {
	var err error         // Error handling
	var result sql.Result // SQL result

	result, err = InsertContainerStmt.Exec(c.CID, c.ProbeID, c.Hostname, c.Image, c.IPAddress, c.MacAddress)

	if err == nil {
		id, err := result.LastInsertId()
		if err != nil {
			return 0, err
		} else {
			return id, nil
		}
	}

	return 0, err
}

/*
	Delete a container
*/
func (c *Container) Delete() error {
	var err error // Error handling

	_, err = DeleteContainerStmt.Exec(c.CID)

	return err
}

/*
	Get containers by $field
*/
func GetContainersBy(field string, value interface{}) ([]Container, error) {
	var containers []Container // Containers to return
	var rows *sql.Rows         // SQL Rows
	var err error              // Error handling

	// Protection against SQL injection
	var fieldExists bool = false
	for _, i := range []string{"id", "containerid", "probeid", "hostname", "image", "ip", "mac"} {
		if field == i {
			fieldExists = true
		}
	}
	if !fieldExists {
		l.Error("GetContainersBy: Field (" + field + ") does not exist.")
		return containers, errors.New("GetContainersBy: Field (" + field + ") does not exist.")
	}

	// Get containers
	rows, err = DB.Query("SELECT * FROM containers WHERE "+field+"=?", value)
	if err != nil {
		l.Error("GetContainersBy: Can't get rows:", err)
		return containers, err
	}
	defer rows.Close()
	for rows.Next() {
		var tmpContainer Container

		if err = rows.Scan(&tmpContainer.ID,
			&tmpContainer.CID,
			&tmpContainer.ProbeID,
			&tmpContainer.Hostname,
			&tmpContainer.Image,
			&tmpContainer.IPAddress,
			&tmpContainer.MacAddress); err != nil {
			l.Error("GetContainersBy: Can't scan row:", err)
			return containers, err
		}

		containers = append(containers, tmpContainer)
	}
	if err = rows.Err(); err != nil {
		l.Error("GetContainersBy: Rows error:", err)
		return containers, err
	}

	return containers, nil
}

/*
	Get a container by id
*/
func GetContainerByID(id int) (Container, error) {
	var container Container // Container to return
	var err error           // Error handling

	err = GetContainerByCIDStmt.QueryRow(id).Scan(&container.ID, &container.CID, &container.ProbeID, &container.Hostname, &container.Image, &container.IPAddress, &container.MacAddress)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			return container, err
		} else {
			l.Error("GetContainerByID:", err)
			return container, err
		}
	}

	return container, nil
}

/*
	Get a container by cid
*/
func GetContainerByCID(cid string) (Container, error) {
	var container Container // Container to return
	var err error           // Error handling

	err = GetContainerByCIDStmt.QueryRow(cid).Scan(&container.ID, &container.CID, &container.ProbeID, &container.Hostname, &container.Image, &container.IPAddress, &container.MacAddress)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			return container, err
		} else {
			l.Error("GetContainerByCID:", err)
			return container, err
		}
	}

	return container, nil
}

/*
	Insert a stat
*/
func (s *Stat) Insert() error {
	var err error // Error handling
	var timeInsert int64 = time.Now().Unix()

	_, err = InsertStatStmt.Exec(s.ContainerID, timeInsert, s.SizeRootFs, s.SizeRw, s.SizeMemory, s.Running)

	return err
}

/*
	Delete a stat
*/
func (s *Stat) Delete() error {
	var err error // Error handling

	_, err = DeleteStatStmt.Exec(s.ContainerID, s.Time)

	return err
}

/*
	Get stats by container id
*/
func GetStatsByContainerID(containerID string) ([]Stat, error) {
	var stats []Stat   // List of stats to return
	var err error      // Erro handling
	var tmpStat Stat   // Temporary stat
	var rows *sql.Rows // Temporary sql rows

	rows, err = GetStatsByContainerIdStmt.Query(containerID)
	if err != nil {
		l.Error("GetStatsByContainerID:", err)
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		err = rows.Scan(&tmpStat.ContainerID, &tmpStat.Time, &tmpStat.SizeRootFs, &tmpStat.SizeRw, &tmpStat.SizeMemory, &tmpStat.Running)
		if err != nil {
			l.Error("GetStatsByContainerID:", err)
			return nil, err
		}
		stats = append(stats, tmpStat)
	}
	err = rows.Err()
	if err != nil {
		l.Error("GetStatsByContainerID:", err)
		return nil, err
	}

	return stats, nil
}
<|endoftext|>


<commit_before>package workflows

//go:generate go run cuelang.org/go/cmd/cue cmd genworkflows cuelang.org/go/internal/ci
<commit_msg>.github: disable generation of schema<commit_after>package workflows

// Disable generation of this script for now.
// go:generate go run cuelang.org/go/cmd/cue cmd genworkflows cuelang.org/go/internal/ci
<|endoftext|>


<commit_before>/*
Copyright 2019 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package awstasks

import (
	"io/ioutil"
	"os"
	"path"
	"reflect"
	"testing"

	"k8s.io/kops/pkg/diff"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
	"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
	"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
)

type renderTest struct {
	Resource interface{}
	Expected string
}

func doRenderTests(t *testing.T, method string, cases []*renderTest) {
	outdir, err := ioutil.TempDir("/tmp", "kops-render-")
	if err != nil {
		t.Errorf("failed to create local render directory: %s", err)
		t.FailNow()
	}
	defer os.RemoveAll(outdir)

	for i, c := range cases {
		var filename string
		var target interface{}

		cloud := awsup.BuildMockAWSCloud("eu-west-2", "abc")

		switch method {
		case "RenderTerraform":
			target = terraform.NewTerraformTarget(cloud, "eu-west-2", "test", outdir, terraform.Version012, nil)
			filename = "kubernetes.tf"
		case "RenderCloudformation":
			target = cloudformation.NewCloudformationTarget(cloud, "eu-west-2", "test", outdir)
			filename = "kubernetes.json"
		default:
			t.Errorf("unknown render method: %s", method)
			t.FailNow()
		}

		// @step: build the inputs for the methods - hopefully these don't change between them
		var inputs []reflect.Value
		for _, x := range []interface{}{target, c.Resource, c.Resource, c.Resource} {
			inputs = append(inputs, reflect.ValueOf(x))
		}

		err := func() error {
			// @step: invoke the rendering method of the target
			resp := reflect.ValueOf(c.Resource).MethodByName(method).Call(inputs)
			if err := resp[0].Interface(); err != nil {
				return err.(error)
			}

			// @step: invoke the target finish up
			in := []reflect.Value{reflect.ValueOf(make(map[string]fi.Task))}
			resp = reflect.ValueOf(target).MethodByName("Finish").Call(in)
			if err := resp[0].Interface(); err != nil {
				return err.(error)
			}

			// @step: check the render is as expected
			if c.Expected != "" {
				content, err := ioutil.ReadFile(path.Join(outdir, filename))
				if err != nil {
					return err
				}
				if c.Expected != string(content) {
					diffString := diff.FormatDiff(c.Expected, string(content))
					t.Logf("diff:\n%s\n", diffString)
					t.Errorf("case %d, expected: %s\n,got: %s\n", i, c.Expected, string(content))
					//assert.Equal(t, "", string(content))
				}
			}

			return nil
		}()
		if err != nil {
			t.Errorf("case %d, did not expect an error: %s", i, err)
		}
	}
}
<commit_msg>add os.RemoveAll err verification<commit_after>/*
Copyright 2019 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package awstasks

import (
	"io/ioutil"
	"os"
	"path"
	"reflect"
	"testing"

	"k8s.io/kops/pkg/diff"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
	"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
	"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
)

type renderTest struct {
	Resource interface{}
	Expected string
}

func doRenderTests(t *testing.T, method string, cases []*renderTest) {
	outdir, err := ioutil.TempDir("/tmp", "kops-render-")
	if err != nil {
		t.Errorf("failed to create local render directory: %s", err)
		t.FailNow()
	}
	defer func() {
		err := os.RemoveAll(outdir)
		if err != nil {
			t.Errorf("failed to remove temp dir %q: %v", outdir, err)
		}
	}()

	for i, c := range cases {
		var filename string
		var target interface{}

		cloud := awsup.BuildMockAWSCloud("eu-west-2", "abc")

		switch method {
		case "RenderTerraform":
			target = terraform.NewTerraformTarget(cloud, "eu-west-2", "test", outdir, terraform.Version012, nil)
			filename = "kubernetes.tf"
		case "RenderCloudformation":
			target = cloudformation.NewCloudformationTarget(cloud, "eu-west-2", "test", outdir)
			filename = "kubernetes.json"
		default:
			t.Errorf("unknown render method: %s", method)
			t.FailNow()
		}

		// @step: build the inputs for the methods - hopefully these don't change between them
		var inputs []reflect.Value
		for _, x := range []interface{}{target, c.Resource, c.Resource, c.Resource} {
			inputs = append(inputs, reflect.ValueOf(x))
		}

		err := func() error {
			// @step: invoke the rendering method of the target
			resp := reflect.ValueOf(c.Resource).MethodByName(method).Call(inputs)
			if err := resp[0].Interface(); err != nil {
				return err.(error)
			}

			// @step: invoke the target finish up
			in := []reflect.Value{reflect.ValueOf(make(map[string]fi.Task))}
			resp = reflect.ValueOf(target).MethodByName("Finish").Call(in)
			if err := resp[0].Interface(); err != nil {
				return err.(error)
			}

			// @step: check the render is as expected
			if c.Expected != "" {
				content, err := ioutil.ReadFile(path.Join(outdir, filename))
				if err != nil {
					return err
				}
				if c.Expected != string(content) {
					diffString := diff.FormatDiff(c.Expected, string(content))
					t.Logf("diff:\n%s\n", diffString)
					t.Errorf("case %d, expected: %s\n,got: %s\n", i, c.Expected, string(content))
					//assert.Equal(t, "", string(content))
				}
			}

			return nil
		}()
		if err != nil {
			t.Errorf("case %d, did not expect an error: %s", i, err)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"sort"
	"strings"
)

func GlistStats(list string) []string {
	list = strings.Trim(list, "| ")
	list = strings.Replace(list, "|", "\n", -1)
	stats := ParseList(list)
	var txt []string
	for _, stat := range stats {
		if strings.Contains(stat, "404 item not found:") {
			txt = append(txt, fmt.Sprintf("%s\n", stat))
		} else {
			n := strings.Index(stat, " (")
			itemName := stat[0:n]
			n = strings.Index(stat, "Last ID:")
			idDate := stat[n : len(stat)]
			txt = append(txt, fmt.Sprintf("%s - %s\n", idDate, itemName))
		}
	}
	sort.Strings(txt)
	return txt
}
<commit_msg>go fmt<commit_after>package main

import (
	"fmt"
	"sort"
	"strings"
)

func GlistStats(list string) []string {
	list = strings.Trim(list, "| ")
	list = strings.Replace(list, "|", "\n", -1)
	stats := ParseList(list)
	var txt []string
	for _, stat := range stats {
		if strings.Contains(stat, "404 item not found:") {
			txt = append(txt, fmt.Sprintf("%s\n", stat))
		} else {
			n := strings.Index(stat, " (")
			itemName := stat[0:n]
			n = strings.Index(stat, "Last ID:")
			idDate := stat[n:len(stat)]
			txt = append(txt, fmt.Sprintf("%s - %s\n", idDate, itemName))
		}
	}
	sort.Strings(txt)
	return txt
}
<|endoftext|>


<commit_before>//go:build js
// +build js

package bits

type _err string

func (e _err) Error() string {
	return string(e)
}

// RuntimeError implements runtime.Error.
func (e _err) RuntimeError() {
}

var (
	overflowError error = _err("runtime error: integer overflow")
	divideError   error = _err("runtime error: integer divide by zero")
)
<commit_msg>Implement *32 functions in `math/bits` without 64-bit arithmetics.<commit_after>//go:build js
// +build js

package bits

type _err string

func (e _err) Error() string {
	return string(e)
}

// RuntimeError implements runtime.Error.
func (e _err) RuntimeError() {
}

var (
	overflowError error = _err("runtime error: integer overflow")
	divideError   error = _err("runtime error: integer divide by zero")
)

func Mul32(x, y uint32) (hi, lo uint32) {
	// Avoid slow 64-bit integers for better performance. Adapted from Mul64().
	const mask16 = 1<<16 - 1
	x0 := x & mask16
	x1 := x >> 16
	y0 := y & mask16
	y1 := y >> 16
	w0 := x0 * y0
	t := x1*y0 + w0>>16
	w1 := t & mask16
	w2 := t >> 16
	w1 += x0 * y1
	hi = x1*y1 + w2 + w1>>16
	lo = x * y
	return
}

func Add32(x, y, carry uint32) (sum, carryOut uint32) {
	// Avoid slow 64-bit integers for better performance. Adapted from Add64().
	sum = x + y + carry
	carryOut = ((x & y) | ((x | y) &^ sum)) >> 31
	return
}

func Div32(hi, lo, y uint32) (quo, rem uint32) {
	// Avoid slow 64-bit integers for better performance. Adapted from Div64().
	const (
		two16  = 1 << 16
		mask16 = two16 - 1
	)
	if y == 0 {
		panic(divideError)
	}
	if y <= hi {
		panic(overflowError)
	}

	s := uint(LeadingZeros32(y))
	y <<= s

	yn1 := y >> 16
	yn0 := y & mask16
	un16 := hi<<s | lo>>(32-s)
	un10 := lo << s
	un1 := un10 >> 16
	un0 := un10 & mask16
	q1 := un16 / yn1
	rhat := un16 - q1*yn1

	for q1 >= two16 || q1*yn0 > two16*rhat+un1 {
		q1--
		rhat += yn1
		if rhat >= two16 {
			break
		}
	}

	un21 := un16*two16 + un1 - q1*y
	q0 := un21 / yn1
	rhat = un21 - q0*yn1

	for q0 >= two16 || q0*yn0 > two16*rhat+un0 {
		q0--
		rhat += yn1
		if rhat >= two16 {
			break
		}
	}

	return q1*two16 + q0, (un21*two16 + un0 - q0*y) >> s
}

func Rem32(hi, lo, y uint32) uint32 {
	// We scale down hi so that hi < y, then use Div32 to compute the
	// rem with the guarantee that it won't panic on quotient overflow.
	// Given that
	//   hi ≡ hi%y    (mod y)
	// we have
	//   hi<<64 + lo ≡ (hi%y)<<64 + lo    (mod y)
	_, rem := Div32(hi%y, lo, y)
	return rem
}
<|endoftext|>


<commit_before>package wlog

import (
	"fmt"
	"io/ioutil"
	"strings"
)

// Default config location.
var ConfigLocation = "log.conf"

// LoadAppenders
func LoadAppenders(lines []string) {
	ScanAddConsoleAppender(lines)
	ScanAddFileAppender(lines)
	ScanAddDBAppender(lines)
}

// IsHasAppender
func IsHasAppender(name string, lines []string) bool {
	name = strings.ToLower(name)
	value, ok := ScanConfigValue("appender", lines)
	if !ok {
		return false
	}
	aS := strings.Split(value, ",")
	for _, a := range aS {
		a = strings.TrimSpace(a)
		a = strings.ToLower(a)
		if a == name {
			return true
		}
	}
	return false
}

// ScanConfigValue
func ScanConfigValue(scanKey string, lines []string) (string, bool) {
	for _, line := range lines {
		line = strings.TrimSpace(line)
		// skip blank and comment line
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		lineA := strings.Split(line, "=")
		// skip not include = line
		if len(lineA) != 2 {
			continue
		}
		key := strings.TrimSpace(lineA[0])
		key = strings.ToLower(key)
		value := strings.TrimSpace(lineA[1])
		// process append-file-location key
		if key == scanKey {
			return value, true
		}
	}
	return "", false
}

// LoadConfig try to read config file.
func LoadConfig(location string) error {
	bs, err := ioutil.ReadFile(location)
	if err != nil {
		// file not found
		return err
	}

	lines := strings.Split(string(bs), "\n")

	LoadAppenders(lines)

	return nil
}

// LoadDefaultConfig loads logger configuations.
// Privilege sequence:
// - ConfigLocation specification
// - log.conf
// - conf/log.conf
// - /rundata/log.conf
// - /conf/common/log.conf
func InitConfig() {
	// Load config from ConfigLoaction
	if LoadConfig(ConfigLocation) == nil {
		fmt.Printf("Init logger form: %s\n", ConfigLocation)
		return
	}

	// Load config from current dir
	if LoadConfig("log.conf") == nil {
		fmt.Printf("Init logger form: %s\n", "log.conf")
		return
	}

	// Load config from conf dir
	if LoadConfig("conf/log.conf") == nil {
		fmt.Printf("Init logger form: %s\n", "conf/log.conf")
		return
	}

	// Load config from /rundata dir
	if LoadConfig("/rundata/log.conf") == nil {
		fmt.Printf("Init logger form: %s\n", "/rundata/log.conf")
		return
	}

	// Load config from /conf dir
	if LoadConfig("/conf/common/log.conf") == nil {
		fmt.Printf("Init logger form: %s\n", "/conf/log.conf")
		return
	}

}
<commit_msg>fix config<commit_after>package wlog

import (
	"fmt"
	"io/ioutil"
	"strings"
)

// Default config location.
var ConfigLocation = "log.conf"

// LoadAppenders
func LoadAppenders(lines []string) {
	ScanAddConsoleAppender(lines)
	ScanAddFileAppender(lines)
	ScanAddDBAppender(lines)
}

// IsHasAppender
func IsHasAppender(name string, lines []string) bool {
	name = strings.ToLower(name)
	value, ok := ScanConfigValue("appender", lines)
	if !ok {
		return false
	}
	aS := strings.Split(value, ",")
	for _, a := range aS {
		a = strings.TrimSpace(a)
		a = strings.ToLower(a)
		if a == name {
			return true
		}
	}
	return false
}

// ScanConfigValue
func ScanConfigValue(scanKey string, lines []string) (string, bool) {
	for _, line := range lines {
		line = strings.TrimSpace(line)
		// skip blank and comment line
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		lineA := strings.Split(line, "=")
		// skip not include = line
		if len(lineA) != 2 {
			continue
		}
		key := strings.TrimSpace(lineA[0])
		key = strings.ToLower(key)
		value := strings.TrimSpace(lineA[1])
		// process append-file-location key
		if key == scanKey {
			return value, true
		}
	}
	return "", false
}

// LoadConfig try to read config file.
func LoadConfig(location string) error {
	bs, err := ioutil.ReadFile(location)
	if err != nil {
		// file not found
		return err
	}
	fmt.Printf("Init logger form: %s\n", location)
	lines := strings.Split(string(bs), "\n")

	LoadAppenders(lines)

	return nil
}

// LoadDefaultConfig loads logger configuations.
// Privilege sequence:
// - ConfigLocation specification
// - log.conf
// - conf/log.conf
// - /etc/mlog/log.conf
func InitConfig() {
	// Load config from ConfigLoaction
	if LoadConfig(ConfigLocation) == nil {
		return
	}

	// Load config from current dir
	if LoadConfig("log.conf") == nil {
		return
	}

	// Load config from conf dir
	if LoadConfig("conf/log.conf") == nil {
		return
	}

	// Load config from /etc
	if LoadConfig("/etc/mlog/log.conf") == nil {
		return
	}
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/lancetw/hcfd-forecast/db"
	"github.com/lancetw/hcfd-forecast/rain"
	"github.com/line/line-bot-sdk-go/linebot"
)

const timeZone = "Asia/Taipei"

var bot *linebot.Client

func main() {
	strID := os.Getenv("ChannelID")
	numID, err := strconv.ParseInt(strID, 10, 64)
	if err != nil {
		log.Fatal("Wrong environment setting about ChannelID")
	}
	bot, err = linebot.NewClient(numID, os.Getenv("ChannelSecret"), os.Getenv("MID"))
	if err != nil {
		log.Println("Bot:", bot, " err:", err)
	}

	for {
		c := db.Connect(os.Getenv("REDISTOGO_URL"))

		targets := []string{"新竹市", "新竹縣", "台中市", "高雄市", "台北市"}
		msgs, token := rain.GetInfo(targets[0], targets)

		n, addErr := c.Do("SADD", "token", token)
		if addErr != nil {
			log.Println("SADD to redis error", addErr, n)
		}

		status, getErr := redis.Int(c.Do("SISMEMBER", "token", token))
		if getErr != nil {
			if err != nil {
				log.Println(err)
			}
		}

		if status == 1 {
			log.Println("\n***************************************")

			users, smembersErr := redis.Strings(c.Do("SMEMBERS", "user"))

			if smembersErr != nil {
				log.Println("SMEMBERS redis error", smembersErr)
			} else {
				local := time.Now()
				location, err := time.LoadLocation(timeZone)
				if err == nil {
					local = local.In(location)
				}

				for _, contentTo := range users {
					for _, msg := range msgs {
						_, err = bot.SendText([]string{contentTo}, msg)
						if err != nil {
							log.Println(err)
						}
					}
				}
			}
		}

		defer c.Close()

		time.Sleep(5 * 60 * time.Second)
	}
}
<commit_msg>1 minutes<commit_after>package main

import (
	"log"
	"os"
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/lancetw/hcfd-forecast/db"
	"github.com/lancetw/hcfd-forecast/rain"
	"github.com/line/line-bot-sdk-go/linebot"
)

const timeZone = "Asia/Taipei"

var bot *linebot.Client

func main() {
	strID := os.Getenv("ChannelID")
	numID, err := strconv.ParseInt(strID, 10, 64)
	if err != nil {
		log.Fatal("Wrong environment setting about ChannelID")
	}
	bot, err = linebot.NewClient(numID, os.Getenv("ChannelSecret"), os.Getenv("MID"))
	if err != nil {
		log.Println("Bot:", bot, " err:", err)
	}

	for {
		c := db.Connect(os.Getenv("REDISTOGO_URL"))

		targets := []string{"新竹市", "新竹縣", "台中市", "高雄市", "台北市"}
		msgs, token := rain.GetInfo(targets[0], targets)

		n, addErr := c.Do("SADD", "token", token)
		if addErr != nil {
			log.Println("SADD to redis error", addErr, n)
		}

		status, getErr := redis.Int(c.Do("SISMEMBER", "token", token))
		if getErr != nil {
			if err != nil {
				log.Println(err)
			}
		}

		if status == 1 {
			log.Println("\n***************************************")

			users, smembersErr := redis.Strings(c.Do("SMEMBERS", "user"))

			if smembersErr != nil {
				log.Println("SMEMBERS redis error", smembersErr)
			} else {
				local := time.Now()
				location, err := time.LoadLocation(timeZone)
				if err == nil {
					local = local.In(location)
				}

				for _, contentTo := range users {
					for _, msg := range msgs {
						_, err = bot.SendText([]string{contentTo}, msg)
						if err != nil {
							log.Println(err)
						}
					}
				}
			}
		}

		defer c.Close()

		time.Sleep(60 * time.Second)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/lancetw/hcfd-forecast/db"
	"github.com/lancetw/hcfd-forecast/rain"
	"github.com/line/line-bot-sdk-go/linebot"
)

const timeZone = "Asia/Taipei"

var bot *linebot.Client

func main() {
	strID := os.Getenv("ChannelID")
	numID, err := strconv.ParseInt(strID, 10, 64)
	if err != nil {
		log.Fatal("Wrong environment setting about ChannelID")
	}
	bot, err = linebot.NewClient(numID, os.Getenv("ChannelSecret"), os.Getenv("MID"))
	if err != nil {
		log.Println("Bot:", bot, " err:", err)
	}

	for {
		var msgs = rain.GetInfo()
		log.Println("\n***************************************")

		c := db.Connect(os.Getenv("REDISTOGO_URL"))
		users, smembersErr := redis.Strings(c.Do("SMEMBERS", "user"))

		if smembersErr != nil {
			log.Println("SMEMBERS redis error", smembersErr)
		} else {
			local := time.Now()
			location, err := time.LoadLocation(timeZone)
			if err == nil {
				local = local.In(location)
			}
			if time.Now().Minute() == 0 {
				for _, contentTo := range users {
					_, err = bot.SendText([]string{contentTo}, fmt.Sprintf("現在時間：%v", local))
					if err != nil {
						log.Println(err)
					}
				}
			}
			for _, contentTo := range users {
				for _, msg := range msgs {
					_, err = bot.SendText([]string{contentTo}, msg)
					if err != nil {
						log.Println(err)
					}
				}
			}
		}
		defer c.Close()
		time.Sleep(60 * time.Second)
	}
}
<commit_msg>changed interval<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/garyburd/redigo/redis"
	"github.com/lancetw/hcfd-forecast/db"
	"github.com/lancetw/hcfd-forecast/rain"
	"github.com/line/line-bot-sdk-go/linebot"
)

const timeZone = "Asia/Taipei"

var bot *linebot.Client

func main() {
	strID := os.Getenv("ChannelID")
	numID, err := strconv.ParseInt(strID, 10, 64)
	if err != nil {
		log.Fatal("Wrong environment setting about ChannelID")
	}
	bot, err = linebot.NewClient(numID, os.Getenv("ChannelSecret"), os.Getenv("MID"))
	if err != nil {
		log.Println("Bot:", bot, " err:", err)
	}

	for {
		var msgs = rain.GetInfo()
		log.Println("\n***************************************")

		c := db.Connect(os.Getenv("REDISTOGO_URL"))
		users, smembersErr := redis.Strings(c.Do("SMEMBERS", "user"))

		if smembersErr != nil {
			log.Println("SMEMBERS redis error", smembersErr)
		} else {
			local := time.Now()
			location, err := time.LoadLocation(timeZone)
			if err == nil {
				local = local.In(location)
			}
			if time.Now().Minute() == 0 {
				for _, contentTo := range users {
					_, err = bot.SendText([]string{contentTo}, fmt.Sprintf("現在時間：%v", local))
					if err != nil {
						log.Println(err)
					}
				}
			}
			for _, contentTo := range users {
				for _, msg := range msgs {
					_, err = bot.SendText([]string{contentTo}, msg)
					if err != nil {
						log.Println(err)
					}
				}
			}
		}
		defer c.Close()
		time.Sleep(60 * 10 * time.Second)
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2019 Sick Yoon
// This file is part of gocelery which is released under MIT license.
// See file LICENSE for full license details.

package gocelery

import (
	"context"
	"math/rand"
	"reflect"
	"testing"
	"time"

	uuid "github.com/satori/go.uuid"
)

// add is test task method
func add(a int, b int) int {
	return a + b
}

// TestWorkerRegisterTask tests whether a task can be registered and retrieved correctly
func TestWorkerRegisterTask(t *testing.T) {
	testCases := []struct {
		name           string
		broker         CeleryBroker
		backend        CeleryBackend
		registeredTask interface{}
	}{
		{
			name:           "register task with redis broker/backend",
			broker:         redisBroker,
			backend:        redisBackend,
			registeredTask: add,
		},
		{
			name:           "register task with amqp broker/backend",
			broker:         amqpBroker,
			backend:        amqpBackend,
			registeredTask: add,
		},
	}
	for _, tc := range testCases {
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, 1)
		taskName := uuid.Must(uuid.NewV4()).String()
		celeryWorker.Register(taskName, tc.registeredTask)
		receivedTask := celeryWorker.GetTask(taskName)
		if !reflect.DeepEqual(
			reflect.ValueOf(receivedTask),
			reflect.ValueOf(tc.registeredTask),
		) {
			t.Errorf("test '%s': expected registered task %+v but received %+v", tc.name, tc.registeredTask, receivedTask)
		}
	}
}

// TestWorkerRunTask tests successful function execution
func TestWorkerRunTask(t *testing.T) {
	testCases := []struct {
		name           string
		broker         CeleryBroker
		backend        CeleryBackend
		registeredTask interface{}
	}{
		{
			name:           "run task with redis broker/backend",
			broker:         redisBroker,
			backend:        redisBackend,
			registeredTask: add,
		},
		{
			name:           "run task with amqp broker/backend",
			broker:         amqpBroker,
			backend:        amqpBackend,
			registeredTask: add,
		},
	}
	for _, tc := range testCases {
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, 1)
		taskName := uuid.Must(uuid.NewV4()).String()
		celeryWorker.Register(taskName, tc.registeredTask)
		args := []interface{}{
			rand.Int(),
			rand.Int(),
		}
		res := add(args[0].(int), args[1].(int))
		taskMessage := &TaskMessage{
			ID:      uuid.Must(uuid.NewV4()).String(),
			Task:    taskName,
			Args:    args,
			Kwargs:  nil,
			Retries: 1,
			ETA:     nil,
		}
		resultMsg, err := celeryWorker.RunTask(taskMessage)
		if err != nil {
			t.Errorf("test '%s': failed to run celery task %v: %v", tc.name, taskMessage, err)
			continue
		}
		reflectRes := resultMsg.Result.(int64)
		if int64(res) != reflectRes {
			t.Errorf("test '%s': reflect result %v is different from normal result %v", tc.name, reflectRes, res)
		}
	}
}

// TestWorkerNumWorkers ensures correct number of workers is set
func TestWorkerNumWorkers(t *testing.T) {
	testCases := []struct {
		name    string
		broker  CeleryBroker
		backend CeleryBackend
	}{
		{
			name:    "ensure correct number of workers with redis broker/backend",
			broker:  redisBroker,
			backend: redisBackend,
		},
		{
			name:    "ensure correct number of workers with amqp broker/backend",
			broker:  amqpBroker,
			backend: amqpBackend,
		},
	}
	for _, tc := range testCases {
		numWorkers := rand.Intn(10)
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, numWorkers)
		celeryNumWorkers := celeryWorker.GetNumWorkers()
		if numWorkers != celeryNumWorkers {
			t.Errorf("test '%s': number of workers are different: %d vs %d", tc.name, numWorkers, celeryNumWorkers)
		}
	}
}

// TestWorkerStartStop tests starting and stopping workers
// and gracefully wait for all workers to terminate
// ensure test timeout is set to avoid hanging
func TestWorkerStartStop(t *testing.T) {
	testCases := []struct {
		name    string
		broker  CeleryBroker
		backend CeleryBackend
	}{
		{
			name:    "start and gracefully stop workers with redis broker/backend",
			broker:  redisBroker,
			backend: redisBackend,
		},
		{
			name:    "start and gracefully stop workers with amqp broker/backend",
			broker:  amqpBroker,
			backend: amqpBackend,
		},
	}
	for _, tc := range testCases {
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, 1000)
		go celeryWorker.StartWorker()
		time.Sleep(100 * time.Millisecond)
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		go func() {
			celeryWorker.StopWorker()
			cancel()
		}()
		func() {
			for {
				select {
				case <-ctx.Done():
					if ctx.Err() != context.Canceled {
						t.Errorf("test '%s': failed to stop celery workers in time: %+v", tc.name, ctx.Err())
					}
					return
				default:
					time.Sleep(100 * time.Millisecond)
				}
			}
		}()
	}
}
<commit_msg>Increase timeout in TestWorkerStartStop from 10s to 20s to fix redis broker/backend testcase fail<commit_after>// Copyright (c) 2019 Sick Yoon
// This file is part of gocelery which is released under MIT license.
// See file LICENSE for full license details.

package gocelery

import (
	"context"
	"math/rand"
	"reflect"
	"testing"
	"time"

	uuid "github.com/satori/go.uuid"
)

// add is test task method
func add(a int, b int) int {
	return a + b
}

// TestWorkerRegisterTask tests whether a task can be registered and retrieved correctly
func TestWorkerRegisterTask(t *testing.T) {
	testCases := []struct {
		name           string
		broker         CeleryBroker
		backend        CeleryBackend
		registeredTask interface{}
	}{
		{
			name:           "register task with redis broker/backend",
			broker:         redisBroker,
			backend:        redisBackend,
			registeredTask: add,
		},
		{
			name:           "register task with amqp broker/backend",
			broker:         amqpBroker,
			backend:        amqpBackend,
			registeredTask: add,
		},
	}
	for _, tc := range testCases {
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, 1)
		taskName := uuid.Must(uuid.NewV4()).String()
		celeryWorker.Register(taskName, tc.registeredTask)
		receivedTask := celeryWorker.GetTask(taskName)
		if !reflect.DeepEqual(
			reflect.ValueOf(receivedTask),
			reflect.ValueOf(tc.registeredTask),
		) {
			t.Errorf("test '%s': expected registered task %+v but received %+v", tc.name, tc.registeredTask, receivedTask)
		}
	}
}

// TestWorkerRunTask tests successful function execution
func TestWorkerRunTask(t *testing.T) {
	testCases := []struct {
		name           string
		broker         CeleryBroker
		backend        CeleryBackend
		registeredTask interface{}
	}{
		{
			name:           "run task with redis broker/backend",
			broker:         redisBroker,
			backend:        redisBackend,
			registeredTask: add,
		},
		{
			name:           "run task with amqp broker/backend",
			broker:         amqpBroker,
			backend:        amqpBackend,
			registeredTask: add,
		},
	}
	for _, tc := range testCases {
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, 1)
		taskName := uuid.Must(uuid.NewV4()).String()
		celeryWorker.Register(taskName, tc.registeredTask)
		args := []interface{}{
			rand.Int(),
			rand.Int(),
		}
		res := add(args[0].(int), args[1].(int))
		taskMessage := &TaskMessage{
			ID:      uuid.Must(uuid.NewV4()).String(),
			Task:    taskName,
			Args:    args,
			Kwargs:  nil,
			Retries: 1,
			ETA:     nil,
		}
		resultMsg, err := celeryWorker.RunTask(taskMessage)
		if err != nil {
			t.Errorf("test '%s': failed to run celery task %v: %v", tc.name, taskMessage, err)
			continue
		}
		reflectRes := resultMsg.Result.(int64)
		if int64(res) != reflectRes {
			t.Errorf("test '%s': reflect result %v is different from normal result %v", tc.name, reflectRes, res)
		}
	}
}

// TestWorkerNumWorkers ensures correct number of workers is set
func TestWorkerNumWorkers(t *testing.T) {
	testCases := []struct {
		name    string
		broker  CeleryBroker
		backend CeleryBackend
	}{
		{
			name:    "ensure correct number of workers with redis broker/backend",
			broker:  redisBroker,
			backend: redisBackend,
		},
		{
			name:    "ensure correct number of workers with amqp broker/backend",
			broker:  amqpBroker,
			backend: amqpBackend,
		},
	}
	for _, tc := range testCases {
		numWorkers := rand.Intn(10)
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, numWorkers)
		celeryNumWorkers := celeryWorker.GetNumWorkers()
		if numWorkers != celeryNumWorkers {
			t.Errorf("test '%s': number of workers are different: %d vs %d", tc.name, numWorkers, celeryNumWorkers)
		}
	}
}

// TestWorkerStartStop tests starting and stopping workers
// and gracefully wait for all workers to terminate
// ensure test timeout is set to avoid hanging
func TestWorkerStartStop(t *testing.T) {
	testCases := []struct {
		name    string
		broker  CeleryBroker
		backend CeleryBackend
	}{
		{
			name:    "start and gracefully stop workers with redis broker/backend",
			broker:  redisBroker,
			backend: redisBackend,
		},
		{
			name:    "start and gracefully stop workers with amqp broker/backend",
			broker:  amqpBroker,
			backend: amqpBackend,
		},
	}
	for _, tc := range testCases {
		celeryWorker := NewCeleryWorker(tc.broker, tc.backend, 1000)
		go celeryWorker.StartWorker()
		time.Sleep(100 * time.Millisecond)
		ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
		go func() {
			celeryWorker.StopWorker()
			cancel()
		}()
		func() {
			for {
				select {
				case <-ctx.Done():
					if ctx.Err() != context.Canceled {
						t.Errorf("test '%s': failed to stop celery workers in time: %+v", tc.name, ctx.Err())
					}
					return
				default:
					time.Sleep(100 * time.Millisecond)
				}
			}
		}()
	}
}
<|endoftext|>


<commit_before>package openstack

const (
	BaseOps = `---
- type: replace
  path: /azs
  value:
  - name: z1
    cloud_properties:
      availability_zone: ((az))
  - name: z2
    cloud_properties:
      availability_zone: ((az))
  - name: z3
    cloud_properties:
      availability_zone: ((az))

- type: replace
  path: /compilation
  value:
    workers: 5
    reuse_compilation_vms: true
    az: z1
    vm_type: default
    network: default

- type: replace
  path: /disk_types/name=default/disk_size?
  value: 3000

- type: replace
  path: /networks
  value:
  - name: default
    type: manual
    subnets:
    - range: ((internal_cidr))
      gateway: ((internal_gw))
      azs: [z1, z2, z3]
      dns: [8.8.8.8]
      reserved: [((jumpbox__internal_ip))]
      cloud_properties:
        net_id: ((net_id))

- type: replace
  path: /vm_extensions/-
  value:
    name: cf-router-network-properties

- type: replace
  path: /vm_extensions/-
  value:
    name: cf-tcp-router-network-properties

- type: replace
  path: /vm_extensions/-
  value:
    name: diego-ssh-proxy-network-properties
`
)
<commit_msg>Add vm types to openstack cloud config.<commit_after>package openstack

const (
	BaseOps = `---
- type: replace
  path: /azs
  value:
  - name: z1
    cloud_properties:
      availability_zone: ((az))
  - name: z2
    cloud_properties:
      availability_zone: ((az))
  - name: z3
    cloud_properties:
      availability_zone: ((az))

- type: replace
  path: /vm_types
  value:
  - name: default
    cloud_properties:
      instance_type: m1.small
  - name: large
    cloud_properties:
      instance_type: m1.xlarge

- type: replace
  path: /compilation
  value:
    workers: 5
    reuse_compilation_vms: true
    az: z1
    vm_type: default
    network: default

- type: replace
  path: /disk_types/name=default/disk_size?
  value: 3000

- type: replace
  path: /networks
  value:
  - name: default
    type: manual
    subnets:
    - range: ((internal_cidr))
      gateway: ((internal_gw))
      azs: [z1, z2, z3]
      dns: [8.8.8.8]
      reserved: [((jumpbox__internal_ip))]
      cloud_properties:
        net_id: ((net_id))

- type: replace
  path: /vm_extensions/-
  value:
    name: cf-router-network-properties

- type: replace
  path: /vm_extensions/-
  value:
    name: cf-tcp-router-network-properties

- type: replace
  path: /vm_extensions/-
  value:
    name: diego-ssh-proxy-network-properties
`
)
<|endoftext|>


<commit_before>package configurations

import (
	"os"
	"os/user"
	"path"
)

var applicationName = "bscli"

// IsDev returns if in dev environment or not
func IsDev() bool {
	if os.Getenv("GO_BANK_CLI_DEV") == "true" {
		return true
	}
	return false
}

// DatabasePath returns the path nad name for the database
// taking into account the type of environment
func DatabasePath() (string, string) {
	dbName := "bank"
	if IsDev() {
		return dbName, os.TempDir()
	}

	return dbName, ApplicationHomePath()
}

// LogPath returns the path to the log file
func LogPath() string {
	return path.Join(ApplicationHomePath(), applicationName+".log")
}

// ApplicationHomePath builds the path to application data in the user home,
// something like ~/.bankservices
func ApplicationHomePath() string {
	usr, err := user.Current()
	if err != nil {
		// TODO: no panic here...
		panic(err)
	}
	return path.Join(usr.HomeDir, ".bank")
}
<commit_msg>Removes unsed package<commit_after><|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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 app

import (
	"regexp"
	"testing"

	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"time"

	"github.com/stretchr/testify/assert"
	fed_v1a1 "k8s.io/kubernetes/federation/apis/federation/v1alpha1"
	"k8s.io/kubernetes/federation/cmd/federated-apiserver/app/options"
	"k8s.io/kubernetes/pkg/api/unversioned"
)

func TestLongRunningRequestRegexp(t *testing.T) {
	regexp := regexp.MustCompile(options.NewAPIServer().LongRunningRequestRE)
	dontMatch := []string{
		"/api/v1/watch-namespace/",
		"/api/v1/namespace-proxy/",
		"/api/v1/namespace-watch",
		"/api/v1/namespace-proxy",
		"/api/v1/namespace-portforward/pods",
		"/api/v1/portforward/pods",
		". anything",
		"/ that",
	}
	doMatch := []string{
		"/api/v1/pods/watch",
		"/api/v1/watch/stuff",
		"/api/v1/default/service/proxy",
		"/api/v1/pods/proxy/path/to/thing",
		"/api/v1/namespaces/myns/pods/mypod/log",
		"/api/v1/namespaces/myns/pods/mypod/logs",
		"/api/v1/namespaces/myns/pods/mypod/portforward",
		"/api/v1/namespaces/myns/pods/mypod/exec",
		"/api/v1/namespaces/myns/pods/mypod/attach",
		"/api/v1/namespaces/myns/pods/mypod/log/",
		"/api/v1/namespaces/myns/pods/mypod/logs/",
		"/api/v1/namespaces/myns/pods/mypod/portforward/",
		"/api/v1/namespaces/myns/pods/mypod/exec/",
		"/api/v1/namespaces/myns/pods/mypod/attach/",
		"/api/v1/watch/namespaces/myns/pods",
	}
	for _, path := range dontMatch {
		if regexp.MatchString(path) {
			t.Errorf("path should not have match regexp but did: %s", path)
		}
	}
	for _, path := range doMatch {
		if !regexp.MatchString(path) {
			t.Errorf("path should have match regexp did not: %s", path)
		}
	}
}

var insecurePort = 8081
var serverIP = fmt.Sprintf("http://localhost:%v", insecurePort)
var groupVersion = fed_v1a1.SchemeGroupVersion

func TestRun(t *testing.T) {
	s := options.NewAPIServer()
	s.InsecurePort = insecurePort
	_, ipNet, _ := net.ParseCIDR("10.10.10.0/24")
	s.ServiceClusterIPRange = *ipNet
	s.StorageConfig.ServerList = []string{"http://localhost:4001"}
	go func() {
		if err := Run(s); err != nil {
			t.Fatalf("Error in bringing up the server: %v", err)
		}
	}()
	if err := waitForApiserverUp(); err != nil {
		t.Fatalf("%v", err)
	}
	testSwaggerSpec(t)
	testSupport(t)
	testAPIGroupList(t)
	testAPIGroup(t)
	testAPIResourceList(t)
}

func waitForApiserverUp() error {
	for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
		_, err := http.Get(serverIP)
		if err == nil {
			return nil
		}
	}
	return fmt.Errorf("waiting for apiserver timed out")
}

func readResponse(serverURL string) ([]byte, error) {
	response, err := http.Get(serverURL)
	if err != nil {
		return nil, fmt.Errorf("Error in fetching %s: %v", serverURL, err)
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status: %d for URL: %s, expected status: %d", response.StatusCode, serverURL, http.StatusOK)
	}
	contents, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, fmt.Errorf("Error reading response from %s: %v", serverURL, err)
	}
	return contents, nil
}

func testSwaggerSpec(t *testing.T) {
	serverURL := serverIP + "/swaggerapi"
	_, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

func testSupport(t *testing.T) {
	serverURL := serverIP + "/version"
	_, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

func findGroup(groups []unversioned.APIGroup, groupName string) *unversioned.APIGroup {
	for _, group := range groups {
		if group.Name == groupName {
			return &group
		}
	}
	return nil
}

func testAPIGroupList(t *testing.T) {
	var groupVersionForDiscovery = unversioned.GroupVersionForDiscovery{
		GroupVersion: groupVersion.String(),
		Version:      groupVersion.Version,
	}

	serverURL := serverIP + "/apis"
	contents, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
	var apiGroupList unversioned.APIGroupList
	err = json.Unmarshal(contents, &apiGroupList)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
	}

	found := findGroup(apiGroupList.Groups, groupVersion.Group)
	assert.NotNil(t, found)
	assert.Equal(t, found.Name, groupVersion.Group)
	assert.Equal(t, 1, len(found.Versions))
	assert.Equal(t, found.Versions[0], groupVersionForDiscovery)
	assert.Equal(t, found.PreferredVersion, groupVersionForDiscovery)
}

func testAPIGroup(t *testing.T) {
	serverURL := serverIP + "/apis/federation"
	contents, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
	var apiGroup unversioned.APIGroup
	err = json.Unmarshal(contents, &apiGroup)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
	}
	assert.Equal(t, apiGroup.APIVersion, "v1")
	assert.Equal(t, apiGroup.Name, groupVersion.Group)
	assert.Equal(t, 1, len(apiGroup.Versions))
	assert.Equal(t, apiGroup.Versions[0].GroupVersion, groupVersion.String())
	assert.Equal(t, apiGroup.Versions[0].Version, groupVersion.Version)
	assert.Equal(t, apiGroup.Versions[0], apiGroup.PreferredVersion)
}

func findResource(resources []unversioned.APIResource, resourceName string) *unversioned.APIResource {
	for _, resource := range resources {
		if resource.Name == resourceName {
			return &resource
		}
	}
	return nil
}

func testAPIResourceList(t *testing.T) {
	serverURL := serverIP + "/apis/federation/v1alpha1"
	contents, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
	var apiResourceList unversioned.APIResourceList
	err = json.Unmarshal(contents, &apiResourceList)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
	}
	assert.Equal(t, apiResourceList.APIVersion, "v1")
	assert.Equal(t, apiResourceList.GroupVersion, groupVersion.String())

	found := findResource(apiResourceList.APIResources, "clusters")
	assert.NotNil(t, found)
	assert.False(t, found.Namespaced)
	found = findResource(apiResourceList.APIResources, "clusters/status")
	assert.NotNil(t, found)
	assert.False(t, found.Namespaced)
}
<commit_msg>change port of tests for federated-apiserver to avoid conflict<commit_after>/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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 app

import (
	"regexp"
	"testing"

	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"time"

	"github.com/stretchr/testify/assert"
	fed_v1a1 "k8s.io/kubernetes/federation/apis/federation/v1alpha1"
	"k8s.io/kubernetes/federation/cmd/federated-apiserver/app/options"
	"k8s.io/kubernetes/pkg/api/unversioned"
)

func TestLongRunningRequestRegexp(t *testing.T) {
	regexp := regexp.MustCompile(options.NewAPIServer().LongRunningRequestRE)
	dontMatch := []string{
		"/api/v1/watch-namespace/",
		"/api/v1/namespace-proxy/",
		"/api/v1/namespace-watch",
		"/api/v1/namespace-proxy",
		"/api/v1/namespace-portforward/pods",
		"/api/v1/portforward/pods",
		". anything",
		"/ that",
	}
	doMatch := []string{
		"/api/v1/pods/watch",
		"/api/v1/watch/stuff",
		"/api/v1/default/service/proxy",
		"/api/v1/pods/proxy/path/to/thing",
		"/api/v1/namespaces/myns/pods/mypod/log",
		"/api/v1/namespaces/myns/pods/mypod/logs",
		"/api/v1/namespaces/myns/pods/mypod/portforward",
		"/api/v1/namespaces/myns/pods/mypod/exec",
		"/api/v1/namespaces/myns/pods/mypod/attach",
		"/api/v1/namespaces/myns/pods/mypod/log/",
		"/api/v1/namespaces/myns/pods/mypod/logs/",
		"/api/v1/namespaces/myns/pods/mypod/portforward/",
		"/api/v1/namespaces/myns/pods/mypod/exec/",
		"/api/v1/namespaces/myns/pods/mypod/attach/",
		"/api/v1/watch/namespaces/myns/pods",
	}
	for _, path := range dontMatch {
		if regexp.MatchString(path) {
			t.Errorf("path should not have match regexp but did: %s", path)
		}
	}
	for _, path := range doMatch {
		if !regexp.MatchString(path) {
			t.Errorf("path should have match regexp did not: %s", path)
		}
	}
}

var insecurePort = 8082
var serverIP = fmt.Sprintf("http://localhost:%v", insecurePort)
var groupVersion = fed_v1a1.SchemeGroupVersion

func TestRun(t *testing.T) {
	s := options.NewAPIServer()
	s.InsecurePort = insecurePort
	_, ipNet, _ := net.ParseCIDR("10.10.10.0/24")
	s.ServiceClusterIPRange = *ipNet
	s.StorageConfig.ServerList = []string{"http://localhost:4001"}
	go func() {
		if err := Run(s); err != nil {
			t.Fatalf("Error in bringing up the server: %v", err)
		}
	}()
	if err := waitForApiserverUp(); err != nil {
		t.Fatalf("%v", err)
	}
	testSwaggerSpec(t)
	testSupport(t)
	testAPIGroupList(t)
	testAPIGroup(t)
	testAPIResourceList(t)
}

func waitForApiserverUp() error {
	for start := time.Now(); time.Since(start) < time.Minute; time.Sleep(5 * time.Second) {
		_, err := http.Get(serverIP)
		if err == nil {
			return nil
		}
	}
	return fmt.Errorf("waiting for apiserver timed out")
}

func readResponse(serverURL string) ([]byte, error) {
	response, err := http.Get(serverURL)
	if err != nil {
		return nil, fmt.Errorf("Error in fetching %s: %v", serverURL, err)
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status: %d for URL: %s, expected status: %d", response.StatusCode, serverURL, http.StatusOK)
	}
	contents, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, fmt.Errorf("Error reading response from %s: %v", serverURL, err)
	}
	return contents, nil
}

func testSwaggerSpec(t *testing.T) {
	serverURL := serverIP + "/swaggerapi"
	_, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

func testSupport(t *testing.T) {
	serverURL := serverIP + "/version"
	_, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

func findGroup(groups []unversioned.APIGroup, groupName string) *unversioned.APIGroup {
	for _, group := range groups {
		if group.Name == groupName {
			return &group
		}
	}
	return nil
}

func testAPIGroupList(t *testing.T) {
	var groupVersionForDiscovery = unversioned.GroupVersionForDiscovery{
		GroupVersion: groupVersion.String(),
		Version:      groupVersion.Version,
	}

	serverURL := serverIP + "/apis"
	contents, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
	var apiGroupList unversioned.APIGroupList
	err = json.Unmarshal(contents, &apiGroupList)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
	}

	found := findGroup(apiGroupList.Groups, groupVersion.Group)
	assert.NotNil(t, found)
	assert.Equal(t, found.Name, groupVersion.Group)
	assert.Equal(t, 1, len(found.Versions))
	assert.Equal(t, found.Versions[0], groupVersionForDiscovery)
	assert.Equal(t, found.PreferredVersion, groupVersionForDiscovery)
}

func testAPIGroup(t *testing.T) {
	serverURL := serverIP + "/apis/federation"
	contents, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
	var apiGroup unversioned.APIGroup
	err = json.Unmarshal(contents, &apiGroup)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
	}
	assert.Equal(t, apiGroup.APIVersion, "v1")
	assert.Equal(t, apiGroup.Name, groupVersion.Group)
	assert.Equal(t, 1, len(apiGroup.Versions))
	assert.Equal(t, apiGroup.Versions[0].GroupVersion, groupVersion.String())
	assert.Equal(t, apiGroup.Versions[0].Version, groupVersion.Version)
	assert.Equal(t, apiGroup.Versions[0], apiGroup.PreferredVersion)
}

func findResource(resources []unversioned.APIResource, resourceName string) *unversioned.APIResource {
	for _, resource := range resources {
		if resource.Name == resourceName {
			return &resource
		}
	}
	return nil
}

func testAPIResourceList(t *testing.T) {
	serverURL := serverIP + "/apis/federation/v1alpha1"
	contents, err := readResponse(serverURL)
	if err != nil {
		t.Fatalf("%v", err)
	}
	var apiResourceList unversioned.APIResourceList
	err = json.Unmarshal(contents, &apiResourceList)
	if err != nil {
		t.Fatalf("Error in unmarshalling response from server %s: %v", serverURL, err)
	}
	assert.Equal(t, apiResourceList.APIVersion, "v1")
	assert.Equal(t, apiResourceList.GroupVersion, groupVersion.String())

	found := findResource(apiResourceList.APIResources, "clusters")
	assert.NotNil(t, found)
	assert.False(t, found.Namespaced)
	found = findResource(apiResourceList.APIResources, "clusters/status")
	assert.NotNil(t, found)
	assert.False(t, found.Namespaced)
}
<|endoftext|>