<commit_before>package rpg2d_test

import (
	"bytes"
	"encoding/gob"
	"encoding/json"

	"github.com/ghthor/engine/rpg2d"
	"github.com/ghthor/engine/rpg2d/coord"
	"github.com/ghthor/engine/rpg2d/entity"
	"github.com/ghthor/engine/rpg2d/entity/entitytest"
	"github.com/ghthor/engine/rpg2d/quad"
	"github.com/ghthor/engine/rpg2d/rpg2dtest"
	"github.com/ghthor/engine/sim/stime"

	"github.com/ghthor/gospec"
	. "github.com/ghthor/gospec"
)

func init() {
	gob.Register(entitytest.MockEntityState{})
}

func DescribeWorldState(c gospec.Context) {
	quadTree, err := quad.New(coord.Bounds{
		coord.Cell{-4, 4},
		coord.Cell{3, -3},
	}, 20, nil)
	c.Assume(err, IsNil)

	terrain, err := rpg2d.NewTerrainMap(quadTree.Bounds(), `
DDDDDDDD
DGGGGGGD
DGGRRGGD
DGRRRRGD
DGRRRRGD
DGGRRGGD
DGGGGGGD
DDDDDDDD
`)
	c.Assume(err, IsNil)

	world := rpg2d.NewWorld(stime.Time(0), quadTree, terrain)

	mockEntity := entitytest.MockEntity{EntityId: 0}
	world.Insert(mockEntity)

	worldState := world.ToState()

	c.Assume(worldState.Time, Equals, stime.Time(0))
	c.Assume(len(worldState.Entities), Equals, 1)

	c.Specify("a world state", func() {
		c.Specify("can be encoded as json", func() {
			jsonBytes, err := json.Marshal(worldState)
			c.Expect(err, IsNil)
			c.Expect(string(jsonBytes), Equals, `{"time":0,"bounds":{"tl":{"x":-4,"y":4},"br":{"x":3,"y":-3}},"entities":[{"id":0,"name":"MockEntity0","cell":{"x":0,"y":0}}],"terrainMap":{"bounds":{"tl":{"x":-4,"y":4},"br":{"x":3,"y":-3}},"terrain":"\nDDDDDDDD\nDGGGGGGD\nDGGRRGGD\nDGRRRRGD\nDGRRRRGD\nDGGRRGGD\nDGGGGGGD\nDDDDDDDD\n"}}`)
		})

		func() {
			buf := bytes.NewBuffer(make([]byte, 0, 1024))
			enc := gob.NewEncoder(buf)

			c.Specify("can be encoded as a gob object", func() {
				c.Expect(enc.Encode(worldState), IsNil)
			})

			c.Specify("can be decoded from a gob object", func() {
				dec := gob.NewDecoder(buf)
				c.Assume(enc.Encode(worldState), IsNil)

				state := rpg2d.WorldState{}
				c.Expect(dec.Decode(&state), IsNil)
				c.Expect(state, rpg2dtest.StateEquals, worldState)
			})
		}()

		c.Specify("can be cloned and modified", func() {
			world.Insert(entitytest.MockEntity{EntityId: 1})
			world.Insert(entitytest.MockEntity{EntityId: 2})
			world.Insert(entitytest.MockEntity{EntityId: 3})
			world.Insert(entitytest.MockEntity{EntityId: 4})

			worldState = world.ToState()
			clone := worldState.Clone()

			// Modify the clone
			clone.Entities = append(clone.Entities[:2], clone.Entities[3:]...)

			// Check that the modification didn't effect the original
			for i, e := range worldState.Entities {
				e, isMockEntity := e.(entitytest.MockEntityState)
				c.Assume(isMockEntity, IsTrue)
				c.Expect(e.EntityId(), Equals, entity.Id(i))
			}
		})

		c.Specify("can be culled by a bounding rectangle", func() {
			toBeCulled := []entity.State{
				entitytest.MockEntity{EntityCell: coord.Cell{-3, 3}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{3, 3}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{3, -3}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{-3, -3}}.ToState(),
			}

			wontBeCulled := []entity.State{
				entitytest.MockEntity{EntityCell: coord.Cell{-2, 2}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{1, 2}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{1, -1}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{-2, -1}}.ToState(),
			}

			worldState.Entities = append(worldState.Entities[:0], wontBeCulled...)
			worldState.Entities = append(worldState.Entities, toBeCulled...)

			worldState = worldState.Cull(coord.Bounds{
				coord.Cell{-2, 2},
				coord.Cell{1, -1},
			})

			c.Expect(worldState.Bounds, Equals, coord.Bounds{
				coord.Cell{-2, 2},
				coord.Cell{1, -1},
			})

			c.Expect(worldState.Entities, Not(ContainsAll), toBeCulled)
			c.Expect(worldState.Entities, ContainsAll, wontBeCulled)
			c.Expect(worldState.TerrainMap.String(), Equals, `
GRRG
RRRR
RRRR
GRRG
`)
		})

		c.Specify("can calculate the differences with a previous worldState state", func() {
			c.Specify("when there are no differences", func() {
				c.Expect(len(worldState.Diff(worldState).Entities), Equals, 0)
			})

			c.Specify("when an entity has changed state", func() {
				clone := worldState.Clone()
				entity := clone.Entities[0].(entitytest.MockEntityState)

				// This is a state change
				entity.Cell = coord.Cell{-1, 0}
				clone.Entities[0] = entity

				c.Expect(len(worldState.Diff(clone).Entities), Equals, 1)
			})

			c.Specify("when there is a new entity", func() {
				clone := worldState.Clone()
				clone.Entities = append(clone.Entities, entitytest.MockEntity{EntityId: 1}.ToState())
				c.Expect(len(worldState.Diff(clone).Entities), Equals, 1)
			})

			c.Specify("when an entity doesn't exist anymore", func() {
				clone := worldState.Clone()
				clone.Entities = clone.Entities[:0]
				c.Expect(len(worldState.Diff(clone).Removed), Equals, 1)
			})

			c.Specify("when the viewport has changed", func() {
				clone := worldState.Clone()
				worldState = worldState.Cull(coord.Bounds{
					coord.Cell{-2, 2},
					coord.Cell{2, -2},
				})

				// TODO Specify all 4 directions and all 4 corners
				clone = clone.Cull(coord.Bounds{
					coord.Cell{-3, 2},
					coord.Cell{1, -2},
				})
				c.Expect(worldState.Diff(clone).TerrainMapSlices, Not(IsNil))
			})

			c.Specify("when the viewport hasn't changed", func() {
				clone := worldState.Clone()
				c.Expect(worldState.Diff(clone).TerrainMapSlices, ContainsExactly, []*rpg2d.TerrainMapState{})
			})
		})

		c.Specify("can be updated with a world state diff", func() {
			c.Specify("that updates the time", func() {
				nextState := world.ToState()
				nextState.Time++

				worldState.Apply(worldState.Diff(nextState))

				c.Expect(worldState, rpg2dtest.StateEquals, nextState)
			})

			c.Specify("that contains a new entity", func() {
				world.Insert(entitytest.MockEntity{EntityId: 1})
				nextState := world.ToState()
				diff := worldState.Diff(nextState)

				worldState.Apply(diff)
				c.Expect(worldState, rpg2dtest.StateEquals, nextState)
			})

			c.Specify("that removes an entity", func() {
				world.Remove(mockEntity)
				nextState := world.ToState()
				diff := worldState.Diff(nextState)

				worldState.Apply(diff)
				c.Expect(worldState, rpg2dtest.StateEquals, nextState)
			})
		})
	})
}
<commit_msg>[rpg2d] specify world state diffing in all 8 possible viewport translation directions<commit_after>package rpg2d_test

import (
	"bytes"
	"encoding/gob"
	"encoding/json"

	"github.com/ghthor/engine/rpg2d"
	"github.com/ghthor/engine/rpg2d/coord"
	"github.com/ghthor/engine/rpg2d/entity"
	"github.com/ghthor/engine/rpg2d/entity/entitytest"
	"github.com/ghthor/engine/rpg2d/quad"
	"github.com/ghthor/engine/rpg2d/rpg2dtest"
	"github.com/ghthor/engine/sim/stime"

	"github.com/ghthor/gospec"
	. "github.com/ghthor/gospec"
)

func init() {
	gob.Register(entitytest.MockEntityState{})
}

func DescribeWorldState(c gospec.Context) {
	quadTree, err := quad.New(coord.Bounds{
		coord.Cell{-4, 4},
		coord.Cell{3, -3},
	}, 20, nil)
	c.Assume(err, IsNil)

	terrain, err := rpg2d.NewTerrainMap(quadTree.Bounds(), `
DDDDDDDD
DGGGGGGD
DGGRRGGD
DGRRRRGD
DGRRRRGD
DGGRRGGD
DGGGGGGD
DDDDDDDD
`)
	c.Assume(err, IsNil)

	world := rpg2d.NewWorld(stime.Time(0), quadTree, terrain)

	mockEntity := entitytest.MockEntity{EntityId: 0}
	world.Insert(mockEntity)

	worldState := world.ToState()

	c.Assume(worldState.Time, Equals, stime.Time(0))
	c.Assume(len(worldState.Entities), Equals, 1)

	c.Specify("a world state", func() {
		c.Specify("can be encoded as json", func() {
			jsonBytes, err := json.Marshal(worldState)
			c.Expect(err, IsNil)
			c.Expect(string(jsonBytes), Equals, `{"time":0,"bounds":{"tl":{"x":-4,"y":4},"br":{"x":3,"y":-3}},"entities":[{"id":0,"name":"MockEntity0","cell":{"x":0,"y":0}}],"terrainMap":{"bounds":{"tl":{"x":-4,"y":4},"br":{"x":3,"y":-3}},"terrain":"\nDDDDDDDD\nDGGGGGGD\nDGGRRGGD\nDGRRRRGD\nDGRRRRGD\nDGGRRGGD\nDGGGGGGD\nDDDDDDDD\n"}}`)
		})

		func() {
			buf := bytes.NewBuffer(make([]byte, 0, 1024))
			enc := gob.NewEncoder(buf)

			c.Specify("can be encoded as a gob object", func() {
				c.Expect(enc.Encode(worldState), IsNil)
			})

			c.Specify("can be decoded from a gob object", func() {
				dec := gob.NewDecoder(buf)
				c.Assume(enc.Encode(worldState), IsNil)

				state := rpg2d.WorldState{}
				c.Expect(dec.Decode(&state), IsNil)
				c.Expect(state, rpg2dtest.StateEquals, worldState)
			})
		}()

		c.Specify("can be cloned and modified", func() {
			world.Insert(entitytest.MockEntity{EntityId: 1})
			world.Insert(entitytest.MockEntity{EntityId: 2})
			world.Insert(entitytest.MockEntity{EntityId: 3})
			world.Insert(entitytest.MockEntity{EntityId: 4})

			worldState = world.ToState()
			clone := worldState.Clone()

			// Modify the clone
			clone.Entities = append(clone.Entities[:2], clone.Entities[3:]...)

			// Check that the modification didn't effect the original
			for i, e := range worldState.Entities {
				e, isMockEntity := e.(entitytest.MockEntityState)
				c.Assume(isMockEntity, IsTrue)
				c.Expect(e.EntityId(), Equals, entity.Id(i))
			}
		})

		c.Specify("can be culled by a bounding rectangle", func() {
			toBeCulled := []entity.State{
				entitytest.MockEntity{EntityCell: coord.Cell{-3, 3}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{3, 3}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{3, -3}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{-3, -3}}.ToState(),
			}

			wontBeCulled := []entity.State{
				entitytest.MockEntity{EntityCell: coord.Cell{-2, 2}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{1, 2}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{1, -1}}.ToState(),
				entitytest.MockEntity{EntityCell: coord.Cell{-2, -1}}.ToState(),
			}

			worldState.Entities = append(worldState.Entities[:0], wontBeCulled...)
			worldState.Entities = append(worldState.Entities, toBeCulled...)

			worldState = worldState.Cull(coord.Bounds{
				coord.Cell{-2, 2},
				coord.Cell{1, -1},
			})

			c.Expect(worldState.Bounds, Equals, coord.Bounds{
				coord.Cell{-2, 2},
				coord.Cell{1, -1},
			})

			c.Expect(worldState.Entities, Not(ContainsAll), toBeCulled)
			c.Expect(worldState.Entities, ContainsAll, wontBeCulled)
			c.Expect(worldState.TerrainMap.String(), Equals, `
GRRG
RRRR
RRRR
GRRG
`)
		})

		c.Specify("can calculate the differences with a previous worldState state", func() {
			c.Specify("when there are no differences", func() {
				c.Expect(len(worldState.Diff(worldState).Entities), Equals, 0)
			})

			c.Specify("when an entity has changed state", func() {
				clone := worldState.Clone()
				entity := clone.Entities[0].(entitytest.MockEntityState)

				// This is a state change
				entity.Cell = coord.Cell{-1, 0}
				clone.Entities[0] = entity

				c.Expect(len(worldState.Diff(clone).Entities), Equals, 1)
			})

			c.Specify("when there is a new entity", func() {
				clone := worldState.Clone()
				clone.Entities = append(clone.Entities, entitytest.MockEntity{EntityId: 1}.ToState())
				c.Expect(len(worldState.Diff(clone).Entities), Equals, 1)
			})

			c.Specify("when an entity doesn't exist anymore", func() {
				clone := worldState.Clone()
				clone.Entities = clone.Entities[:0]
				c.Expect(len(worldState.Diff(clone).Removed), Equals, 1)
			})

			c.Specify("when the viewport has changed", func() {
				mockEntity0 := mockEntity
				mockEntity1 := entitytest.MockEntity{
					EntityId:   1,
					EntityCell: coord.Cell{-1, 0},
				}

				mockEntity2 := entitytest.MockEntity{
					EntityId:   2,
					EntityCell: coord.Cell{-1, 1},
				}

				mockEntity3 := entitytest.MockEntity{
					EntityId:   3,
					EntityCell: coord.Cell{0, 1},
				}

				world.Insert(mockEntity0)
				world.Insert(mockEntity1)
				world.Insert(mockEntity2)
				world.Insert(mockEntity3)
				worldState = world.ToState()

				initialState := worldState.Cull(coord.Bounds{
					coord.Cell{-2, 2},
					coord.Cell{1, -1},
				})

				var nextState rpg2d.WorldState

				expectDiffEquals := func(expectedDiff rpg2d.WorldStateDiff) {
					diff := initialState.Diff(nextState)
					c.Expect(diff, rpg2dtest.StateEquals, expectedDiff)
				}

				c.Specify("north", func() {
					bounds := coord.Bounds{
						coord.Cell{-2, 4},
						coord.Cell{1, 1},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity0.ToState(),
							mockEntity1.ToState(),
						},

						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{-2, 4},
								coord.Cell{1, 3},
							},
							Terrain: "\nDDDD\nGGGG\n",
						}},
					})
				})

				c.Specify("north & east", func() {
					bounds := coord.Bounds{
						coord.Cell{0, 4},
						coord.Cell{3, 1},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity0.ToState(),
							mockEntity1.ToState(),
							mockEntity2.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{0, 4},
								coord.Cell{1, 3},
							},
							Terrain: "\nDD\nGG\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{2, 4},
								coord.Cell{3, 3},
							},
							Terrain: "\nDD\nGD\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{2, 2},
								coord.Cell{3, 1},
							},
							Terrain: "\nGD\nGD\n",
						}},
					})
				})

				c.Specify("east", func() {
					bounds := coord.Bounds{
						coord.Cell{0, 2},
						coord.Cell{3, -1},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity1.ToState(),
							mockEntity2.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{2, 2},
								coord.Cell{3, -1},
							},
							Terrain: "\nGD\nGD\nGD\nGD\n",
						}},
					})
				})

				c.Specify("south & east", func() {
					bounds := coord.Bounds{
						coord.Cell{0, 0},
						coord.Cell{3, -3},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity1.ToState(),
							mockEntity2.ToState(),
							mockEntity3.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{2, 0},
								coord.Cell{3, -1},
							},
							Terrain: "\nGD\nGD\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{2, -2},
								coord.Cell{3, -3},
							},
							Terrain: "\nGD\nDD\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{0, -2},
								coord.Cell{1, -3},
							},
							Terrain: "\nGG\nDD\n",
						}},
					})
				})

				c.Specify("south", func() {
					bounds := coord.Bounds{
						coord.Cell{-2, 0},
						coord.Cell{1, -3},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity2.ToState(),
							mockEntity3.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{-2, -2},
								coord.Cell{1, -3},
							},
							Terrain: "\nGGGG\nDDDD\n",
						}},
					})
				})

				c.Specify("south & west", func() {
					bounds := coord.Bounds{
						coord.Cell{-4, 0},
						coord.Cell{-1, -3},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity0.ToState(),
							mockEntity2.ToState(),
							mockEntity3.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{-2, -2},
								coord.Cell{-1, -3},
							},
							Terrain: "\nGG\nDD\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{-4, -2},
								coord.Cell{-3, -3},
							},
							Terrain: "\nDG\nDD\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{-4, 0},
								coord.Cell{-3, -1},
							},
							Terrain: "\nDG\nDG\n",
						}},
					})
				})

				c.Specify("west", func() {
					bounds := coord.Bounds{
						coord.Cell{-4, 2},
						coord.Cell{-1, -1},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity0.ToState(),
							mockEntity3.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{-4, 2},
								coord.Cell{-3, -1},
							},
							Terrain: "\nDG\nDG\nDG\nDG\n",
						}},
					})
				})

				c.Specify("north & west", func() {
					bounds := coord.Bounds{
						coord.Cell{-4, 4},
						coord.Cell{-1, 1},
					}

					nextState = worldState.Cull(bounds)

					expectDiffEquals(rpg2d.WorldStateDiff{
						Bounds: bounds,
						Removed: entity.StateSlice{
							mockEntity0.ToState(),
							mockEntity1.ToState(),
							mockEntity3.ToState(),
						},
						TerrainMapSlices: []rpg2d.TerrainMapStateSlice{{
							Bounds: coord.Bounds{
								coord.Cell{-4, 2},
								coord.Cell{-3, 1},
							},
							Terrain: "\nDG\nDG\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{-4, 4},
								coord.Cell{-3, 3},
							},
							Terrain: "\nDD\nDG\n",
						}, {
							Bounds: coord.Bounds{
								coord.Cell{-2, 4},
								coord.Cell{-1, 3},
							},
							Terrain: "\nDD\nGG\n",
						}},
					})
				})
			})

			c.Specify("when the viewport hasn't changed", func() {
				clone := worldState.Clone()
				c.Expect(worldState.Diff(clone).TerrainMapSlices, ContainsExactly, []*rpg2d.TerrainMapState{})
			})
		})

		c.Specify("can be updated with a world state diff", func() {
			c.Specify("that updates the time", func() {
				nextState := world.ToState()
				nextState.Time++

				worldState.Apply(worldState.Diff(nextState))

				c.Expect(worldState, rpg2dtest.StateEquals, nextState)
			})

			c.Specify("that contains a new entity", func() {
				world.Insert(entitytest.MockEntity{EntityId: 1})
				nextState := world.ToState()
				diff := worldState.Diff(nextState)

				worldState.Apply(diff)
				c.Expect(worldState, rpg2dtest.StateEquals, nextState)
			})

			c.Specify("that removes an entity", func() {
				world.Remove(mockEntity)
				nextState := world.ToState()
				diff := worldState.Diff(nextState)

				worldState.Apply(diff)
				c.Expect(worldState, rpg2dtest.StateEquals, nextState)
			})
		})
	})
}
<|endoftext|>


<commit_before>package byteio

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

func TestWriteBigEndian(t *testing.T) {
	const testData = "\x0a\x0b\x0c\x0d\x0c\x0d\x01\x02\x03\x04\x05\x06\x07\x08A"
	var b bytes.Buffer
	w := BigEndianWriter{Writer: &b}

	if n, err := w.WriteUint32(168496141); err != nil {
		t.Errorf("test 1: unexpected error: %s", err)
	} else if n != 4 {
		t.Errorf("test 1: expecting to write 4 bytes, read %d", n)
	}
	if n, err := w.WriteUint16(3085); err != nil {
		t.Errorf("test 2: unexpected error: %s", err)
	} else if n != 2 {
		t.Errorf("test 2: expecting to write 2 bytes, read %d", n)
	}
	if n, err := w.WriteUint64(72623859790382856); err != nil {
		t.Errorf("test 3: unexpected error: %s", err)
	} else if n != 8 {
		t.Errorf("test 3: expecting to write 8 bytes, read %d", n)
	}
	if n, err := w.WriteUint8(65); err != nil {
		t.Errorf("test 4: unexpected error: %s", err)
	} else if n != 1 {
		t.Errorf("test 4: expecting to write 1 byte, read %d", n)
	}
	if str := b.String(); str != testData {
		t.Errorf("expecting %q, got %q", testData, str)
	}
}

func BenchmarkWriteBigUint8(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint8(1)
	}
}

func BenchmarkWriteBigInt8(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt8(1)
	}
}

func BenchmarkWriteBigUint16(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint16(1)
	}
}

func BenchmarkWriteBigInt16(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt16(1)
	}
}

func BenchmarkWriteBigUint32(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint32(1)
	}
}

func BenchmarkWriteBigInt32(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt32(1)
	}
}

func BenchmarkWriteBigUint64(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint64(1)
	}
}

func BenchmarkWriteBigInt64(b *testing.B) {
	w := BigEndianWriter{Writer: ioutil.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt64(1)
	}
}
<commit_msg>ioutils is now deprecated<commit_after>package byteio

import (
	"bytes"
	"io"
	"testing"
)

func TestWriteBigEndian(t *testing.T) {
	const testData = "\x0a\x0b\x0c\x0d\x0c\x0d\x01\x02\x03\x04\x05\x06\x07\x08A"
	var b bytes.Buffer
	w := BigEndianWriter{Writer: &b}

	if n, err := w.WriteUint32(168496141); err != nil {
		t.Errorf("test 1: unexpected error: %s", err)
	} else if n != 4 {
		t.Errorf("test 1: expecting to write 4 bytes, read %d", n)
	}
	if n, err := w.WriteUint16(3085); err != nil {
		t.Errorf("test 2: unexpected error: %s", err)
	} else if n != 2 {
		t.Errorf("test 2: expecting to write 2 bytes, read %d", n)
	}
	if n, err := w.WriteUint64(72623859790382856); err != nil {
		t.Errorf("test 3: unexpected error: %s", err)
	} else if n != 8 {
		t.Errorf("test 3: expecting to write 8 bytes, read %d", n)
	}
	if n, err := w.WriteUint8(65); err != nil {
		t.Errorf("test 4: unexpected error: %s", err)
	} else if n != 1 {
		t.Errorf("test 4: expecting to write 1 byte, read %d", n)
	}
	if str := b.String(); str != testData {
		t.Errorf("expecting %q, got %q", testData, str)
	}
}

func BenchmarkWriteBigUint8(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint8(1)
	}
}

func BenchmarkWriteBigInt8(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt8(1)
	}
}

func BenchmarkWriteBigUint16(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint16(1)
	}
}

func BenchmarkWriteBigInt16(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt16(1)
	}
}

func BenchmarkWriteBigUint32(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint32(1)
	}
}

func BenchmarkWriteBigInt32(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt32(1)
	}
}

func BenchmarkWriteBigUint64(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteUint64(1)
	}
}

func BenchmarkWriteBigInt64(b *testing.B) {
	w := BigEndianWriter{Writer: io.Discard}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.WriteInt64(1)
	}
}
<|endoftext|>


<commit_before>package schedule

import (
	"testing"
	"time"
)

func XTestBuildCommitScheduleFullWeeks(t *testing.T) {
	var tests = []struct {
		startDay time.Time
		numDays  int
	}{
		{time.Date(2009, time.November, 9, 0, 0, 0, 0, time.UTC), 7},
		{time.Date(2015, time.November, 9, 0, 0, 0, 0, time.UTC), 21},
		{time.Date(2014, time.July, 7, 0, 0, 0, 0, time.UTC), 365},
	}
	for _, test := range tests {
		days := getTestDays(test.startDay, test.numDays)
		schedule := BuildCommitSchedule(days)
		for r, row := range schedule {
			for c, col := range row {
				if col != EMPTY {
					fmt := "Expected only EMPTY values, but got %d at (%d,%d)"
					t.Errorf(fmt, col, r, c)
				}
			}
		}
	}
}

func XTestBuildCommitScheduleWednesdayStart(t *testing.T) {
	var tests = []struct {
		startDay time.Time
		numDays  int
	}{
		{time.Date(2009, time.November, 11, 0, 0, 0, 0, time.UTC), 9},
		{time.Date(2015, time.November, 11, 0, 0, 0, 0, time.UTC), 23},
		{time.Date(2014, time.July, 9, 0, 0, 0, 0, time.UTC), 367},
	}
	for _, test := range tests {
		days := getTestDays(test.startDay, test.numDays)
		schedule := BuildCommitSchedule(days)
		for r, row := range schedule {
			for c, col := range row {
				firstWeekMondayOrTuesDay := (c == 0 && r < 2)
				if firstWeekMondayOrTuesDay {
					if col != NOT_A_FIELD {
						fmt := "Expected NOT_A_FIELD values, but got %d at (%d,%d)"
						t.Errorf(fmt, col, r, c)
					}
				} else if col != EMPTY {
					fmt := "Expected only EMPTY values, but got %d at (%d,%d)"
					t.Errorf(fmt, col, r, c)
				}
			}
		}
	}
}

func XTestBuildCommitScheduleThrusdayEnd(t *testing.T) {
	var tests = []struct {
		startDay time.Time
		numDays  int
	}{
		{time.Date(2009, time.November, 9, 0, 0, 0, 0, time.UTC), 4},
		{time.Date(2015, time.November, 9, 0, 0, 0, 0, time.UTC), 19},
		{time.Date(2014, time.July, 7, 0, 0, 0, 0, time.UTC), 362},
	}
	for _, test := range tests {
		days := getTestDays(test.startDay, test.numDays)
		schedule := BuildCommitSchedule(days)
		for r, row := range schedule {
			for c, col := range row {
				lastWeekFridayOrSaturdayOrSunday := (c == len(row) && r > 4)
				if lastWeekFridayOrSaturdayOrSunday {
					if col != NOT_A_FIELD {
						fmt := "Expected NOT_A_FIELD values, but got %d at (%d,%d)"
						t.Errorf(fmt, col, r, c)
					}
				} else if col != EMPTY {
					fmt := "Expected only EMPTY values, but got %d at (%d,%d)"
					t.Errorf(fmt, col, r, c)
				}
			}
		}
	}
}

func getTestDays(startDay time.Time, numDays int) []time.Time {
	var resultingDays []time.Time
	for i := 0; i < numDays; i++ {
		resultingDays = append(resultingDays, startDay.AddDate(0, 0, i))
	}
	return resultingDays
}

func TestBuildFirstWeek(t *testing.T) {
	var tests = []struct {
		day              time.Weekday
		expectedSchedule []ScheduleEntries
	}{
		{time.Sunday, []ScheduleEntries{0, 0, 0, 0, 0, 0, 0}},
		{time.Monday, []ScheduleEntries{-1, 0, 0, 0, 0, 0, 0}},
		{time.Tuesday, []ScheduleEntries{-1, -1, 0, 0, 0, 0, 0}},
		{time.Wednesday, []ScheduleEntries{-1, -1, -1, 0, 0, 0, 0}},
		{time.Thursday, []ScheduleEntries{-1, -1, -1, -1, 0, 0, 0}},
		{time.Friday, []ScheduleEntries{-1, -1, -1, -1, -1, 0, 0}},
		{time.Saturday, []ScheduleEntries{-1, -1, -1, -1, -1, -1, 0}},
	}
	for _, test := range tests {
		actualSchedule := buildFirstWeek(test.day)
		if !sliceEqual(actualSchedule, test.expectedSchedule) {
			fmt := "Expected %v as schedule, but got %v"
			t.Errorf(fmt, test.expectedSchedule, actualSchedule)
		}
	}
}

func TestBuildLastWeek(t *testing.T) {
	var tests = []struct {
		day              time.Weekday
		expectedSchedule []ScheduleEntries
	}{
		{time.Sunday, []ScheduleEntries{0, -1, -1, -1, -1, -1, -1}},
		{time.Monday, []ScheduleEntries{0, 0, -1, -1, -1, -1, -1}},
		{time.Tuesday, []ScheduleEntries{0, 0, 0, -1, -1, -1, -1}},
		{time.Wednesday, []ScheduleEntries{0, 0, 0, 0, -1, -1, -1}},
		{time.Thursday, []ScheduleEntries{0, 0, 0, 0, 0, -1, -1}},
		{time.Friday, []ScheduleEntries{0, 0, 0, 0, 0, 0, -1}},
		{time.Saturday, []ScheduleEntries{0, 0, 0, 0, 0, 0, 0}},
	}
	for _, test := range tests {
		actualSchedule := buildLastWeek(test.day)
		if !sliceEqual(actualSchedule, test.expectedSchedule) {
			fmt := "Expected %v as schedule, but got %v"
			t.Errorf(fmt, test.expectedSchedule, actualSchedule)
		}
	}
}

func sliceEqual(sliceA, sliceB []ScheduleEntries) bool {
	if len(sliceA) != len(sliceB) {
		return false
	}
	for i := 0; i < len(sliceA); i++ {
		if sliceA[i] != sliceB[i] {
			return false
		}
	}
	return true
}

func TestConnectWeeksToSchedule(t *testing.T) {
	var tests = []struct {
		firstDay            time.Weekday
		lastDay             time.Weekday
		numEntries          int
		numNotAFieldEntries int
	}{
		{time.Sunday, time.Saturday, 371, 0},
		{time.Monday, time.Saturday, 371, 1},
		{time.Wednesday, time.Wednesday, 371, 6},
		{time.Saturday, time.Sunday, 371, 12},
	}
	for _, test := range tests {
		firstWeek := buildFirstWeek(test.firstDay)
		lastWeek := buildLastWeek(test.lastDay)
		schedule := connectWeeksToSchedule(firstWeek, lastWeek)
		length := 0
		numNotAFieldEntries := 0
		for _, row := range schedule {
			for _, entry := range row {
				if entry != EMPTY && entry != NOT_A_FIELD {
					t.Errorf("Entry should be EMPTY or NOT_A_FIELD, but was %v", entry)
				}
				if entry == NOT_A_FIELD {
					numNotAFieldEntries++
				}
				length++
			}
		}

		if length != test.numEntries {
			t.Errorf("Expected length was %d, but got %d", test.numEntries, length)
		}

		if numNotAFieldEntries != test.numNotAFieldEntries {
			t.Errorf("Expected %d NOT_A_FIELD, but got %d", test.numNotAFieldEntries, numNotAFieldEntries)
		}
	}
}
<commit_msg>Remove obsolete test cases and todo for acceptance test.<commit_after>package schedule

import (
	"testing"
	"time"
)

func XTestBuildCommitScheduleFullWeeks(t *testing.T) {
	var tests = []struct {
		startDay            time.Time
		numNotAFieldEntries int
	}{
		// TODO add edge cases, like leap years etc
		{time.Date(2009, time.November, 9, 0, 0, 0, 0, time.UTC), 0},
		{time.Date(2015, time.November, 9, 0, 0, 0, 0, time.UTC), 6},
		{time.Date(2014, time.July, 7, 0, 0, 0, 0, time.UTC), 12},
	}
	for _, test := range tests {
		days := getTestDays(test.startDay)
		schedule := BuildCommitSchedule(days)
		numNotAFieldEntries := 0
		for _, row := range schedule {
			for _, entry := range row {
				if entry != EMPTY && entry != NOT_A_FIELD {
					t.Errorf("Entry should be EMPTY or NOT_A_FIELD, but was %v", entry)
				}
				if entry == NOT_A_FIELD {
					numNotAFieldEntries++
				}
			}

		}
		if numNotAFieldEntries != test.numNotAFieldEntries {
			t.Errorf("Expected %d NOT_A_FIELD entries, but got %d",
				test.numNotAFieldEntries, numNotAFieldEntries)
		}

	}
}

func getTestDays(startDay time.Time) []time.Time {
	var resultingDays []time.Time
	days := GetDaysSinceDateMinusOneYear(startDay)
	for day := range days {
		resultingDays = append(resultingDays, day)
	}
	return resultingDays
}

func TestBuildFirstWeek(t *testing.T) {
	var tests = []struct {
		day              time.Weekday
		expectedSchedule []ScheduleEntries
	}{
		{time.Sunday, []ScheduleEntries{0, 0, 0, 0, 0, 0, 0}},
		{time.Monday, []ScheduleEntries{-1, 0, 0, 0, 0, 0, 0}},
		{time.Tuesday, []ScheduleEntries{-1, -1, 0, 0, 0, 0, 0}},
		{time.Wednesday, []ScheduleEntries{-1, -1, -1, 0, 0, 0, 0}},
		{time.Thursday, []ScheduleEntries{-1, -1, -1, -1, 0, 0, 0}},
		{time.Friday, []ScheduleEntries{-1, -1, -1, -1, -1, 0, 0}},
		{time.Saturday, []ScheduleEntries{-1, -1, -1, -1, -1, -1, 0}},
	}
	for _, test := range tests {
		actualSchedule := buildFirstWeek(test.day)
		if !sliceEqual(actualSchedule, test.expectedSchedule) {
			fmt := "Expected %v as schedule, but got %v"
			t.Errorf(fmt, test.expectedSchedule, actualSchedule)
		}
	}
}

func TestBuildLastWeek(t *testing.T) {
	var tests = []struct {
		day              time.Weekday
		expectedSchedule []ScheduleEntries
	}{
		{time.Sunday, []ScheduleEntries{0, -1, -1, -1, -1, -1, -1}},
		{time.Monday, []ScheduleEntries{0, 0, -1, -1, -1, -1, -1}},
		{time.Tuesday, []ScheduleEntries{0, 0, 0, -1, -1, -1, -1}},
		{time.Wednesday, []ScheduleEntries{0, 0, 0, 0, -1, -1, -1}},
		{time.Thursday, []ScheduleEntries{0, 0, 0, 0, 0, -1, -1}},
		{time.Friday, []ScheduleEntries{0, 0, 0, 0, 0, 0, -1}},
		{time.Saturday, []ScheduleEntries{0, 0, 0, 0, 0, 0, 0}},
	}
	for _, test := range tests {
		actualSchedule := buildLastWeek(test.day)
		if !sliceEqual(actualSchedule, test.expectedSchedule) {
			fmt := "Expected %v as schedule, but got %v"
			t.Errorf(fmt, test.expectedSchedule, actualSchedule)
		}
	}
}

func sliceEqual(sliceA, sliceB []ScheduleEntries) bool {
	if len(sliceA) != len(sliceB) {
		return false
	}
	for i := 0; i < len(sliceA); i++ {
		if sliceA[i] != sliceB[i] {
			return false
		}
	}
	return true
}

func TestConnectWeeksToSchedule(t *testing.T) {
	var tests = []struct {
		firstDay            time.Weekday
		lastDay             time.Weekday
		numEntries          int
		numNotAFieldEntries int
	}{
		{time.Sunday, time.Saturday, 371, 0},
		{time.Monday, time.Saturday, 371, 1},
		{time.Wednesday, time.Wednesday, 371, 6},
		{time.Saturday, time.Sunday, 371, 12},
	}
	for _, test := range tests {
		firstWeek := buildFirstWeek(test.firstDay)
		lastWeek := buildLastWeek(test.lastDay)
		schedule := connectWeeksToSchedule(firstWeek, lastWeek)
		length := 0
		numNotAFieldEntries := 0
		for _, row := range schedule {
			for _, entry := range row {
				if entry != EMPTY && entry != NOT_A_FIELD {
					t.Errorf("Entry should be EMPTY or NOT_A_FIELD, but was %v", entry)
				}
				if entry == NOT_A_FIELD {
					numNotAFieldEntries++
				}
				length++
			}
		}

		if length != test.numEntries {
			t.Errorf("Expected length was %d, but got %d", test.numEntries, length)
		}

		if numNotAFieldEntries != test.numNotAFieldEntries {
			t.Errorf("Expected %d NOT_A_FIELD entries, but got %d",
				test.numNotAFieldEntries, numNotAFieldEntries)
		}
	}
}
<|endoftext|>


<commit_before>package sparta

// THIS FILE IS AUTOMATICALLY GENERATED
// DO NOT EDIT
// CREATED: Sun Jul  1 07:08:10 PDT 2018

// SpartaGitHash is the commit hash of this Sparta library
const SpartaGitHash = "69394428b611c1d24829da08cd34ce381be50a1e"
<commit_msg>Tagging Sparta commit<commit_after>package sparta

// THIS FILE IS AUTOMATICALLY GENERATED
// DO NOT EDIT
// CREATED: Sun Jul  1 07:08:42 PDT 2018

// SpartaGitHash is the commit hash of this Sparta library
const SpartaGitHash = "1c2fafa43b85e3513bcb055cce4802252c3c17ca"
<|endoftext|>


<commit_before>package sdk_test

/*
   Copyright 2016 Alexander I.Grafov <grafov@gmail.com>

   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.

   ॐ तारे तुत्तारे तुरे स्व
*/

import (
	"encoding/json"
	"io/ioutil"
	"testing"

	"github.com/grafana-tools/sdk"
)

func TestUnmarshal_NewEmptyDashboard26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/new-empty-dashboard-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_EmptyDashboardWithTemplating26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-templating-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_EmptyDashboardWithAnnotation26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-annotation-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_EmptyDashboardWithLinks26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-links-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_DashboardWithDefaultPanelsIn2Rows26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/default-panels-all-types-2-rows-dashboard-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_DashboardWithGraphWithTargets26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/default-panels-graph-with-targets-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
	if len(board.Rows) != 1 {
		t.Errorf("there are 1 row defined but got %d", len(board.Rows))
	}
	if len(board.Rows[0].Panels) != 1 {
		t.Errorf("there are 1 panel defined but got %d", len(board.Rows[0].Panels))
	}
	panel := board.Rows[0].Panels[0]
	if panel.OfType != sdk.GraphType {
		t.Errorf("panel type should be %d (\"graph\") type but got %d", sdk.GraphType, panel.OfType)
	}
	if *panel.Datasource != sdk.MixedSource {
		t.Errorf("panel Datasource should be \"%s\" but got \"%s\"", sdk.MixedSource, *panel.Datasource)
	}
	if len(panel.GraphPanel.Targets) != 2 {
		t.Errorf("panel has 2 targets but got %d", len(panel.GraphPanel.Targets))
	}
}

func TestUnmarshal_DashboardWithEmptyPanels30(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/dashboard-with-default-panels-grafana-3.0.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_DashboardWithHiddenTemplates(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-templating-4.0.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}

	if board.Templating.List[1].Hide != sdk.TemplatingHideVariable {
		t.Errorf("templating has hidden variable '%d', got %d", sdk.TemplatingHideVariable, board.Templating.List[1].Hide)
	}
}

func TestUnmarshal_DashboardWithMixedYaxes(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/dashboard-with-panels-with-mixed-yaxes.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}

	p1, p2 := board.Rows[0].Panels[0], board.Rows[0].Panels[1]
	min1, max1 := p1.Yaxes[0].Min, p1.Yaxes[0].Max
	min2, max2 := p1.Yaxes[1].Min, p1.Yaxes[1].Max
	min3, max3 := p2.Yaxes[0].Min, p2.Yaxes[0].Max
	min4, max4 := p2.Yaxes[1].Min, p2.Yaxes[1].Max

	if min1.Value != 0 || min1.Valid != true {
		t.Errorf("panel #1 has wrong min value: %d, expected: %d", min1.Value, 0)
	}
	if max1.Value != 100 || max1.Valid != true {
		t.Errorf("panel #1 has wrong max value: %d, expected: %d", max1.Value, 100)
	}

	if min2 != nil {
		t.Errorf("panel #1 has wrong min value: %v, expected: %v", min2, nil)
	}
	if max2 != nil {
		t.Errorf("panel #1 has wrong max value: %v, expected: %v", max2, nil)
	}

	if min3.Value != 0 || min3.Valid != true {
		t.Errorf("panel #2 has wrong min value: %d, expected: %d", min3.Value, 0)
	}
	if max3 != nil {
		t.Errorf("panel #2 has wrong max value: %v, expected: %v", max3, nil)
	}

	if min4 != nil {
		t.Errorf("panel #2 has wrong min value: %v, expected: %v", min4, nil)
	}
	if max4.Value != 50 || max4.Valid != true {
		t.Errorf("panel #1 has wrong max value: %d, expected: %d", max4.Value, 100)
	}
}
<commit_msg>Fix test formatting<commit_after>package sdk_test

/*
   Copyright 2016 Alexander I.Grafov <grafov@gmail.com>

   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.

   ॐ तारे तुत्तारे तुरे स्व
*/

import (
	"encoding/json"
	"io/ioutil"
	"testing"

	"github.com/grafana-tools/sdk"
)

func TestUnmarshal_NewEmptyDashboard26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/new-empty-dashboard-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_EmptyDashboardWithTemplating26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-templating-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_EmptyDashboardWithAnnotation26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-annotation-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_EmptyDashboardWithLinks26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-links-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_DashboardWithDefaultPanelsIn2Rows26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/default-panels-all-types-2-rows-dashboard-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_DashboardWithGraphWithTargets26(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/default-panels-graph-with-targets-2.6.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
	if len(board.Rows) != 1 {
		t.Errorf("there are 1 row defined but got %d", len(board.Rows))
	}
	if len(board.Rows[0].Panels) != 1 {
		t.Errorf("there are 1 panel defined but got %d", len(board.Rows[0].Panels))
	}
	panel := board.Rows[0].Panels[0]
	if panel.OfType != sdk.GraphType {
		t.Errorf("panel type should be %d (\"graph\") type but got %d", sdk.GraphType, panel.OfType)
	}
	if *panel.Datasource != sdk.MixedSource {
		t.Errorf("panel Datasource should be \"%s\" but got \"%s\"", sdk.MixedSource, *panel.Datasource)
	}
	if len(panel.GraphPanel.Targets) != 2 {
		t.Errorf("panel has 2 targets but got %d", len(panel.GraphPanel.Targets))
	}
}

func TestUnmarshal_DashboardWithEmptyPanels30(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/dashboard-with-default-panels-grafana-3.0.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}
}

func TestUnmarshal_DashboardWithHiddenTemplates(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/empty-dashboard-with-templating-4.0.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}

	if board.Templating.List[1].Hide != sdk.TemplatingHideVariable {
		t.Errorf("templating has hidden variable '%d', got %d", sdk.TemplatingHideVariable, board.Templating.List[1].Hide)
	}
}

func TestUnmarshal_DashboardWithMixedYaxes(t *testing.T) {
	var board sdk.Board
	raw, _ := ioutil.ReadFile("testdata/dashboard-with-panels-with-mixed-yaxes.json")

	err := json.Unmarshal(raw, &board)

	if err != nil {
		t.Error(err)
	}

	p1, p2 := board.Rows[0].Panels[0], board.Rows[0].Panels[1]
	min1, max1 := p1.Yaxes[0].Min, p1.Yaxes[0].Max
	min2, max2 := p1.Yaxes[1].Min, p1.Yaxes[1].Max
	min3, max3 := p2.Yaxes[0].Min, p2.Yaxes[0].Max
	min4, max4 := p2.Yaxes[1].Min, p2.Yaxes[1].Max

	if min1.Value != 0 || min1.Valid != true {
		t.Errorf("panel #1 has wrong min value: %f, expected: %f", min1.Value, 0.0)
	}
	if max1.Value != 100 || max1.Valid != true {
		t.Errorf("panel #1 has wrong max value: %f, expected: %f", max1.Value, 100.0)
	}

	if min2 != nil {
		t.Errorf("panel #1 has wrong min value: %v, expected: %v", min2, nil)
	}
	if max2 != nil {
		t.Errorf("panel #1 has wrong max value: %v, expected: %v", max2, nil)
	}

	if min3.Value != 0 || min3.Valid != true {
		t.Errorf("panel #2 has wrong min value: %f, expected: %f", min3.Value, 0.0)
	}
	if max3 != nil {
		t.Errorf("panel #2 has wrong max value: %v, expected: %v", max3, nil)
	}

	if min4 != nil {
		t.Errorf("panel #2 has wrong min value: %v, expected: %v", min4, nil)
	}
	if max4.Value != 50 || max4.Valid != true {
		t.Errorf("panel #1 has wrong max value: %f, expected: %f", max4.Value, 100.0)
	}
}
<|endoftext|>


<commit_before>package docker

import (
	"errors"
	"fmt"
	"strconv"
	"time"

	dc "github.com/fsouza/go-dockerclient"
	"github.com/hashicorp/terraform/helper/schema"
)

var (
	creationTime time.Time
)

func resourceDockerContainerCreate(d *schema.ResourceData, meta interface{}) error {
	var err error
	client := meta.(*dc.Client)

	var data Data
	if err := fetchLocalImages(&data, client); err != nil {
		return err
	}

	image := d.Get("image").(string)
	if _, ok := data.DockerImages[image]; !ok {
		if _, ok := data.DockerImages[image+":latest"]; !ok {
			return fmt.Errorf("Unable to find image %s", image)
		}
		image = image + ":latest"
	}

	// The awesome, wonderful, splendiferous, sensical
	// Docker API now lets you specify a HostConfig in
	// CreateContainerOptions, but in my testing it still only
	// actually applies HostConfig options set in StartContainer.
	// How cool is that?
	createOpts := dc.CreateContainerOptions{
		Name: d.Get("name").(string),
		Config: &dc.Config{
			Image:      image,
			Hostname:   d.Get("hostname").(string),
			Domainname: d.Get("domainname").(string),
		},
	}

	if v, ok := d.GetOk("env"); ok {
		createOpts.Config.Env = stringSetToStringSlice(v.(*schema.Set))
	}

	if v, ok := d.GetOk("command"); ok {
		createOpts.Config.Cmd = stringListToStringSlice(v.([]interface{}))
	}

	if v, ok := d.GetOk("entrypoint"); ok {
		createOpts.Config.Entrypoint = stringListToStringSlice(v.([]interface{}))
	}

	exposedPorts := map[dc.Port]struct{}{}
	portBindings := map[dc.Port][]dc.PortBinding{}

	if v, ok := d.GetOk("ports"); ok {
		exposedPorts, portBindings = portSetToDockerPorts(v.(*schema.Set))
	}
	if len(exposedPorts) != 0 {
		createOpts.Config.ExposedPorts = exposedPorts
	}

	volumes := map[string]struct{}{}
	binds := []string{}
	volumesFrom := []string{}

	if v, ok := d.GetOk("volumes"); ok {
		volumes, binds, volumesFrom, err = volumeSetToDockerVolumes(v.(*schema.Set))
		if err != nil {
			return fmt.Errorf("Unable to parse volumes: %s", err)
		}
	}
	if len(volumes) != 0 {
		createOpts.Config.Volumes = volumes
	}

	if v, ok := d.GetOk("labels"); ok {
		createOpts.Config.Labels = mapTypeMapValsToString(v.(map[string]interface{}))
	}

	hostConfig := &dc.HostConfig{
		Privileged:      d.Get("privileged").(bool),
		PublishAllPorts: d.Get("publish_all_ports").(bool),
		RestartPolicy: dc.RestartPolicy{
			Name:              d.Get("restart").(string),
			MaximumRetryCount: d.Get("max_retry_count").(int),
		},
		LogConfig: dc.LogConfig{
			Type: d.Get("log_driver").(string),
		},
	}

	if len(portBindings) != 0 {
		hostConfig.PortBindings = portBindings
	}

	if len(binds) != 0 {
		hostConfig.Binds = binds
	}
	if len(volumesFrom) != 0 {
		hostConfig.VolumesFrom = volumesFrom
	}

	if v, ok := d.GetOk("dns"); ok {
		hostConfig.DNS = stringSetToStringSlice(v.(*schema.Set))
	}

	if v, ok := d.GetOk("links"); ok {
		hostConfig.Links = stringSetToStringSlice(v.(*schema.Set))
	}

	if v, ok := d.GetOk("memory"); ok {
		hostConfig.Memory = int64(v.(int)) * 1024 * 1024
	}

	if v, ok := d.GetOk("memory_swap"); ok {
		swap := int64(v.(int))
		if swap > 0 {
			swap = swap * 1024 * 1024
		}
		hostConfig.MemorySwap = swap
	}

	if v, ok := d.GetOk("cpu_shares"); ok {
		hostConfig.CPUShares = int64(v.(int))
	}

	if v, ok := d.GetOk("log_opts"); ok {
		hostConfig.LogConfig.Config = mapTypeMapValsToString(v.(map[string]interface{}))
	}

	if v, ok := d.GetOk("network_mode"); ok {
		hostConfig.NetworkMode = v
	}

	createOpts.HostConfig = hostConfig

	var retContainer *dc.Container
	if retContainer, err = client.CreateContainer(createOpts); err != nil {
		return fmt.Errorf("Unable to create container: %s", err)
	}
	if retContainer == nil {
		return fmt.Errorf("Returned container is nil")
	}

	d.SetId(retContainer.ID)

	creationTime = time.Now()
	if err := client.StartContainer(retContainer.ID, hostConfig); err != nil {
		return fmt.Errorf("Unable to start container: %s", err)
	}

	return resourceDockerContainerRead(d, meta)
}

func resourceDockerContainerRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*dc.Client)

	apiContainer, err := fetchDockerContainer(d.Id(), client)
	if err != nil {
		return err
	}
	if apiContainer == nil {
		// This container doesn't exist anymore
		d.SetId("")
		return nil
	}

	var container *dc.Container

	loops := 1 // if it hasn't just been created, don't delay
	if !creationTime.IsZero() {
		loops = 30 // with 500ms spacing, 15 seconds; ought to be plenty
	}
	sleepTime := 500 * time.Millisecond

	for i := loops; i > 0; i-- {
		container, err = client.InspectContainer(apiContainer.ID)
		if err != nil {
			return fmt.Errorf("Error inspecting container %s: %s", apiContainer.ID, err)
		}

		if container.State.Running ||
			!container.State.Running && !d.Get("must_run").(bool) {
			break
		}

		if creationTime.IsZero() { // We didn't just create it, so don't wait around
			return resourceDockerContainerDelete(d, meta)
		}

		if container.State.FinishedAt.After(creationTime) {
			// It exited immediately, so error out so dependent containers
			// aren't started
			resourceDockerContainerDelete(d, meta)
			return fmt.Errorf("Container %s exited after creation, error was: %s", apiContainer.ID, container.State.Error)
		}

		time.Sleep(sleepTime)
	}

	// Handle the case of the for loop above running its course
	if !container.State.Running && d.Get("must_run").(bool) {
		resourceDockerContainerDelete(d, meta)
		return fmt.Errorf("Container %s failed to be in running state", apiContainer.ID)
	}

	// Read Network Settings
	if container.NetworkSettings != nil {
		d.Set("ip_address", container.NetworkSettings.IPAddress)
		d.Set("ip_prefix_length", container.NetworkSettings.IPPrefixLen)
		d.Set("gateway", container.NetworkSettings.Gateway)
		d.Set("bridge", container.NetworkSettings.Bridge)
	}

	return nil
}

func resourceDockerContainerUpdate(d *schema.ResourceData, meta interface{}) error {
	return nil
}

func resourceDockerContainerDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*dc.Client)

	removeOpts := dc.RemoveContainerOptions{
		ID:            d.Id(),
		RemoveVolumes: true,
		Force:         true,
	}

	if err := client.RemoveContainer(removeOpts); err != nil {
		return fmt.Errorf("Error deleting container %s: %s", d.Id(), err)
	}

	d.SetId("")
	return nil
}

func stringListToStringSlice(stringList []interface{}) []string {
	ret := []string{}
	for _, v := range stringList {
		ret = append(ret, v.(string))
	}
	return ret
}

func stringSetToStringSlice(stringSet *schema.Set) []string {
	ret := []string{}
	if stringSet == nil {
		return ret
	}
	for _, envVal := range stringSet.List() {
		ret = append(ret, envVal.(string))
	}
	return ret
}

func mapTypeMapValsToString(typeMap map[string]interface{}) map[string]string {
	mapped := make(map[string]string, len(typeMap))
	for k, v := range typeMap {
		mapped[k] = v.(string)
	}
	return mapped
}

func fetchDockerContainer(ID string, client *dc.Client) (*dc.APIContainers, error) {
	apiContainers, err := client.ListContainers(dc.ListContainersOptions{All: true})

	if err != nil {
		return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err)
	}

	for _, apiContainer := range apiContainers {
		if apiContainer.ID == ID {
			return &apiContainer, nil
		}
	}

	return nil, nil
}

func portSetToDockerPorts(ports *schema.Set) (map[dc.Port]struct{}, map[dc.Port][]dc.PortBinding) {
	retExposedPorts := map[dc.Port]struct{}{}
	retPortBindings := map[dc.Port][]dc.PortBinding{}

	for _, portInt := range ports.List() {
		port := portInt.(map[string]interface{})
		internal := port["internal"].(int)
		protocol := port["protocol"].(string)

		exposedPort := dc.Port(strconv.Itoa(internal) + "/" + protocol)
		retExposedPorts[exposedPort] = struct{}{}

		external, extOk := port["external"].(int)
		ip, ipOk := port["ip"].(string)

		if extOk {
			portBinding := dc.PortBinding{
				HostPort: strconv.Itoa(external),
			}
			if ipOk {
				portBinding.HostIP = ip
			}
			retPortBindings[exposedPort] = append(retPortBindings[exposedPort], portBinding)
		}
	}

	return retExposedPorts, retPortBindings
}

func volumeSetToDockerVolumes(volumes *schema.Set) (map[string]struct{}, []string, []string, error) {
	retVolumeMap := map[string]struct{}{}
	retHostConfigBinds := []string{}
	retVolumeFromContainers := []string{}

	for _, volumeInt := range volumes.List() {
		volume := volumeInt.(map[string]interface{})
		fromContainer := volume["from_container"].(string)
		containerPath := volume["container_path"].(string)
		hostPath := volume["host_path"].(string)
		readOnly := volume["read_only"].(bool)

		switch {
		case len(fromContainer) == 0 && len(containerPath) == 0:
			return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Volume entry without container path or source container")
		case len(fromContainer) != 0 && len(containerPath) != 0:
			return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Both a container and a path specified in a volume entry")
		case len(fromContainer) != 0:
			retVolumeFromContainers = append(retVolumeFromContainers, fromContainer)
		case len(hostPath) != 0:
			readWrite := "rw"
			if readOnly {
				readWrite = "ro"
			}
			retVolumeMap[containerPath] = struct{}{}
			retHostConfigBinds = append(retHostConfigBinds, hostPath+":"+containerPath+":"+readWrite)
		default:
			retVolumeMap[containerPath] = struct{}{}
		}
	}

	return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, nil
}
<commit_msg>Convert v to string<commit_after>package docker

import (
	"errors"
	"fmt"
	"strconv"
	"time"

	dc "github.com/fsouza/go-dockerclient"
	"github.com/hashicorp/terraform/helper/schema"
)

var (
	creationTime time.Time
)

func resourceDockerContainerCreate(d *schema.ResourceData, meta interface{}) error {
	var err error
	client := meta.(*dc.Client)

	var data Data
	if err := fetchLocalImages(&data, client); err != nil {
		return err
	}

	image := d.Get("image").(string)
	if _, ok := data.DockerImages[image]; !ok {
		if _, ok := data.DockerImages[image+":latest"]; !ok {
			return fmt.Errorf("Unable to find image %s", image)
		}
		image = image + ":latest"
	}

	// The awesome, wonderful, splendiferous, sensical
	// Docker API now lets you specify a HostConfig in
	// CreateContainerOptions, but in my testing it still only
	// actually applies HostConfig options set in StartContainer.
	// How cool is that?
	createOpts := dc.CreateContainerOptions{
		Name: d.Get("name").(string),
		Config: &dc.Config{
			Image:      image,
			Hostname:   d.Get("hostname").(string),
			Domainname: d.Get("domainname").(string),
		},
	}

	if v, ok := d.GetOk("env"); ok {
		createOpts.Config.Env = stringSetToStringSlice(v.(*schema.Set))
	}

	if v, ok := d.GetOk("command"); ok {
		createOpts.Config.Cmd = stringListToStringSlice(v.([]interface{}))
	}

	if v, ok := d.GetOk("entrypoint"); ok {
		createOpts.Config.Entrypoint = stringListToStringSlice(v.([]interface{}))
	}

	exposedPorts := map[dc.Port]struct{}{}
	portBindings := map[dc.Port][]dc.PortBinding{}

	if v, ok := d.GetOk("ports"); ok {
		exposedPorts, portBindings = portSetToDockerPorts(v.(*schema.Set))
	}
	if len(exposedPorts) != 0 {
		createOpts.Config.ExposedPorts = exposedPorts
	}

	volumes := map[string]struct{}{}
	binds := []string{}
	volumesFrom := []string{}

	if v, ok := d.GetOk("volumes"); ok {
		volumes, binds, volumesFrom, err = volumeSetToDockerVolumes(v.(*schema.Set))
		if err != nil {
			return fmt.Errorf("Unable to parse volumes: %s", err)
		}
	}
	if len(volumes) != 0 {
		createOpts.Config.Volumes = volumes
	}

	if v, ok := d.GetOk("labels"); ok {
		createOpts.Config.Labels = mapTypeMapValsToString(v.(map[string]interface{}))
	}

	hostConfig := &dc.HostConfig{
		Privileged:      d.Get("privileged").(bool),
		PublishAllPorts: d.Get("publish_all_ports").(bool),
		RestartPolicy: dc.RestartPolicy{
			Name:              d.Get("restart").(string),
			MaximumRetryCount: d.Get("max_retry_count").(int),
		},
		LogConfig: dc.LogConfig{
			Type: d.Get("log_driver").(string),
		},
	}

	if len(portBindings) != 0 {
		hostConfig.PortBindings = portBindings
	}

	if len(binds) != 0 {
		hostConfig.Binds = binds
	}
	if len(volumesFrom) != 0 {
		hostConfig.VolumesFrom = volumesFrom
	}

	if v, ok := d.GetOk("dns"); ok {
		hostConfig.DNS = stringSetToStringSlice(v.(*schema.Set))
	}

	if v, ok := d.GetOk("links"); ok {
		hostConfig.Links = stringSetToStringSlice(v.(*schema.Set))
	}

	if v, ok := d.GetOk("memory"); ok {
		hostConfig.Memory = int64(v.(int)) * 1024 * 1024
	}

	if v, ok := d.GetOk("memory_swap"); ok {
		swap := int64(v.(int))
		if swap > 0 {
			swap = swap * 1024 * 1024
		}
		hostConfig.MemorySwap = swap
	}

	if v, ok := d.GetOk("cpu_shares"); ok {
		hostConfig.CPUShares = int64(v.(int))
	}

	if v, ok := d.GetOk("log_opts"); ok {
		hostConfig.LogConfig.Config = mapTypeMapValsToString(v.(map[string]interface{}))
	}

	if v, ok := d.GetOk("network_mode"); ok {
		hostConfig.NetworkMode = v.(string)
	}

	createOpts.HostConfig = hostConfig

	var retContainer *dc.Container
	if retContainer, err = client.CreateContainer(createOpts); err != nil {
		return fmt.Errorf("Unable to create container: %s", err)
	}
	if retContainer == nil {
		return fmt.Errorf("Returned container is nil")
	}

	d.SetId(retContainer.ID)

	creationTime = time.Now()
	if err := client.StartContainer(retContainer.ID, hostConfig); err != nil {
		return fmt.Errorf("Unable to start container: %s", err)
	}

	return resourceDockerContainerRead(d, meta)
}

func resourceDockerContainerRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*dc.Client)

	apiContainer, err := fetchDockerContainer(d.Id(), client)
	if err != nil {
		return err
	}
	if apiContainer == nil {
		// This container doesn't exist anymore
		d.SetId("")
		return nil
	}

	var container *dc.Container

	loops := 1 // if it hasn't just been created, don't delay
	if !creationTime.IsZero() {
		loops = 30 // with 500ms spacing, 15 seconds; ought to be plenty
	}
	sleepTime := 500 * time.Millisecond

	for i := loops; i > 0; i-- {
		container, err = client.InspectContainer(apiContainer.ID)
		if err != nil {
			return fmt.Errorf("Error inspecting container %s: %s", apiContainer.ID, err)
		}

		if container.State.Running ||
			!container.State.Running && !d.Get("must_run").(bool) {
			break
		}

		if creationTime.IsZero() { // We didn't just create it, so don't wait around
			return resourceDockerContainerDelete(d, meta)
		}

		if container.State.FinishedAt.After(creationTime) {
			// It exited immediately, so error out so dependent containers
			// aren't started
			resourceDockerContainerDelete(d, meta)
			return fmt.Errorf("Container %s exited after creation, error was: %s", apiContainer.ID, container.State.Error)
		}

		time.Sleep(sleepTime)
	}

	// Handle the case of the for loop above running its course
	if !container.State.Running && d.Get("must_run").(bool) {
		resourceDockerContainerDelete(d, meta)
		return fmt.Errorf("Container %s failed to be in running state", apiContainer.ID)
	}

	// Read Network Settings
	if container.NetworkSettings != nil {
		d.Set("ip_address", container.NetworkSettings.IPAddress)
		d.Set("ip_prefix_length", container.NetworkSettings.IPPrefixLen)
		d.Set("gateway", container.NetworkSettings.Gateway)
		d.Set("bridge", container.NetworkSettings.Bridge)
	}

	return nil
}

func resourceDockerContainerUpdate(d *schema.ResourceData, meta interface{}) error {
	return nil
}

func resourceDockerContainerDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*dc.Client)

	removeOpts := dc.RemoveContainerOptions{
		ID:            d.Id(),
		RemoveVolumes: true,
		Force:         true,
	}

	if err := client.RemoveContainer(removeOpts); err != nil {
		return fmt.Errorf("Error deleting container %s: %s", d.Id(), err)
	}

	d.SetId("")
	return nil
}

func stringListToStringSlice(stringList []interface{}) []string {
	ret := []string{}
	for _, v := range stringList {
		ret = append(ret, v.(string))
	}
	return ret
}

func stringSetToStringSlice(stringSet *schema.Set) []string {
	ret := []string{}
	if stringSet == nil {
		return ret
	}
	for _, envVal := range stringSet.List() {
		ret = append(ret, envVal.(string))
	}
	return ret
}

func mapTypeMapValsToString(typeMap map[string]interface{}) map[string]string {
	mapped := make(map[string]string, len(typeMap))
	for k, v := range typeMap {
		mapped[k] = v.(string)
	}
	return mapped
}

func fetchDockerContainer(ID string, client *dc.Client) (*dc.APIContainers, error) {
	apiContainers, err := client.ListContainers(dc.ListContainersOptions{All: true})

	if err != nil {
		return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err)
	}

	for _, apiContainer := range apiContainers {
		if apiContainer.ID == ID {
			return &apiContainer, nil
		}
	}

	return nil, nil
}

func portSetToDockerPorts(ports *schema.Set) (map[dc.Port]struct{}, map[dc.Port][]dc.PortBinding) {
	retExposedPorts := map[dc.Port]struct{}{}
	retPortBindings := map[dc.Port][]dc.PortBinding{}

	for _, portInt := range ports.List() {
		port := portInt.(map[string]interface{})
		internal := port["internal"].(int)
		protocol := port["protocol"].(string)

		exposedPort := dc.Port(strconv.Itoa(internal) + "/" + protocol)
		retExposedPorts[exposedPort] = struct{}{}

		external, extOk := port["external"].(int)
		ip, ipOk := port["ip"].(string)

		if extOk {
			portBinding := dc.PortBinding{
				HostPort: strconv.Itoa(external),
			}
			if ipOk {
				portBinding.HostIP = ip
			}
			retPortBindings[exposedPort] = append(retPortBindings[exposedPort], portBinding)
		}
	}

	return retExposedPorts, retPortBindings
}

func volumeSetToDockerVolumes(volumes *schema.Set) (map[string]struct{}, []string, []string, error) {
	retVolumeMap := map[string]struct{}{}
	retHostConfigBinds := []string{}
	retVolumeFromContainers := []string{}

	for _, volumeInt := range volumes.List() {
		volume := volumeInt.(map[string]interface{})
		fromContainer := volume["from_container"].(string)
		containerPath := volume["container_path"].(string)
		hostPath := volume["host_path"].(string)
		readOnly := volume["read_only"].(bool)

		switch {
		case len(fromContainer) == 0 && len(containerPath) == 0:
			return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Volume entry without container path or source container")
		case len(fromContainer) != 0 && len(containerPath) != 0:
			return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, errors.New("Both a container and a path specified in a volume entry")
		case len(fromContainer) != 0:
			retVolumeFromContainers = append(retVolumeFromContainers, fromContainer)
		case len(hostPath) != 0:
			readWrite := "rw"
			if readOnly {
				readWrite = "ro"
			}
			retVolumeMap[containerPath] = struct{}{}
			retHostConfigBinds = append(retHostConfigBinds, hostPath+":"+containerPath+":"+readWrite)
		default:
			retVolumeMap[containerPath] = struct{}{}
		}
	}

	return retVolumeMap, retHostConfigBinds, retVolumeFromContainers, nil
}
<|endoftext|>


<commit_before>// Package buspirate interfaces with the binary mode of the BusPirate.
// http://dangerousprototypes.com/docs/Bus_Pirate
package buspirate

import (
	"fmt"
	"github.com/pkg/term"
	"time"
)

// Open opens a connection to a BusPirate module and places it into binary mode.
func Open(dev string) (*BusPirate, error) {
	t, err := term.Open(dev, term.Speed(115200), term.RawMode)
	if err != nil {
		return nil, err
	}
	bp := BusPirate{term: t}
	return &bp, bp.enterBinaryMode()
}

// BusPirate represents a connection to a remote BusPirate device.
type BusPirate struct {
	term *term.Term
}

// enterBinaryMode resets the BusPirate and enters binary mode.
// http://dangerousprototypes.com/docs/Bitbang
func (bp *BusPirate) enterBinaryMode() error {
	bp.term.Flush()
	bp.term.Write([]byte{'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'})
	const n = 30
	for i := 0; i < n; i++ {
		// send binary reset
		bp.term.Write([]byte{0x00})
		time.Sleep(10 * time.Millisecond)
		n, err := bp.term.Available()
		if err != nil {
			return err
		}
		buf := make([]byte, n)
		_, err = bp.term.Read(buf)
		if err != nil {
			return err
		}
		if string(buf) == "BBIO1" {
			return nil
		}
	}
	return fmt.Errorf("could not enter binary mode")
}

// PowerOn turns on the 5v and 3v3 regulators.
func (bp *BusPirate) PowerOn() {
	buf := []byte{0xc0}
	bp.term.Write(buf)
	bp.term.Read(buf)
}

// PowerOff turns off the 5v and 3v3 refulators.
func (bp *BusPirate) PowerOff() {
	buf := []byte{0x80}
	bp.term.Write(buf)
	bp.term.Read(buf)
}

// SetPWM enables PWM output on the AUX pin with the specified duty cycle.
// duty is clamped between [0, 1].
func (bp *BusPirate) SetPWM(duty float64) {
	if duty > 1.0 {
		duty = 1.0
	}
	if duty < 0.0 {
		duty = 0.0
	}
	PRy := uint16(0x3e7f)
	OCR := uint16(float64(PRy) * duty)
	buf := []byte{0x12, 0x00, uint8(OCR >> 8), uint8(OCR), uint8(PRy >> 8), uint8(PRy)}
	bp.term.Write(buf)
	bp.term.Read(buf[:1])
}
<commit_msg>how many typos am I going to make ?<commit_after>// Package buspirate interfaces with the binary mode of the BusPirate.
// http://dangerousprototypes.com/docs/Bus_Pirate
package buspirate

import (
	"fmt"
	"github.com/pkg/term"
	"time"
)

// Open opens a connection to a BusPirate module and places it into binary mode.
func Open(dev string) (*BusPirate, error) {
	t, err := term.Open(dev, term.Speed(115200), term.RawMode)
	if err != nil {
		return nil, err
	}
	bp := BusPirate{term: t}
	return &bp, bp.enterBinaryMode()
}

// BusPirate represents a connection to a remote BusPirate device.
type BusPirate struct {
	term *term.Term
}

// enterBinaryMode resets the BusPirate and enters binary mode.
// http://dangerousprototypes.com/docs/Bitbang
func (bp *BusPirate) enterBinaryMode() error {
	bp.term.Flush()
	bp.term.Write([]byte{'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'})
	const n = 30
	for i := 0; i < n; i++ {
		// send binary reset
		bp.term.Write([]byte{0x00})
		time.Sleep(10 * time.Millisecond)
		n, err := bp.term.Available()
		if err != nil {
			return err
		}
		buf := make([]byte, n)
		_, err = bp.term.Read(buf)
		if err != nil {
			return err
		}
		if string(buf) == "BBIO1" {
			return nil
		}
	}
	return fmt.Errorf("could not enter binary mode")
}

// PowerOn turns on the 5v and 3v3 regulators.
func (bp *BusPirate) PowerOn() {
	buf := []byte{0xc0}
	bp.term.Write(buf)
	bp.term.Read(buf)
}

// PowerOff turns off the 5v and 3v3 regulators.
func (bp *BusPirate) PowerOff() {
	buf := []byte{0x80}
	bp.term.Write(buf)
	bp.term.Read(buf)
}

// SetPWM enables PWM output on the AUX pin with the specified duty cycle.
// duty is clamped between [0, 1].
func (bp *BusPirate) SetPWM(duty float64) {
	if duty > 1.0 {
		duty = 1.0
	}
	if duty < 0.0 {
		duty = 0.0
	}
	PRy := uint16(0x3e7f)
	OCR := uint16(float64(PRy) * duty)
	buf := []byte{0x12, 0x00, uint8(OCR >> 8), uint8(OCR), uint8(PRy >> 8), uint8(PRy)}
	bp.term.Write(buf)
	bp.term.Read(buf[:1])
}
<|endoftext|>


<commit_before>// Package tt supports table-driven tests with little boilerplate.
//
// See the test case for this package for example usage.
package tt

import (
	"bytes"
	"fmt"
	"reflect"
)

// Table represents a test table.
type Table []*Case

// Case represents a test case. It is created by the C function, and offers
// setters that augment and return itself; those calls can be chained like
// C(...).Rets(...).
type Case struct {
	args         []interface{}
	retsMatchers [][]interface{}
}

// Args returns a new Case with the given arguments.
func Args(args ...interface{}) *Case {
	return &Case{args: args}
}

// Rets modifies the test case so that it requires the return values to match
// the given values. It returns the receiver.
func (c *Case) Rets(matchers ...interface{}) *Case {
	c.retsMatchers = append(c.retsMatchers, matchers)
	return c
}

func match(matchers, actual []interface{}) bool {
	for i, matcher := range matchers {
		// TODO: Support custom matching strategy
		if !reflect.DeepEqual(matcher, actual[i]) {
			return false
		}
	}
	return true
}

// FnToTest describes a function to test.
type FnToTest struct {
	name    string
	body    interface{}
	argsFmt string
	retsFmt string
}

// Fn makes a new FnToTest with the given function name and body.
func Fn(name string, body interface{}) *FnToTest {
	return &FnToTest{name: name, body: body}
}

// ArgsFmt sets the string for formatting arguments in test error messages, and
// return fn itself.
func (fn *FnToTest) ArgsFmt(s string) *FnToTest {
	fn.argsFmt = s
	return fn
}

// RetsFmt sets the string for formatting return values in test error messages,
// and return fn itself.
func (fn *FnToTest) RetsFmt(s string) *FnToTest {
	fn.retsFmt = s
	return fn
}

// T is the interface for accessing testing.T.
type T interface {
	Errorf(format string, args ...interface{})
}

// Test tests a function against test cases.
func Test(t T, fn *FnToTest, tests Table) {
	for _, test := range tests {
		rets := call(fn.body, test.args)
		for _, retsMatcher := range test.retsMatchers {
			if !match(retsMatcher, rets) {
				var argsString, retsString, wantRetsString string
				if fn.argsFmt == "" {
					argsString = sprintArgs(test.args...)
				} else {
					argsString = fmt.Sprintf(fn.argsFmt, test.args...)
				}
				if fn.retsFmt == "" {
					retsString = sprintRets(rets...)
					wantRetsString = sprintRets(retsMatcher...)
				} else {
					retsString = fmt.Sprintf(fn.retsFmt, rets...)
					wantRetsString = fmt.Sprintf(fn.retsFmt, retsMatcher...)
				}
				t.Errorf("%s(%s) -> %s, want %s", fn.name, argsString, retsString, wantRetsString)
			}
		}
	}
}

func sprintArgs(args ...interface{}) string {
	return sprintCommaDelimited(args...)
}

func sprintRets(rets ...interface{}) string {
	if len(rets) == 1 {
		return fmt.Sprint(rets[0])
	}
	return "(" + sprintCommaDelimited(rets...) + ")"
}

func sprintCommaDelimited(args ...interface{}) string {
	var b bytes.Buffer
	for i, arg := range args {
		if i > 0 {
			b.WriteString(", ")
		}
		fmt.Fprint(&b, arg)
	}
	return b.String()
}

func call(fn interface{}, args []interface{}) []interface{} {
	argsReflect := make([]reflect.Value, len(args))
	for i, arg := range args {
		argsReflect[i] = reflect.ValueOf(arg)
	}
	retsReflect := reflect.ValueOf(fn).Call(argsReflect)
	rets := make([]interface{}, len(retsReflect))
	for i, retReflect := range retsReflect {
		rets[i] = retReflect.Interface()
	}
	return rets
}
<commit_msg>tt: Support custom return value matching.<commit_after>// Package tt supports table-driven tests with little boilerplate.
//
// See the test case for this package for example usage.
package tt

import (
	"bytes"
	"fmt"
	"reflect"
)

// Table represents a test table.
type Table []*Case

// Case represents a test case. It is created by the C function, and offers
// setters that augment and return itself; those calls can be chained like
// C(...).Rets(...).
type Case struct {
	args         []interface{}
	retsMatchers [][]interface{}
}

// Args returns a new Case with the given arguments.
func Args(args ...interface{}) *Case {
	return &Case{args: args}
}

// Rets modifies the test case so that it requires the return values to match
// the given values. It returns the receiver. The arguments may implement the
// Matcher interface, in which case its Match method is called with the actual
// return value. Otherwise, reflect.DeepEqual is used to determine matches.
func (c *Case) Rets(matchers ...interface{}) *Case {
	c.retsMatchers = append(c.retsMatchers, matchers)
	return c
}

// FnToTest describes a function to test.
type FnToTest struct {
	name    string
	body    interface{}
	argsFmt string
	retsFmt string
}

// Fn makes a new FnToTest with the given function name and body.
func Fn(name string, body interface{}) *FnToTest {
	return &FnToTest{name: name, body: body}
}

// ArgsFmt sets the string for formatting arguments in test error messages, and
// return fn itself.
func (fn *FnToTest) ArgsFmt(s string) *FnToTest {
	fn.argsFmt = s
	return fn
}

// RetsFmt sets the string for formatting return values in test error messages,
// and return fn itself.
func (fn *FnToTest) RetsFmt(s string) *FnToTest {
	fn.retsFmt = s
	return fn
}

// T is the interface for accessing testing.T.
type T interface {
	Errorf(format string, args ...interface{})
}

// Test tests a function against test cases.
func Test(t T, fn *FnToTest, tests Table) {
	for _, test := range tests {
		rets := call(fn.body, test.args)
		for _, retsMatcher := range test.retsMatchers {
			if !match(retsMatcher, rets) {
				var argsString, retsString, wantRetsString string
				if fn.argsFmt == "" {
					argsString = sprintArgs(test.args...)
				} else {
					argsString = fmt.Sprintf(fn.argsFmt, test.args...)
				}
				if fn.retsFmt == "" {
					retsString = sprintRets(rets...)
					wantRetsString = sprintRets(retsMatcher...)
				} else {
					retsString = fmt.Sprintf(fn.retsFmt, rets...)
					wantRetsString = fmt.Sprintf(fn.retsFmt, retsMatcher...)
				}
				t.Errorf("%s(%s) -> %s, want %s", fn.name, argsString, retsString, wantRetsString)
			}
		}
	}
}

// RetValue is an empty interface used in the Matcher interface.
type RetValue interface{}

// Matcher wraps the Match method.
type Matcher interface {
	// Match reports whether a return value is considered a match. The argument
	// is of type RetValue so that it cannot be implemented accidentally.
	Match(RetValue) bool
}

func match(matchers, actual []interface{}) bool {
	for i, matcher := range matchers {
		if !matchOne(matcher, actual[i]) {
			return false
		}
	}
	return true
}

func matchOne(m, a interface{}) bool {
	if m, ok := m.(Matcher); ok {
		return m.Match(a)
	}
	return reflect.DeepEqual(m, a)
}

func sprintArgs(args ...interface{}) string {
	return sprintCommaDelimited(args...)
}

func sprintRets(rets ...interface{}) string {
	if len(rets) == 1 {
		return fmt.Sprint(rets[0])
	}
	return "(" + sprintCommaDelimited(rets...) + ")"
}

func sprintCommaDelimited(args ...interface{}) string {
	var b bytes.Buffer
	for i, arg := range args {
		if i > 0 {
			b.WriteString(", ")
		}
		fmt.Fprint(&b, arg)
	}
	return b.String()
}

func call(fn interface{}, args []interface{}) []interface{} {
	argsReflect := make([]reflect.Value, len(args))
	for i, arg := range args {
		argsReflect[i] = reflect.ValueOf(arg)
	}
	retsReflect := reflect.ValueOf(fn).Call(argsReflect)
	rets := make([]interface{}, len(retsReflect))
	for i, retReflect := range retsReflect {
		rets[i] = retReflect.Interface()
	}
	return rets
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. 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 fuseops contains implementations of the fuse.Op interface that may
// be returned by fuse.Connection.ReadOp. See documentation in that package for
// more.
package fuseops

import (
	"github.com/jacobsa/bazilfuse"
	"golang.org/x/net/context"
)

// Convert the supplied bazilfuse request struct to an Op, returning nil if it
// is unknown.
//
// This function is an implementation detail of the fuse package, and must not
// be called by anyone else.
func Convert(r bazilfuse.Request) (o Op) {
	var co *commonOp

	switch r.(type) {
	case *bazilfuse.InitRequest:
		to := &InitOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &LookUpInodeOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &GetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &SetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &ForgetInodeOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &MkDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &CreateFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &RmDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &UnlinkOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &OpenDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &ReadDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &ReleaseDirHandleOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &OpenFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &ReadFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &WriteFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &SyncFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &FlushFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.InitRequest:
		to := &ReleaseFileHandleOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	default:
		return
	}

	co.init(r)
	return
}

// A helper for embedding common behavior.
type commonOp struct {
	ctx context.Context
	r   bazilfuse.Request
}

func (o *commonOp) init(r bazilfuse.Request) {
	o.ctx = context.Background()
	o.r = r
}

func (o *commonOp) Header() OpHeader {
	bh := o.r.Hdr()
	return OpHeader{
		Uid: bh.Uid,
		Gid: bh.Gid,
	}
}

func (o *commonOp) Context() context.Context {
	return o.ctx
}

func (o *commonOp) respondErr(err error) {
	if err != nil {
		panic("Expect non-nil here.")
	}

	o.r.RespondError(err)
}
<commit_msg>Fixed switch cases.<commit_after>// Copyright 2015 Google Inc. 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 fuseops contains implementations of the fuse.Op interface that may
// be returned by fuse.Connection.ReadOp. See documentation in that package for
// more.
package fuseops

import (
	"github.com/jacobsa/bazilfuse"
	"golang.org/x/net/context"
)

// Convert the supplied bazilfuse request struct to an Op, returning nil if it
// is unknown.
//
// This function is an implementation detail of the fuse package, and must not
// be called by anyone else.
func Convert(r bazilfuse.Request) (o Op) {
	var co *commonOp

	switch r.(type) {
	case *bazilfuse.InitRequest:
		to := &InitOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.LookupRequest:
		to := &LookUpInodeOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.GetattrRequest:
		to := &GetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.SetattrRequest:
		to := &SetInodeAttributesOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.MkdirRequest:
		to := &MkDirOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.CreateRequest:
		to := &CreateFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.RemoveRequest:
		//TODO

	case *bazilfuse.OpenRequest:
		//TODO

	case *bazilfuse.ReadRequest:
		//TODO

	case *bazilfuse.ReleaseRequest:
		//TODO

	case *bazilfuse.WriteRequest:
		to := &WriteFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.FsyncRequest:
		to := &SyncFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	case *bazilfuse.FlushRequest:
		to := &FlushFileOp{
		//TODO
		}
		o = to
		co = &to.commonOp

	default:
		return
	}

	co.init(r)
	return
}

// A helper for embedding common behavior.
type commonOp struct {
	ctx context.Context
	r   bazilfuse.Request
}

func (o *commonOp) init(r bazilfuse.Request) {
	o.ctx = context.Background()
	o.r = r
}

func (o *commonOp) Header() OpHeader {
	bh := o.r.Hdr()
	return OpHeader{
		Uid: bh.Uid,
		Gid: bh.Gid,
	}
}

func (o *commonOp) Context() context.Context {
	return o.ctx
}

func (o *commonOp) respondErr(err error) {
	if err != nil {
		panic("Expect non-nil here.")
	}

	o.r.RespondError(err)
}
<|endoftext|>


<commit_before>package go_utils

import (
	"fmt"
	"log"
	"reflect"
	"strings"
	"strconv"
)
//------------------------------------------------
//               Type Conversions
//------------------------------------------------

// ToInt64 converts the argument to a int64
// throws panic if argument is non-numeric parameter
func ToInt64(a interface{}) int64 {
	switch t := a.(type) {
	case string:
		if strings.Contains(t, ".") {
			fpNum, err := strconv.ParseFloat(t, 64)
			if err != nil {
				log.Println(StringConversionError{})
				return 0
			}
			return int64(fpNum)
		} else {
			num, err := ConvStringToInt(a)
			if err != nil {
				panic(fmt.Sprintf("Error converting string!  Got <%T> %#v", a, a))
			}
			return int64(num)
		}
	}
	if IsInteger(a) {
		return reflect.ValueOf(a).Int()
	} else if IsUnsignedInteger(a) {
		return int64(reflect.ValueOf(a).Uint())
	} else if IsFloat(a) {
		return int64(reflect.ValueOf(a).Float())
	} else {
		panic(fmt.Sprintf("Expected a number!  Got <%T> %#v", a, a))
	}
}

// ToFloat converts the argument to a float64
// throws panic if argument is non-numeric parameter
func ToFloat(a interface{}) float64 {
	if IsInteger(a) {
		return float64(reflect.ValueOf(a).Int())
	} else if IsUnsignedInteger(a) {
		return float64(reflect.ValueOf(a).Uint())
	} else if IsFloat(a) {
		return reflect.ValueOf(a).Float()
	} else {
		panic(fmt.Sprintf("Expected a number!  Got <%T> %#v", a, a))
	}
}

// ToUnsignedInteger converts the argument to a uint64
// throws panic if argument is non-numeric parameter
func ToUnsignedInteger(a interface{}) uint64 {
	if IsInteger(a) {
		return uint64(reflect.ValueOf(a).Int())
	} else if IsUnsignedInteger(a) {
		return reflect.ValueOf(a).Uint()
	} else if IsFloat(a) {
		return uint64(reflect.ValueOf(a).Float())
	} else {
		panic(fmt.Sprintf("Expected a number!  Got <%T> %#v", a, a))
	}
}

//------------------------------------------------
//               Type Equality
//------------------------------------------------

func IsArray(a interface{}) bool {
	if a == nil {
		return false
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.Array:
		return true
	default:
		return false
	}
}

func IsBool(a interface{}) bool {
	return reflect.TypeOf(a).Kind() == reflect.Bool
}

func IsChan(a interface{}) bool {
	if IsNil(a) {
		return false
	}
	return reflect.TypeOf(a).Kind() == reflect.Chan
}

func IsError(a interface{}) bool {
	_, ok := a.(error)
	return ok
}

func IsFloat(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Float32 && kind <= reflect.Float64
}

func IsInteger(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Int && kind <= reflect.Int64
}

func IsMap(a interface{}) bool {
	if a == nil {
		return false
	}
	return reflect.TypeOf(a).Kind() == reflect.Map
}

func IsNil(a interface{}) bool {
	if a == nil {
		return true
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
		return reflect.ValueOf(a).IsNil()
	}
	return false
}

func IsNumber(a interface{}) bool {
	if a == nil {
		return false
	}
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Int  && kind <= reflect.Float64
}

func IsSlice(a interface{}) bool {
	if a == nil {
		return false
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.Slice:
		return true
	default:
		return false
	}
}

func IsString(a interface{}) bool {
	if a == nil {
		return false
	}
	return reflect.TypeOf(a).Kind() == reflect.String
}

func IsUnsignedInteger(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Uint && kind <= reflect.Uint64
}

//------------------------------------------------
//                 Type Helpers
//------------------------------------------------

// LengthOf returns the number if items in argument
func LengthOf(a interface{}) int {
	if a == nil {
		return 0
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.String, reflect.Slice, reflect.Map, reflect.Chan, reflect.Array:
		return reflect.ValueOf(a).Len()
	default:
		return 0
	}
}

// ToString converts the value to a string
func ToString(a interface{}) string {
	return fmt.Sprint(a)
}

// TypeOf returns the reflection Type of the value in the interface{}.
// TypeOf(nil) returns nil.
func TypeOf(a interface{}) string {
	return fmt.Sprintf("%v", reflect.TypeOf(a))
}
<commit_msg>add IsInt and IsUint<commit_after>package go_utils

import (
	"fmt"
	"log"
	"reflect"
	"strings"
	"strconv"
)
//------------------------------------------------
//               Type Conversions
//------------------------------------------------

// ToInt64 converts the argument to a int64
// throws panic if argument is non-numeric parameter
func ToInt64(a interface{}) int64 {
	switch t := a.(type) {
	case string:
		if strings.Contains(t, ".") {
			fpNum, err := strconv.ParseFloat(t, 64)
			if err != nil {
				log.Println(StringConversionError{})
				return 0
			}
			return int64(fpNum)
		} else {
			num, err := ConvStringToInt(a)
			if err != nil {
				panic(fmt.Sprintf("Error converting string!  Got <%T> %#v", a, a))
			}
			return int64(num)
		}
	}
	if IsInteger(a) {
		return reflect.ValueOf(a).Int()
	} else if IsUnsignedInteger(a) {
		return int64(reflect.ValueOf(a).Uint())
	} else if IsFloat(a) {
		return int64(reflect.ValueOf(a).Float())
	} else {
		panic(fmt.Sprintf("Expected a number!  Got <%T> %#v", a, a))
	}
}

// ToFloat converts the argument to a float64
// throws panic if argument is non-numeric parameter
func ToFloat(a interface{}) float64 {
	if IsInteger(a) {
		return float64(reflect.ValueOf(a).Int())
	} else if IsUnsignedInteger(a) {
		return float64(reflect.ValueOf(a).Uint())
	} else if IsFloat(a) {
		return reflect.ValueOf(a).Float()
	} else {
		panic(fmt.Sprintf("Expected a number!  Got <%T> %#v", a, a))
	}
}

// ToUnsignedInteger converts the argument to a uint64
// throws panic if argument is non-numeric parameter
func ToUnsignedInteger(a interface{}) uint64 {
	if IsInteger(a) {
		return uint64(reflect.ValueOf(a).Int())
	} else if IsUnsignedInteger(a) {
		return reflect.ValueOf(a).Uint()
	} else if IsFloat(a) {
		return uint64(reflect.ValueOf(a).Float())
	} else {
		panic(fmt.Sprintf("Expected a number!  Got <%T> %#v", a, a))
	}
}

//------------------------------------------------
//               Type Equality
//------------------------------------------------

func IsArray(a interface{}) bool {
	if a == nil {
		return false
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.Array:
		return true
	default:
		return false
	}
}

func IsBool(a interface{}) bool {
	return reflect.TypeOf(a).Kind() == reflect.Bool
}

func IsChan(a interface{}) bool {
	if IsNil(a) {
		return false
	}
	return reflect.TypeOf(a).Kind() == reflect.Chan
}

func IsError(a interface{}) bool {
	_, ok := a.(error)
	return ok
}

func IsFloat(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Float32 && kind <= reflect.Float64
}

func IsInteger(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Int && kind <= reflect.Int64
}

func IsInt(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind == reflect.Int
}

func IsUint(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind == reflect.Uint
}

func IsMap(a interface{}) bool {
	if a == nil {
		return false
	}
	return reflect.TypeOf(a).Kind() == reflect.Map
}

func IsNil(a interface{}) bool {
	if a == nil {
		return true
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
		return reflect.ValueOf(a).IsNil()
	}
	return false
}

func IsNumber(a interface{}) bool {
	if a == nil {
		return false
	}
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Int  && kind <= reflect.Float64
}

func IsSlice(a interface{}) bool {
	if a == nil {
		return false
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.Slice:
		return true
	default:
		return false
	}
}

func IsString(a interface{}) bool {
	if a == nil {
		return false
	}
	return reflect.TypeOf(a).Kind() == reflect.String
}

func IsUnsignedInteger(a interface{}) bool {
	kind := reflect.TypeOf(a).Kind()
	return kind >= reflect.Uint && kind <= reflect.Uint64
}

//------------------------------------------------
//                 Type Helpers
//------------------------------------------------

// LengthOf returns the number if items in argument
func LengthOf(a interface{}) int {
	if a == nil {
		return 0
	}
	switch reflect.TypeOf(a).Kind() {
	case reflect.String, reflect.Slice, reflect.Map, reflect.Chan, reflect.Array:
		return reflect.ValueOf(a).Len()
	default:
		return 0
	}
}

// ToString converts the value to a string
func ToString(a interface{}) string {
	return fmt.Sprint(a)
}

// TypeOf returns the reflection Type of the value in the interface{}.
// TypeOf(nil) returns nil.
func TypeOf(a interface{}) string {
	return fmt.Sprintf("%v", reflect.TypeOf(a))
}
<|endoftext|>