<commit_before>package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"github.com/proshik/githubstatbot/api"
	"github.com/proshik/githubstatbot/github"
	"github.com/proshik/githubstatbot/storage"
	"github.com/proshik/githubstatbot/telegram"
	"golang.org/x/crypto/acme/autocert"
	"log"
	"net/http"
	"os"
	"time"
)

//For run:
//env PORT=8080 DB_PATH=/data/githubstatbot/boltdb.db GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= TELEGRAM_TOKEN= go run githubstatbot.go
func main() {
	flag.Parse()

	port := os.Getenv("PORT")
	if port == "" {
		log.Panic("Port is empty")
	}

	tlsDir := os.Getenv("TLS_DIR")

	path := os.Getenv("DB_PATH")
	if path == "" {
		log.Panic("DB path is empty")
	}

	clientID := os.Getenv("GITHUB_CLIENT_ID")
	clientSecret := os.Getenv("GITHUB_CLIENT_SECRET")
	if clientID == "" || clientSecret == "" {
		log.Panic("ClientId or clientSecret is empty")
	}

	telegramToken := os.Getenv("TELEGRAM_TOKEN")
	if telegramToken == "" {
		log.Panic("Telegram token is empty")
	}

	db := storage.New(path)
	stateStore := storage.NewStateStore()
	oAuth := github.NewOAuth(clientID, clientSecret)

	bot, err := telegram.NewBot(telegramToken, false, db, stateStore, oAuth)
	if err != nil {
		log.Panic(err)
	}
	go bot.ReadUpdates()

	handler := api.New(oAuth, db, stateStore, bot)
	router := httprouter.New()
	router.GET("/", handler.Index)
	router.GET("/github_redirect", handler.GitHubRedirect)

	//Run HTTPS server
	startHttpsServer(router, tlsDir)
	//Run HTTP server
	fmt.Printf("Starting HTTP server on port %s\n", port)
	http.ListenAndServe(":"+port, http.HandlerFunc(redirectToHttps))
}

func redirectToHttps(w http.ResponseWriter, r *http.Request) {
	newURI := "https://" + r.Host + r.URL.String()
	http.Redirect(w, r, newURI, http.StatusFound)
}

func startHttpsServer(h http.Handler, tlsDir string) {
	if tlsDir == "" {
		log.Printf("TLS_DIR is empty, so skip serving https")
		return
	}

	httpsServer := &http.Server{
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 5 * time.Second,
		IdleTimeout:  120 * time.Second,
		Handler:      h,
	}

	m := autocert.Manager{
		Prompt: autocert.AcceptTOS,
		Cache:  autocert.DirCache(tlsDir),
	}

	httpsServer.Addr = ":443"
	httpsServer.TLSConfig = &tls.Config{GetCertificate: m.GetCertificate}

	go func() {
		fmt.Printf("Starting HTTPS server on %s\n", httpsServer.Addr)
		err := httpsServer.ListenAndServeTLS("", "")
		if err != nil {
			log.Fatalf("httpsSrv.ListendAndServeTLS() failed with %s", err)
		}
	}()
}
<commit_msg>Add logging to file and stdout<commit_after>package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"github.com/proshik/githubstatbot/api"
	"github.com/proshik/githubstatbot/github"
	"github.com/proshik/githubstatbot/storage"
	"github.com/proshik/githubstatbot/telegram"
	"golang.org/x/crypto/acme/autocert"
	"log"
	"net/http"
	"os"
	"time"
	"io"
)

//For run:
//env PORT=8080 DB_PATH=/data/githubstatbot/boltdb.db GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= TELEGRAM_TOKEN= go run githubstatbot.go
func main() {
	flag.Parse()

	port := os.Getenv("PORT")
	if port == "" {
		log.Panic("Port is empty")
	}

	tlsDir := os.Getenv("TLS_DIR")

	logFile := os.Getenv("LOG_FILE")
	configureLog(logFile)

	path := os.Getenv("DB_PATH")
	if path == "" {
		log.Panic("DB path is empty")
	}

	clientID := os.Getenv("GITHUB_CLIENT_ID")
	clientSecret := os.Getenv("GITHUB_CLIENT_SECRET")
	if clientID == "" || clientSecret == "" {
		log.Panic("ClientId or clientSecret is empty")
	}

	telegramToken := os.Getenv("TELEGRAM_TOKEN")
	if telegramToken == "" {
		log.Panic("Telegram token is empty")
	}

	db := storage.New(path)
	stateStore := storage.NewStateStore()
	oAuth := github.NewOAuth(clientID, clientSecret)

	bot, err := telegram.NewBot(telegramToken, false, db, stateStore, oAuth)
	if err != nil {
		log.Panic(err)
	}
	go bot.ReadUpdates()

	handler := api.New(oAuth, db, stateStore, bot)
	router := httprouter.New()
	router.GET("/", handler.Index)
	router.GET("/github_redirect", handler.GitHubRedirect)

	//Run HTTPS server
	startHttpsServer(router, tlsDir)
	//Run HTTP server
	fmt.Printf("Starting HTTP server on port %s\n", port)
	http.ListenAndServe(":"+port, http.HandlerFunc(redirectToHttps))
}

func configureLog(logFileAddr string) {
	var path string
	if logFileAddr != "" {
		path = logFileAddr
	} else {
		path = "log.txt"
	}

	logFile, err := os.OpenFile(path, os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666)
	if err != nil {
		panic(err)
	}

	mw := io.MultiWriter(os.Stdout, logFile)
	log.SetOutput(mw)
}

func redirectToHttps(w http.ResponseWriter, r *http.Request) {
	newURI := "https://" + r.Host + r.URL.String()
	http.Redirect(w, r, newURI, http.StatusFound)
}

func startHttpsServer(h http.Handler, tlsDir string) {
	if tlsDir == "" {
		log.Printf("TLS_DIR is empty, so skip serving https")
		return
	}

	httpsServer := &http.Server{
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 5 * time.Second,
		IdleTimeout:  120 * time.Second,
		Handler:      h,
	}

	m := autocert.Manager{
		Prompt: autocert.AcceptTOS,
		Cache:  autocert.DirCache(tlsDir),
	}

	httpsServer.Addr = ":443"
	httpsServer.TLSConfig = &tls.Config{GetCertificate: m.GetCertificate}

	go func() {
		fmt.Printf("Starting HTTPS server on %s\n", httpsServer.Addr)
		err := httpsServer.ListenAndServeTLS("", "")
		if err != nil {
			log.Fatalf("httpsSrv.ListendAndServeTLS() failed with %s", err)
		}
	}()
}
<|endoftext|>


<commit_before>package main

import "testing"

func TestGetBitsFromPacket(t *testing.T) {

	var bytePos int
	var bitPos int
	tests := []struct {
		packet []byte
		bpP    uint
		ret    uint8
	}{
		{[]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 24, 255},
		{[]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 12, 240},
		{[]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 9, 14},
		{[]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 3, 1},
		{[]byte{0x00, 0x00, 0x00, 0x00, 0x00}, 24, 0},
		{[]byte{0x00, 0x00, 0x00, 0x00, 0x00}, 12, 0},
		{[]byte{0x00, 0x00, 0x00, 0x00, 0x00}, 9, 0},
		{[]byte{0x00, 0x00, 0x00, 0x00, 0x00}, 3, 0},
	}

	for _, test := range tests {
		res := getBitsFromPacket(test.packet, &bytePos, &bitPos, test.bpP)
		if res != test.ret {
			t.Errorf("Input: %d Expected: %d \t Got %d", test.packet, test.ret, res)
		}
	}
}

func TestCheckConfig(t *testing.T) {
	tests := []struct {
		name string
		cfg  configs
		err  string
	}{
		// Testing different output stiles
		{name: "Two Bits per Pixel", cfg: configs{2, 0, 0, 0, TERMINAL}, err: "-bits 2 is not divisible by three or one"},
		{name: "One Bit per Pixel", cfg: configs{1, 0, 0, 0, TERMINAL}},
		{name: "27 Bits per Pixel", cfg: configs{27, 0, 0, 0, TERMINAL}, err: "-bits 27 must be smaller than 25"},
		{name: "Terminal only", cfg: configs{3, 0, 0, 0, TERMINAL}},
		{name: "Terminal and Timeslize", cfg: configs{3, 0, 0, 0, (TERMINAL | TIMESLIZES)}, err: "-timeslize and -terminal can't be combined"},
		{name: "Fixed Slize", cfg: configs{1, 0, 0, 0, 0}},
		{name: "Time Slize", cfg: configs{1, 0, 50, 0, 0}},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			res := checkConfig(tc.cfg)

			if tc.err != "" {
				if res.Error() != tc.err {
					t.Errorf("Expected: %v \t Got: %v", tc.err, res)
				}
			}
		})
	}
}

func TestCreatePixel(t *testing.T) {
	tests := []struct {
		name   string
		packet []byte
		byteP  int
		bitP   int
		bpP    uint
		red    uint8
		green  uint8
		blue   uint8
	}{
		{"White", []byte{0xFF, 0xFF}, 0, 0, 1, 255, 255, 255},
		{"Black", []byte{0x00, 0x00}, 0, 0, 1, 0, 0, 0},
		{"Royal Blue", []byte{0x41, 0x69, 0xE1, 0x41, 0x69, 0xE1}, 0, 0, 24, 65, 105, 225},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			c := createPixel(tc.packet, &(tc.byteP), &(tc.bitP), tc.bpP)
			r, g, b, _ := c.RGBA()
			if uint8(r) != tc.red || uint8(g) != tc.green || uint8(b) != tc.blue {
				t.Errorf("Expected: ", tc.red, tc.green, tc.blue, "\t Got: ", uint8(r), uint8(g), uint8(b))
			}
		})
	}
}
<commit_msg>Adjust last test<commit_after>package main

import "testing"

func TestGetBitsFromPacket(t *testing.T) {

	var bytePos int
	var bitPos int
	tests := []struct {
		name   string
		packet []byte
		bpP    uint
		ret    uint8
	}{
		{"24 Bits", []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 24, 255},
		{"12 Bits", []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 12, 240},
		{"9 Bits", []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 9, 14},
		{"3 Bits", []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, 3, 1},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			// Reset position, as the stream of provided bits is limited
			bytePos = 0
			bitPos = 0
			res := getBitsFromPacket(tc.packet, &bytePos, &bitPos, tc.bpP)
			if res != tc.ret {
				t.Errorf("Input: %d Expected: %d \t Got %d", tc.packet, tc.ret, res)
			}
		})
	}
}

func TestCheckConfig(t *testing.T) {
	tests := []struct {
		name string
		cfg  configs
		err  string
	}{
		// Testing different output stiles
		{name: "Two Bits per Pixel", cfg: configs{2, 0, 0, 0, TERMINAL}, err: "-bits 2 is not divisible by three or one"},
		{name: "One Bit per Pixel", cfg: configs{1, 0, 0, 0, TERMINAL}},
		{name: "27 Bits per Pixel", cfg: configs{27, 0, 0, 0, TERMINAL}, err: "-bits 27 must be smaller than 25"},
		{name: "Terminal only", cfg: configs{3, 0, 0, 0, TERMINAL}},
		{name: "Terminal and Timeslize", cfg: configs{3, 0, 0, 0, (TERMINAL | TIMESLIZES)}, err: "-timeslize and -terminal can't be combined"},
		{name: "Fixed Slize", cfg: configs{1, 0, 0, 0, 0}},
		{name: "Time Slize", cfg: configs{1, 0, 50, 0, 0}},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			res := checkConfig(tc.cfg)

			if tc.err != "" {
				if res.Error() != tc.err {
					t.Errorf("Expected: %v \t Got: %v", tc.err, res)
				}
			}
		})
	}
}

func TestCreatePixel(t *testing.T) {
	tests := []struct {
		name   string
		packet []byte
		byteP  int
		bitP   int
		bpP    uint
		red    uint8
		green  uint8
		blue   uint8
	}{
		{"White", []byte{0xFF, 0xFF}, 0, 0, 1, 255, 255, 255},
		{"Black", []byte{0x00, 0x00}, 0, 0, 1, 0, 0, 0},
		{"Royal Blue", []byte{0x41, 0x69, 0xE1, 0x41, 0x69, 0xE1}, 0, 0, 24, 65, 105, 225},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			c := createPixel(tc.packet, &(tc.byteP), &(tc.bitP), tc.bpP)
			r, g, b, _ := c.RGBA()
			if uint8(r) != tc.red || uint8(g) != tc.green || uint8(b) != tc.blue {
				t.Errorf("Expected: ", tc.red, tc.green, tc.blue, "\t Got: ", uint8(r), uint8(g), uint8(b))
			}
		})
	}
}
<|endoftext|>


<commit_before>package gocumber

import (
	"fmt"
	"testing"

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

type FuncTestingFramework struct {
	err func(args ...interface{})
	log func(args ...interface{})
}

func (t FuncTestingFramework) Error(args ...interface{}) { t.err(args...) }
func (t FuncTestingFramework) Log(args ...interface{})   { t.log(args...) }

func TestRun_HappyPath(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	// Simply defining steps to prove that it parses right, no need to fill them in
	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {})

	steps.Run(tt, "test/valid.feature")

	assert.False(t, tt.Failed())
}

func TestRun_FailsOnMissingFile(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Run(tt, "file_does_not_exist")

	assert.True(t, tt.Failed())
}

func TestRun_FailsOnInvalidGherkin(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Run(tt, "test/invalid.feature")

	assert.True(t, tt.Failed())
}

func TestRun_FailsOnUndefinedSteps(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Run(tt, "test/valid.feature")

	assert.True(t, tt.Failed())
}

func ExampleRun_WithUndefinedSteps() {
	steps := make(Definitions)

	tt := FuncTestingFramework{
		err: func(args ...interface{}) { fmt.Println(args...) },
	}
	steps.Run(tt, "test/valid_with_url_params.feature")

	// Output:
	// Undefined step:
	// When I get "/something/%{UUID}"
}

func TestRun_FailsOnPendingSteps(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.When("I create a user with the following json data:", nil)
	steps.Then("the user should be created with the expected data", nil)

	steps.Run(tt, "test/valid.feature")

	assert.True(t, tt.Failed())
}

func ExampleRun_WithPendingSteps() {
	steps := make(Definitions)

	tt := FuncTestingFramework{
		err: func(args ...interface{}) { fmt.Println(args...) },
		log: func(args ...interface{}) { fmt.Println(args...) },
	}
	steps.When("I create a user with the following json data:", nil)
	steps.Then("the user should be created with the expected data", nil)

	steps.Run(tt, "test/valid.feature")

	// Output:
	// Scenario: Create a user with a json payload
	// Pending step:
	// When I create a user with the following json data:
}

func ExampleRun_WithFailingSteps() {
	steps := make(Definitions)

	tt := FuncTestingFramework{
		err: func(args ...interface{}) { fmt.Println(args...) },
		log: func(args ...interface{}) { fmt.Println(args...) },
	}
	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {
		tt.Error("Expectation failed")
	})

	steps.Run(tt, "test/valid.feature")

	// Output:
	// Scenario: Create a user with a json payload
	// Expectation failed
}

func TestRun_SuccessWithBackground(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var called int
	steps.Given("I am able to perform", func([]string, StepNode) {
		called++
	})
	steps.When("I perform admirably", func([]string, StepNode) {})
	steps.When("I act a fool", func([]string, StepNode) {})
	steps.Then("things should go well", func([]string, StepNode) {})

	steps.Run(tt, "test/valid_with_background.feature")

	assert.Equal(t, 2, called, "Expected background to be executed for each scenario")
	assert.False(t, tt.Failed())
}

func TestRun_SuccessWithOutlineSteps(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Given("I have no users", func([]string, StepNode) {})
	steps.When("I create a new user with the following data:", func([]string, StepNode) {})
	steps.Then("no users should be created", func([]string, StepNode) {})

	steps.Run(tt, "test/valid_with_outline.feature")

	assert.False(t, tt.Failed())
}

func TestRun_SuccessWithPyString(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Given("I do something the following json data:", func([]string, StepNode) {})
	steps.When("I do something", func([]string, StepNode) {})
	steps.Then("something should have happened", func([]string, StepNode) {})

	steps.Run(tt, "test/valid_with_pystring.feature")

	assert.False(t, tt.Failed())
}

func TestColumnMap_Happy(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var called bool
	steps.When("I create something with the following table data:", func(_ []string, step StepNode) {
		called = true
		assert.Equal(t,
			map[string]string{
				"key":  "value",
				"key1": "value1",
				"key2": "value2",
				"key3": "value3",
			},
			ColumnMap(step.Table()))
	})

	steps.Run(tt, "test/valid_with_table_data.feature")

	assert.True(t, called)
	assert.False(t, tt.Failed())
}

func TestExec_MatchFound(t *testing.T) {
	steps := make(Definitions)

	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {})

	assert.True(t, steps.Exec("the user should be created with the expected data"))
}

func TestExec_NoMatch(t *testing.T) {
	steps := make(Definitions)

	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {})

	assert.False(t, steps.Exec("some unknown step"))
}

func TestDocstrings_OutlineVariables(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var called int
	steps.Given("something is:", func(_ []string, step StepNode) {
		called++
		assert.Equal(t, []string{"minimally functional"}, step.PyString().Lines())
	})

	steps.Run(t, "test/valid_with_pystring_outline.feature")

	assert.Equal(t, 1, called, "Expected scenario to be executed for each outline example")
	assert.False(t, tt.Failed())
}

func TestDocstrings_OutlineVariablesWithMultipleExamples(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var expected_replaced_pystrings = []string{"minimally functional barely", "incredibly functional overwhelmingly"}

	var called int
	steps.Given("something is:", func(_ []string, step StepNode) {
		assert.Equal(t, []string{expected_replaced_pystrings[called]}, step.PyString().Lines())
		called++
	})

	steps.Run(t, "test/valid_with_pystring_outline_multiple_examples.feature")

	assert.Equal(t, 2, called, "Expected scenario to be executed for each outline example")
	assert.False(t, tt.Failed())
}
<commit_msg>Issue-15: update test for replacement of outline table data from examples<commit_after>package gocumber

import (
	"fmt"
	"testing"

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

type FuncTestingFramework struct {
	err func(args ...interface{})
	log func(args ...interface{})
}

func (t FuncTestingFramework) Error(args ...interface{}) { t.err(args...) }
func (t FuncTestingFramework) Log(args ...interface{})   { t.log(args...) }

func TestRun_HappyPath(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	// Simply defining steps to prove that it parses right, no need to fill them in
	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {})

	steps.Run(tt, "test/valid.feature")

	assert.False(t, tt.Failed())
}

func TestRun_FailsOnMissingFile(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Run(tt, "file_does_not_exist")

	assert.True(t, tt.Failed())
}

func TestRun_FailsOnInvalidGherkin(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Run(tt, "test/invalid.feature")

	assert.True(t, tt.Failed())
}

func TestRun_FailsOnUndefinedSteps(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Run(tt, "test/valid.feature")

	assert.True(t, tt.Failed())
}

func ExampleRun_WithUndefinedSteps() {
	steps := make(Definitions)

	tt := FuncTestingFramework{
		err: func(args ...interface{}) { fmt.Println(args...) },
	}
	steps.Run(tt, "test/valid_with_url_params.feature")

	// Output:
	// Undefined step:
	// When I get "/something/%{UUID}"
}

func TestRun_FailsOnPendingSteps(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.When("I create a user with the following json data:", nil)
	steps.Then("the user should be created with the expected data", nil)

	steps.Run(tt, "test/valid.feature")

	assert.True(t, tt.Failed())
}

func ExampleRun_WithPendingSteps() {
	steps := make(Definitions)

	tt := FuncTestingFramework{
		err: func(args ...interface{}) { fmt.Println(args...) },
		log: func(args ...interface{}) { fmt.Println(args...) },
	}
	steps.When("I create a user with the following json data:", nil)
	steps.Then("the user should be created with the expected data", nil)

	steps.Run(tt, "test/valid.feature")

	// Output:
	// Scenario: Create a user with a json payload
	// Pending step:
	// When I create a user with the following json data:
}

func ExampleRun_WithFailingSteps() {
	steps := make(Definitions)

	tt := FuncTestingFramework{
		err: func(args ...interface{}) { fmt.Println(args...) },
		log: func(args ...interface{}) { fmt.Println(args...) },
	}
	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {
		tt.Error("Expectation failed")
	})

	steps.Run(tt, "test/valid.feature")

	// Output:
	// Scenario: Create a user with a json payload
	// Expectation failed
}

func TestRun_SuccessWithBackground(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var called int
	steps.Given("I am able to perform", func([]string, StepNode) {
		called++
	})
	steps.When("I perform admirably", func([]string, StepNode) {})
	steps.When("I act a fool", func([]string, StepNode) {})
	steps.Then("things should go well", func([]string, StepNode) {})

	steps.Run(tt, "test/valid_with_background.feature")

	assert.Equal(t, 2, called, "Expected background to be executed for each scenario")
	assert.False(t, tt.Failed())
}

func TestRun_SuccessWithOutlineSteps(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Given("I have no users", func([]string, StepNode) {})
	steps.Then("no users should be created", func([]string, StepNode) {})

	var expected_first_example = map[string]string{
		"key":      "value",
		"username": "",
		"first":    "",
		"last":     "",
	}

	var expected_second_example = map[string]string{
		"key":      "value",
		"username": "",
		"first":    "fname",
		"last":     "lname",
	}

	var expected_third_example = map[string]string{
		"key":      "value",
		"username": "newuser",
		"first":    "",
		"last":     "lname",
	}

	var expected_fourth_example = map[string]string{
		"key":      "value",
		"username": "newuser",
		"first":    "fname",
		"last":     "",
	}

	var expected_fifth_example = map[string]string{
		"key":      "value",
		"username": "newuser",
		"first":    "fname",
		"last":     "lname",
	}

	var expected_replaced_table_data = []map[string]string{
		expected_first_example,
		expected_second_example,
		expected_third_example,
		expected_fourth_example,
		expected_fifth_example,
	}

	var called int
	steps.When("I create a new user with the following data:", func(_ []string, step StepNode) {
		assert.Equal(t, expected_replaced_table_data[called], ColumnMap(step.Table()))
		called++
	})

	steps.Run(tt, "test/valid_with_outline.feature")

	assert.Equal(t, 5, called, "Expected scenario to be executed for each outline example")
	assert.False(t, tt.Failed())
}

func TestRun_SuccessWithPyString(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	steps.Given("I do something the following json data:", func([]string, StepNode) {})
	steps.When("I do something", func([]string, StepNode) {})
	steps.Then("something should have happened", func([]string, StepNode) {})

	steps.Run(tt, "test/valid_with_pystring.feature")

	assert.False(t, tt.Failed())
}

func TestColumnMap_Happy(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var called bool
	steps.When("I create something with the following table data:", func(_ []string, step StepNode) {
		called = true
		assert.Equal(t,
			map[string]string{
				"key":  "value",
				"key1": "value1",
				"key2": "value2",
				"key3": "value3",
			},
			ColumnMap(step.Table()))
	})

	steps.Run(tt, "test/valid_with_table_data.feature")

	assert.True(t, called)
	assert.False(t, tt.Failed())
}

func TestExec_MatchFound(t *testing.T) {
	steps := make(Definitions)

	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {})

	assert.True(t, steps.Exec("the user should be created with the expected data"))
}

func TestExec_NoMatch(t *testing.T) {
	steps := make(Definitions)

	steps.When("I create a user with the following json data:", func([]string, StepNode) {})
	steps.Then("the user should be created with the expected data", func([]string, StepNode) {})

	assert.False(t, steps.Exec("some unknown step"))
}

func TestDocstrings_OutlineVariables(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var called int
	steps.Given("something is:", func(_ []string, step StepNode) {
		called++
		assert.Equal(t, []string{"minimally functional"}, step.PyString().Lines())
	})

	steps.Run(t, "test/valid_with_pystring_outline.feature")

	assert.Equal(t, 1, called, "Expected scenario to be executed for each outline example")
	assert.False(t, tt.Failed())
}

func TestDocstrings_OutlineVariablesWithMultipleExamples(t *testing.T) {
	steps := make(Definitions)
	tt := new(testing.T)

	var expected_replaced_pystrings = []string{"minimally functional barely", "incredibly functional overwhelmingly"}

	var called int
	steps.Given("something is:", func(_ []string, step StepNode) {
		assert.Equal(t, []string{expected_replaced_pystrings[called]}, step.PyString().Lines())
		called++
	})

	steps.Run(t, "test/valid_with_pystring_outline_multiple_examples.feature")

	assert.Equal(t, 2, called, "Expected scenario to be executed for each outline example")
	assert.False(t, tt.Failed())
}
<|endoftext|>


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

package godata

import (
	"strings"
	"os"
	"go/ast"
	"go/parser"
	"./logger"
	"container/vector"
)

var DefaultOutputFileName string

// Returns the greater of both numbers.
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// ================================
// ============ GoFile ============
// ================================

type GoFile struct {
	Filename           string         // file name with full path
	Pack               *GoPackage     // the package this file belongs to
	HasMain            bool           // main function found (only true for main package)
	IsCGOFile          bool           // imports "C"
	IsTestFile         bool           // files with "_test.go" suffix
	TestFunctions      *vector.Vector // vector of all test functions (name only)
	BenchmarkFunctions *vector.Vector // vector of all benchmark functions (name only)
}

/*
 Parses the content of a .go file and searches for package name, imports and
 main function.
*/
func (this *GoFile) ParseFile(packs *GoPackageContainer) (err os.Error) {
	var packName string
	var fileast *ast.File

	fileast, err = parser.ParseFile(this.Filename, nil, 0)

	packName = fileast.Name.String()

	if err != nil {
		logger.Warn("Parsing file %s returned with errors: %s\n", this.Filename, err)
	}

	// check if package is in the correct path
	if packName != "main" {
		switch strings.Count(this.Filename, "/") {
		case 0: // no sub-directory
			logger.Warn("File %s from package %s is not in the correct path. Should be %s.\n",
				this.Filename, fileast.Name,
				strings.Join([]string{packName, this.Filename}, "/"))
		case 1: // one sub-directory
			if this.Filename[0:strings.Index(this.Filename, "/")] != packName {
				logger.Warn("File %s from package %s is not in the correct directory. Should be %s.\n",
					this.Filename, packName,
					strings.Join([]string{packName,
						this.Filename[strings.Index(this.Filename, "/")+1 : len(this.Filename)],
					},
						"/"))
			}
		default: // >1 sub-directories
			if this.Filename[max(strings.LastIndex(this.Filename, "/")-len(packName), 0):strings.LastIndex(this.Filename, "/")] != packName {

				// NOTE: this case will result in a link-error (exit with error here?)
				logger.Warn("File %s from package %s is not in the expected directory.\n",
					this.Filename, packName)
			}
			packName = strings.Join([]string{
				this.Filename[0:strings.LastIndex(this.Filename[0:strings.LastIndex(this.Filename, "/")], "/")],
				packName,
			},
				"/")
		}
	}

	// create empty temporary package, will be merged later
	this.Pack = NewGoPackage(packName)

	// find the local imports in this file
	visitor := astVisitor{this, packs}
	ast.Walk(visitor, fileast)

	packs.AddFile(this, packName)

	return
}

// ================================
// ========== astVisitor ==========
// ================================

// this visitor looks for imports and the main function in an AST
type astVisitor struct {
	file  *GoFile
	packs *GoPackageContainer
}

/*
 Implementation of the visitor interface for ast walker.
 Returning nil stops the walker, anything else continues into the subtree
*/
func (v astVisitor) Visit(node interface{}) (w ast.Visitor) {
	switch n := node.(type) {
	case *ast.ImportSpec:
		var packName string
		var packType int
		for _, bl := range n.Path {
			if (len(bl.Value) > 4) &&
				(bl.Value[1] == '.') &&
				(bl.Value[2] == '/') {

				// local package found
				packName = string(bl.Value[3 : len(bl.Value)-1])
				packType = LOCAL_PACKAGE

			} else {
				packName = string(bl.Value[1 : len(bl.Value)-1])
				packType = UNKNOWN_PACKAGE
			}

			dep, exists := v.packs.Get(packName)
			if !exists {
				dep = v.packs.AddNewPackage(packName)
			} else if dep.Type == LOCAL_PACKAGE {
				packType = LOCAL_PACKAGE
			}

			dep.Type = packType
			v.file.Pack.Depends.Push(dep)

			if string(bl.Value) == "\"C\"" {
				v.file.IsCGOFile = true // not used yet
			}

		}
		return nil
	case *ast.FuncDecl:
		if n.Recv == nil && n.Name.Value == "main" && v.file.Pack.Name == "main" {
			v.file.HasMain = true
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.Value, "Test") &&
			n.Body != nil {
			v.file.TestFunctions.Push(n.Name.Value)
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.Value, "Benchmark") &&
			n.Body != nil {
			v.file.BenchmarkFunctions.Push(n.Name.Value)
		}
		return nil
	case *ast.Package, *ast.File, *ast.BadDecl,
		*ast.GenDecl, *ast.Ident, []ast.Decl:
		return v

	default:
		return nil // makes parsing faster
			   // this may cause some files to not parse correctly
	}

	return nil // unreachable
}
<commit_msg>fixes ast.Ident changes in current Go tip<commit_after>// Copyright 2009 by Maurice Gilden. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package godata

import (
	"strings"
	"os"
	"go/ast"
	"go/parser"
	"./logger"
	"container/vector"
)

var DefaultOutputFileName string

// Returns the greater of both numbers.
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// ================================
// ============ GoFile ============
// ================================

type GoFile struct {
	Filename           string         // file name with full path
	Pack               *GoPackage     // the package this file belongs to
	HasMain            bool           // main function found (only true for main package)
	IsCGOFile          bool           // imports "C"
	IsTestFile         bool           // files with "_test.go" suffix
	TestFunctions      *vector.Vector // vector of all test functions (name only)
	BenchmarkFunctions *vector.Vector // vector of all benchmark functions (name only)
}

/*
 Parses the content of a .go file and searches for package name, imports and
 main function.
*/
func (this *GoFile) ParseFile(packs *GoPackageContainer) (err os.Error) {
	var packName string
	var fileast *ast.File

	fileast, err = parser.ParseFile(this.Filename, nil, 0)

	packName = fileast.Name.String()

	if err != nil {
		logger.Warn("Parsing file %s returned with errors: %s\n", this.Filename, err)
	}

	// check if package is in the correct path
	if packName != "main" {
		switch strings.Count(this.Filename, "/") {
		case 0: // no sub-directory
			logger.Warn("File %s from package %s is not in the correct path. Should be %s.\n",
				this.Filename, fileast.Name,
				strings.Join([]string{packName, this.Filename}, "/"))
		case 1: // one sub-directory
			if this.Filename[0:strings.Index(this.Filename, "/")] != packName {
				logger.Warn("File %s from package %s is not in the correct directory. Should be %s.\n",
					this.Filename, packName,
					strings.Join([]string{packName,
						this.Filename[strings.Index(this.Filename, "/")+1 : len(this.Filename)],
					},
						"/"))
			}
		default: // >1 sub-directories
			if this.Filename[max(strings.LastIndex(this.Filename, "/")-len(packName), 0):strings.LastIndex(this.Filename, "/")] != packName {

				// NOTE: this case will result in a link-error (exit with error here?)
				logger.Warn("File %s from package %s is not in the expected directory.\n",
					this.Filename, packName)
			}
			packName = strings.Join([]string{
				this.Filename[0:strings.LastIndex(this.Filename[0:strings.LastIndex(this.Filename, "/")], "/")],
				packName,
			},
				"/")
		}
	}

	// create empty temporary package, will be merged later
	this.Pack = NewGoPackage(packName)

	// find the local imports in this file
	visitor := astVisitor{this, packs}
	ast.Walk(visitor, fileast)

	packs.AddFile(this, packName)

	return
}

// ================================
// ========== astVisitor ==========
// ================================

// this visitor looks for imports and the main function in an AST
type astVisitor struct {
	file  *GoFile
	packs *GoPackageContainer
}

/*
 Implementation of the visitor interface for ast walker.
 Returning nil stops the walker, anything else continues into the subtree
*/
func (v astVisitor) Visit(node interface{}) (w ast.Visitor) {
	switch n := node.(type) {
	case *ast.ImportSpec:
		var packName string
		var packType int
		for _, bl := range n.Path {
			if (len(bl.Value) > 4) &&
				(bl.Value[1] == '.') &&
				(bl.Value[2] == '/') {

				// local package found
				packName = string(bl.Value[3 : len(bl.Value)-1])
				packType = LOCAL_PACKAGE

			} else {
				packName = string(bl.Value[1 : len(bl.Value)-1])
				packType = UNKNOWN_PACKAGE
			}

			dep, exists := v.packs.Get(packName)
			if !exists {
				dep = v.packs.AddNewPackage(packName)
			} else if dep.Type == LOCAL_PACKAGE {
				packType = LOCAL_PACKAGE
			}

			dep.Type = packType
			v.file.Pack.Depends.Push(dep)

			if string(bl.Value) == "\"C\"" {
				v.file.IsCGOFile = true // not used yet
			}

		}
		return nil
	case *ast.FuncDecl:
		if n.Recv == nil && n.Name.String() == "main" && v.file.Pack.Name == "main" {
			v.file.HasMain = true
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.String(), "Test") &&
			n.Body != nil {
			v.file.TestFunctions.Push(n.Name.String())
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.String(), "Benchmark") &&
			n.Body != nil {
			v.file.BenchmarkFunctions.Push(n.Name.String())
		}
		return nil
	case *ast.Package, *ast.File, *ast.BadDecl,
		*ast.GenDecl, *ast.Ident, []ast.Decl:
		return v

	default:
		return nil // makes parsing faster
			   // this may cause some files to not parse correctly
	}

	return nil // unreachable
}
<|endoftext|>


<commit_before>package backend

import (
	"context"
	"fmt"
	"path/filepath"

	"github.com/containerd/containerd"
	"github.com/containerd/go-cni"
	"github.com/opencontainers/runtime-spec/specs-go"
)

//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 github.com/containerd/go-cni.CNI

// CNINetworkConfig provides configuration for CNINetwork to override the
// defaults.
//
type CNINetworkConfig struct {
	// BridgeName is the name that the bridge set up in the current network
	// namespace to connect the veth's to.
	//
	BridgeName string

	// NetworkName is the virtual name used to identify the managed network.
	//
	NetworkName string

	// Subnet is the subnet (in CIDR notation) which the veths should be
	// added to.
	//
	Subnet string
}

const (
	// fileStoreWorkDir is a default directory used for storing
	// container-related files
	//
	fileStoreWorkDir = "/tmp"

	// binariesDir corresponds to the directory where CNI plugins have their
	// binaries in.
	//
	binariesDir = "/usr/local/concourse/bin"
)

var (
	// nameServers is the default set of nameservers used.
	//
	nameServers = []string{"8.8.8.8"}

	// defaultCNINetworkConfig is the default configuration for the CNI network
	// created to put concourse containers into.
	//
	defaultCNINetworkConfig = CNINetworkConfig{
		BridgeName:  "concourse0",
		NetworkName: "concourse",
		Subnet:      "10.80.0.0/16",
	}
)

func (c CNINetworkConfig) ToJSON() string {
	const networksConfListFormat = `{
  "cniVersion": "0.4.0",
  "name": "%s",
  "plugins": [
    {
      "type": "bridge",
      "bridge": "%s",
      "isGateway": true,
      "ipMasq": true,
      "ipam": {
        "type": "host-local",
        "subnet": "%s",
        "routes": [
          {
            "dst": "0.0.0.0/0"
          }
        ]
      }
    },
    {
      "type": "firewall"
    }
  ]
}`

	return fmt.Sprintf(networksConfListFormat,
		c.NetworkName, c.BridgeName, c.Subnet,
	)
}

// CNINetworkOpt defines a functional option that when applied, modifies the
// configuration of a CNINetwork.
//
type CNINetworkOpt func(n *cniNetwork)

// WithCNIBinariesDir is the directory where the binaries necessary for setting
// up the network live.
//
func WithCNIBinariesDir(dir string) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.binariesDir = dir
	}
}

// WithNameServers sets the set of nameservers to be configured for the
// /etc/resolv.conf inside the containers.
//
func WithNameServers(nameservers []string) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.nameServers = nameservers
	}
}

// WithCNIClient is an implementor of the CNI interface for reaching out to CNI
// plugins.
//
func WithCNIClient(c cni.CNI) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.client = c
	}
}

// WithCNINetworkConfig provides a custom CNINetworkConfig to be used by the CNI
// client at startup time.
//
func WithCNINetworkConfig(c CNINetworkConfig) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.config = c
	}
}

// WithCNIFileStore changes the default FileStore used to store files that
// belong to network configurations for containers.
//
func WithCNIFileStore(f FileStore) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.store = f
	}
}

type cniNetwork struct {
	client      cni.CNI
	store       FileStore
	config      CNINetworkConfig
	nameServers []string
	binariesDir string
}

var _ Network = (*cniNetwork)(nil)

func NewCNINetwork(opts ...CNINetworkOpt) (*cniNetwork, error) {
	var err error

	n := &cniNetwork{
		binariesDir: binariesDir,
		config:      defaultCNINetworkConfig,
		nameServers: nameServers,
	}

	for _, opt := range opts {
		opt(n)
	}

	if n.store == nil {
		n.store = NewFileStore(fileStoreWorkDir)
	}

	if n.client == nil {
		n.client, err = cni.New(cni.WithPluginDir([]string{n.binariesDir}))
		if err != nil {
			return nil, fmt.Errorf("cni init: %w", err)
		}

		err = n.client.Load(
			cni.WithConfListBytes([]byte(n.config.ToJSON())),
			cni.WithLoNetwork,
		)
		if err != nil {
			return nil, fmt.Errorf("cni configuration loading: %w", err)
		}
	}

	return n, nil
}

func (n cniNetwork) SetupMounts(handle string) ([]specs.Mount, error) {
	if handle == "" {
		return nil, ErrInvalidInput("empty handle")
	}

	etcHosts, err := n.store.Create(
		filepath.Join(handle, "/hosts"),
		[]byte("127.0.0.1 localhost"),
	)
	if err != nil {
		return nil, fmt.Errorf("creating /etc/hosts: %w", err)
	}

	resolvConf, err := n.store.Create(
		filepath.Join(handle, "/resolv.conf"),
		n.generateResolvConfContents(),
	)
	if err != nil {
		return nil, fmt.Errorf("creating /etc/resolv.conf: %w", err)
	}

	return []specs.Mount{
		{
			Destination: "/etc/hosts",
			Type:        "bind",
			Source:      etcHosts,
			Options:     []string{"bind", "rw"},
		}, {
			Destination: "/etc/resolv.conf",
			Type:        "bind",
			Source:      resolvConf,
			Options:     []string{"bind", "rw"},
		},
	}, nil
}

func (n cniNetwork) generateResolvConfContents() []byte {
	contents := ""
	for _, n := range n.nameServers {
		contents = contents + fmt.Sprintf("nameserver %s\n", n)
	}

	return []byte(contents)
}

func (n cniNetwork) Add(ctx context.Context, task containerd.Task) error {
	if task == nil {
		return ErrInvalidInput("nil task")
	}

	id, netns := netId(task), netNsPath(task)

	_, err := n.client.Setup(ctx, id, netns)
	if err != nil {
		return fmt.Errorf("cni net setup: %w", err)
	}

	return nil
}

func (n cniNetwork) Remove(ctx context.Context, task containerd.Task) error {
	if task == nil {
		return ErrInvalidInput("nil task")
	}

	id, netns := netId(task), netNsPath(task)

	err := n.client.Remove(ctx, id, netns)
	if err != nil {
		return fmt.Errorf("cni net teardown: %w", err)
	}

	return nil
}

func netId(task containerd.Task) string {
	return task.ID()
}

func netNsPath(task containerd.Task) string {
	return fmt.Sprintf("/proc/%d/ns/net", task.Pid())
}
<commit_msg>worker: rename nameServers to be defaultNameServers<commit_after>package backend

import (
	"context"
	"fmt"
	"path/filepath"

	"github.com/containerd/containerd"
	"github.com/containerd/go-cni"
	"github.com/opencontainers/runtime-spec/specs-go"
)

//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 github.com/containerd/go-cni.CNI

// CNINetworkConfig provides configuration for CNINetwork to override the
// defaults.
//
type CNINetworkConfig struct {
	// BridgeName is the name that the bridge set up in the current network
	// namespace to connect the veth's to.
	//
	BridgeName string

	// NetworkName is the virtual name used to identify the managed network.
	//
	NetworkName string

	// Subnet is the subnet (in CIDR notation) which the veths should be
	// added to.
	//
	Subnet string
}

const (
	// fileStoreWorkDir is a default directory used for storing
	// container-related files
	//
	fileStoreWorkDir = "/tmp"

	// binariesDir corresponds to the directory where CNI plugins have their
	// binaries in.
	//
	binariesDir = "/usr/local/concourse/bin"
)

var (
	// defaultNameServers is the default set of nameservers used.
	//
	defaultNameServers = []string{"8.8.8.8"}

	// defaultCNINetworkConfig is the default configuration for the CNI network
	// created to put concourse containers into.
	//
	defaultCNINetworkConfig = CNINetworkConfig{
		BridgeName:  "concourse0",
		NetworkName: "concourse",
		Subnet:      "10.80.0.0/16",
	}
)

func (c CNINetworkConfig) ToJSON() string {
	const networksConfListFormat = `{
  "cniVersion": "0.4.0",
  "name": "%s",
  "plugins": [
    {
      "type": "bridge",
      "bridge": "%s",
      "isGateway": true,
      "ipMasq": true,
      "ipam": {
        "type": "host-local",
        "subnet": "%s",
        "routes": [
          {
            "dst": "0.0.0.0/0"
          }
        ]
      }
    },
    {
      "type": "firewall"
    }
  ]
}`

	return fmt.Sprintf(networksConfListFormat,
		c.NetworkName, c.BridgeName, c.Subnet,
	)
}

// CNINetworkOpt defines a functional option that when applied, modifies the
// configuration of a CNINetwork.
//
type CNINetworkOpt func(n *cniNetwork)

// WithCNIBinariesDir is the directory where the binaries necessary for setting
// up the network live.
//
func WithCNIBinariesDir(dir string) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.binariesDir = dir
	}
}

// WithNameServers sets the set of nameservers to be configured for the
// /etc/resolv.conf inside the containers.
//
func WithNameServers(nameservers []string) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.nameServers = nameservers
	}
}

// WithCNIClient is an implementor of the CNI interface for reaching out to CNI
// plugins.
//
func WithCNIClient(c cni.CNI) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.client = c
	}
}

// WithCNINetworkConfig provides a custom CNINetworkConfig to be used by the CNI
// client at startup time.
//
func WithCNINetworkConfig(c CNINetworkConfig) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.config = c
	}
}

// WithCNIFileStore changes the default FileStore used to store files that
// belong to network configurations for containers.
//
func WithCNIFileStore(f FileStore) CNINetworkOpt {
	return func(n *cniNetwork) {
		n.store = f
	}
}

type cniNetwork struct {
	client      cni.CNI
	store       FileStore
	config      CNINetworkConfig
	nameServers []string
	binariesDir string
}

var _ Network = (*cniNetwork)(nil)

func NewCNINetwork(opts ...CNINetworkOpt) (*cniNetwork, error) {
	var err error

	n := &cniNetwork{
		binariesDir: binariesDir,
		config:      defaultCNINetworkConfig,
		nameServers: defaultNameServers,
	}

	for _, opt := range opts {
		opt(n)
	}

	if n.store == nil {
		n.store = NewFileStore(fileStoreWorkDir)
	}

	if n.client == nil {
		n.client, err = cni.New(cni.WithPluginDir([]string{n.binariesDir}))
		if err != nil {
			return nil, fmt.Errorf("cni init: %w", err)
		}

		err = n.client.Load(
			cni.WithConfListBytes([]byte(n.config.ToJSON())),
			cni.WithLoNetwork,
		)
		if err != nil {
			return nil, fmt.Errorf("cni configuration loading: %w", err)
		}
	}

	return n, nil
}

func (n cniNetwork) SetupMounts(handle string) ([]specs.Mount, error) {
	if handle == "" {
		return nil, ErrInvalidInput("empty handle")
	}

	etcHosts, err := n.store.Create(
		filepath.Join(handle, "/hosts"),
		[]byte("127.0.0.1 localhost"),
	)
	if err != nil {
		return nil, fmt.Errorf("creating /etc/hosts: %w", err)
	}

	resolvConf, err := n.store.Create(
		filepath.Join(handle, "/resolv.conf"),
		n.generateResolvConfContents(),
	)
	if err != nil {
		return nil, fmt.Errorf("creating /etc/resolv.conf: %w", err)
	}

	return []specs.Mount{
		{
			Destination: "/etc/hosts",
			Type:        "bind",
			Source:      etcHosts,
			Options:     []string{"bind", "rw"},
		}, {
			Destination: "/etc/resolv.conf",
			Type:        "bind",
			Source:      resolvConf,
			Options:     []string{"bind", "rw"},
		},
	}, nil
}

func (n cniNetwork) generateResolvConfContents() []byte {
	contents := ""
	for _, n := range n.nameServers {
		contents = contents + fmt.Sprintf("nameserver %s\n", n)
	}

	return []byte(contents)
}

func (n cniNetwork) Add(ctx context.Context, task containerd.Task) error {
	if task == nil {
		return ErrInvalidInput("nil task")
	}

	id, netns := netId(task), netNsPath(task)

	_, err := n.client.Setup(ctx, id, netns)
	if err != nil {
		return fmt.Errorf("cni net setup: %w", err)
	}

	return nil
}

func (n cniNetwork) Remove(ctx context.Context, task containerd.Task) error {
	if task == nil {
		return ErrInvalidInput("nil task")
	}

	id, netns := netId(task), netNsPath(task)

	err := n.client.Remove(ctx, id, netns)
	if err != nil {
		return fmt.Errorf("cni net teardown: %w", err)
	}

	return nil
}

func netId(task containerd.Task) string {
	return task.ID()
}

func netNsPath(task containerd.Task) string {
	return fmt.Sprintf("/proc/%d/ns/net", task.Pid())
}
<|endoftext|>


<commit_before>package prose

import (
	"path/filepath"
	"strings"
	"testing"
)

func BenchmarkDoc(b *testing.B) {
	content := readDataFile(filepath.Join(testdata, "sherlock.txt"))
	text := string(content)
	for n := 0; n < b.N; n++ {
		_, err := NewDocument(text)
		if err != nil {
			panic(err)
		}
	}
}

func CustomTokenizer(b *testing.B) {
	content := readDataFile(filepath.Join(testdata, "sherlock.txt"))
    tok := NewIterTokenizer(
        UsingSanitizer(strings.NewReplacer()), // Disable sanitizer
        UsingPrefixes([]string{"(", `"`, "[", "'"}),
        UsingSuffixes([]string{",", ")", `"`, "]", "!", ";", ".", "?", ":", "'"}),
    )
	text := string(content)
	for n := 0; n < b.N; n++ {
		_, err := NewDocument(text, UsingTokenizer(tok))
		if err != nil {
			panic(err)
		}
	}
}
<commit_msg>Fix test name<commit_after>package prose

import (
	"path/filepath"
	"strings"
	"testing"
)

func BenchmarkDoc(b *testing.B) {
	content := readDataFile(filepath.Join(testdata, "sherlock.txt"))
	text := string(content)
	for n := 0; n < b.N; n++ {
		_, err := NewDocument(text)
		if err != nil {
			panic(err)
		}
	}
}

func BenchmarkCustomTokenizer(b *testing.B) {
	content := readDataFile(filepath.Join(testdata, "sherlock.txt"))
	tok := NewIterTokenizer(
		UsingSanitizer(strings.NewReplacer()), // Disable sanitizer
		UsingPrefixes([]string{"(", `"`, "[", "'"}),
		UsingSuffixes([]string{",", ")", `"`, "]", "!", ";", ".", "?", ":", "'"}),
	)
	text := string(content)
	for n := 0; n < b.N; n++ {
		_, err := NewDocument(text, UsingTokenizer(tok))
		if err != nil {
			panic(err)
		}
	}
}
<|endoftext|>


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

package godata

import (
	"strings"
	"os"
	"go/ast"
	"go/parser"
	"./logger"
	"container/vector"
)

var DefaultOutputFileName string

// Returns the greater of both numbers.
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// ================================
// ============ GoFile ============
// ================================

type GoFile struct {
	Filename           string         // file name with relative path
	Pack               *GoPackage     // the package this file belongs to
	HasMain            bool           // main function found (only true for main package)
	IsCGOFile          bool           // imports "C"
	IsTestFile         bool           // files with "_test.go" suffix
	TestFunctions      *vector.Vector // vector of all test functions (name only)
	BenchmarkFunctions *vector.Vector // vector of all benchmark functions (name only)
}

/*
 Parses the content of a .go file and searches for package name, imports and
 main function.
*/
func (this *GoFile) ParseFile(packs *GoPackageContainer) (err os.Error) {
	var packName string
	var fileast *ast.File

	if fileast, err = parser.ParseFile(this.Filename, nil, 0); err != nil {
		logger.Error("%s\n", err)
		os.Exit(1)
	}

	packName = fileast.Name.String()

	if err != nil {
		logger.Warn("Parsing file %s returned with errors: %s\n", this.Filename, err)
	}

	// check if package is in the correct path
	if packName != "main" {
		switch strings.Count(this.Filename, "/") {
		case 0: // no sub-directory
			logger.Warn("File %s from package %s is not in the correct path. Should be %s.\n",
				this.Filename, fileast.Name,
				strings.Join([]string{packName, this.Filename}, "/"))
		case 1: // one sub-directory
			if this.Filename[0:strings.Index(this.Filename, "/")] != packName {
				logger.Warn("File %s from package %s is not in the correct directory. Should be %s.\n",
					this.Filename, packName,
					strings.Join([]string{packName,
						this.Filename[strings.Index(this.Filename, "/")+1 : len(this.Filename)],
					},
						"/"))
			}
		default: // >1 sub-directories
			if this.Filename[max(strings.LastIndex(this.Filename, "/")-len(packName), 0):strings.LastIndex(this.Filename, "/")] != packName {

				// NOTE: this case will result in a link-error (exit with error here?)
				logger.Warn("File %s from package %s is not in the expected directory.\n",
					this.Filename, packName)
			}
			packName = strings.Join([]string{
				this.Filename[0:strings.LastIndex(this.Filename[0:strings.LastIndex(this.Filename, "/")], "/")],
				packName,
			},
				"/")
		}
	}

	// create empty temporary package, will be merged later
	this.Pack = NewGoPackage(packName)

	// find the local imports in this file
	visitor := astVisitor{this, packs}
	ast.Walk(visitor, fileast)

	packs.AddFile(this, packName)

	return
}

// ================================
// ========== astVisitor ==========
// ================================

// this visitor looks for imports and the main function in an AST
type astVisitor struct {
	file  *GoFile
	packs *GoPackageContainer
}

/*
 Implementation of the visitor interface for ast walker.
 Returning nil stops the walker, anything else continues into the subtree
*/
func (v astVisitor) Visit(node interface{}) (w ast.Visitor) {
	switch n := node.(type) {
	case *ast.ImportSpec:
		var packName string
		var packType int
		for _, bl := range n.Path {
			if (len(bl.Value) > 4) &&
				(bl.Value[1] == '.') &&
				(bl.Value[2] == '/') {

				// local package found
				packName = string(bl.Value[3 : len(bl.Value)-1])
				packType = LOCAL_PACKAGE

			} else {
				packName = string(bl.Value[1 : len(bl.Value)-1])
				packType = UNKNOWN_PACKAGE
			}

			dep, exists := v.packs.Get(packName)
			if !exists {
				dep = v.packs.AddNewPackage(packName)
			} else if dep.Type == LOCAL_PACKAGE {
				packType = LOCAL_PACKAGE
			}

			dep.Type = packType
			v.file.Pack.Depends.Push(dep)

			if string(bl.Value) == "\"C\"" {
				v.file.IsCGOFile = true // not used yet
			}

		}
		return nil
	case *ast.FuncDecl:
		if n.Recv == nil && n.Name.String() == "main" && v.file.Pack.Name == "main" {
			v.file.HasMain = true
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.String(), "Test") &&
			n.Body != nil {
			v.file.TestFunctions.Push(n.Name.String())
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.String(), "Benchmark") &&
			n.Body != nil {
			v.file.BenchmarkFunctions.Push(n.Name.String())
		}
		return nil
	case *ast.Package, *ast.File, *ast.BadDecl,
		*ast.GenDecl, *ast.Ident, []ast.Decl:
		return v

	default:
		return nil // makes parsing faster
			   // this may cause some files to not parse correctly
	}

	return nil // unreachable
}
<commit_msg>quick fix for new parameter for parser.ParseFile<commit_after>// Copyright 2009 by Maurice Gilden. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package godata

import (
	"strings"
	"os"
	"go/ast"
	"go/parser"
	"./logger"
	"container/vector"
)

var DefaultOutputFileName string

// Returns the greater of both numbers.
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// ================================
// ============ GoFile ============
// ================================

type GoFile struct {
	Filename           string         // file name with relative path
	Pack               *GoPackage     // the package this file belongs to
	HasMain            bool           // main function found (only true for main package)
	IsCGOFile          bool           // imports "C"
	IsTestFile         bool           // files with "_test.go" suffix
	TestFunctions      *vector.Vector // vector of all test functions (name only)
	BenchmarkFunctions *vector.Vector // vector of all benchmark functions (name only)
}

/*
 Parses the content of a .go file and searches for package name, imports and
 main function.
*/
func (this *GoFile) ParseFile(packs *GoPackageContainer) (err os.Error) {
	var packName string
	var fileast *ast.File

	if fileast, err = parser.ParseFile(this.Filename, nil, nil, 0); err != nil {
		logger.Error("%s\n", err)
		os.Exit(1)
	}

	packName = fileast.Name.String()

	if err != nil {
		logger.Warn("Parsing file %s returned with errors: %s\n", this.Filename, err)
	}

	// check if package is in the correct path
	if packName != "main" {
		switch strings.Count(this.Filename, "/") {
		case 0: // no sub-directory
			logger.Warn("File %s from package %s is not in the correct path. Should be %s.\n",
				this.Filename, fileast.Name,
				strings.Join([]string{packName, this.Filename}, "/"))
		case 1: // one sub-directory
			if this.Filename[0:strings.Index(this.Filename, "/")] != packName {
				logger.Warn("File %s from package %s is not in the correct directory. Should be %s.\n",
					this.Filename, packName,
					strings.Join([]string{packName,
						this.Filename[strings.Index(this.Filename, "/")+1 : len(this.Filename)],
					},
						"/"))
			}
		default: // >1 sub-directories
			if this.Filename[max(strings.LastIndex(this.Filename, "/")-len(packName), 0):strings.LastIndex(this.Filename, "/")] != packName {

				// NOTE: this case will result in a link-error (exit with error here?)
				logger.Warn("File %s from package %s is not in the expected directory.\n",
					this.Filename, packName)
			}
			packName = strings.Join([]string{
				this.Filename[0:strings.LastIndex(this.Filename[0:strings.LastIndex(this.Filename, "/")], "/")],
				packName,
			},
				"/")
		}
	}

	// create empty temporary package, will be merged later
	this.Pack = NewGoPackage(packName)

	// find the local imports in this file
	visitor := astVisitor{this, packs}
	ast.Walk(visitor, fileast)

	packs.AddFile(this, packName)

	return
}

// ================================
// ========== astVisitor ==========
// ================================

// this visitor looks for imports and the main function in an AST
type astVisitor struct {
	file  *GoFile
	packs *GoPackageContainer
}

/*
 Implementation of the visitor interface for ast walker.
 Returning nil stops the walker, anything else continues into the subtree
*/
func (v astVisitor) Visit(node interface{}) (w ast.Visitor) {
	switch n := node.(type) {
	case *ast.ImportSpec:
		var packName string
		var packType int
		for _, bl := range n.Path {
			if (len(bl.Value) > 4) &&
				(bl.Value[1] == '.') &&
				(bl.Value[2] == '/') {

				// local package found
				packName = string(bl.Value[3 : len(bl.Value)-1])
				packType = LOCAL_PACKAGE

			} else {
				packName = string(bl.Value[1 : len(bl.Value)-1])
				packType = UNKNOWN_PACKAGE
			}

			dep, exists := v.packs.Get(packName)
			if !exists {
				dep = v.packs.AddNewPackage(packName)
			} else if dep.Type == LOCAL_PACKAGE {
				packType = LOCAL_PACKAGE
			}

			dep.Type = packType
			v.file.Pack.Depends.Push(dep)

			if string(bl.Value) == "\"C\"" {
				v.file.IsCGOFile = true // not used yet
			}

		}
		return nil
	case *ast.FuncDecl:
		if n.Recv == nil && n.Name.String() == "main" && v.file.Pack.Name == "main" {
			v.file.HasMain = true
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.String(), "Test") &&
			n.Body != nil {
			v.file.TestFunctions.Push(n.Name.String())
		} else if n.Recv == nil && v.file.IsTestFile &&
			strings.HasPrefix(n.Name.String(), "Benchmark") &&
			n.Body != nil {
			v.file.BenchmarkFunctions.Push(n.Name.String())
		}
		return nil
	case *ast.Package, *ast.File, *ast.BadDecl,
		*ast.GenDecl, *ast.Ident, []ast.Decl:
		return v

	default:
		return nil // makes parsing faster
			   // this may cause some files to not parse correctly
	}

	return nil // unreachable
}
<|endoftext|>


<commit_before>package cbo

// An Endpoint is a low-level object representing a participant in a net.
type Endpoint struct {
	Name string
	Net  *Net
	ERC  ERCMode

	// Passthrough, if non-nil, is a set of endpoints that "pass through"
	// ERC characteristics.
	//
	// This is used for devices like resistors where the ERC direction
	// and output mode "pass through" for rules-checking purposes. It is also
	// used with terminals, once connected, to ensure that the outer net
	// is compatible with the inner net.
	//
	// When set, the endpoint's own ERC is ignored and one is instead inferred
	// by combining the ERC modes arriving on "the other side".
	Passthrough EndpointSet
}

// An EndpointSet is a set of endpoints.
type EndpointSet map[*Endpoint]struct{}

func (s EndpointSet) Has(e *Endpoint) bool {
	_, has := s[e]
	return has
}

func (s EndpointSet) Add(e *Endpoint) {
	s[e] = struct{}{}
}

func (s EndpointSet) Remove(e *Endpoint) {
	delete(s, e)
}

func (s EndpointSet) List() []*Endpoint {
	ret := make([]*Endpoint, 0, len(s))
	for e := range s {
		ret = append(ret, e)
	}
	return ret
}
<commit_msg>cbo: allow nil EndpointSets to be read<commit_after>package cbo

import (
	"sort"
)

// An Endpoint is a low-level object representing a participant in a net.
type Endpoint struct {
	Name string
	Net  *Net
	ERC  ERCMode

	// Passthrough, if non-nil, is a set of endpoints that "pass through"
	// ERC characteristics.
	//
	// This is used for devices like resistors where the ERC direction
	// and output mode "pass through" for rules-checking purposes. It is also
	// used with terminals, once connected, to ensure that the outer net
	// is compatible with the inner net.
	//
	// When set, the endpoint's own ERC is ignored and one is instead inferred
	// by combining the ERC modes arriving on "the other side".
	Passthrough EndpointSet
}

// An EndpointSet is a set of endpoints.
type EndpointSet map[*Endpoint]struct{}

func (s EndpointSet) Has(e *Endpoint) bool {
	if s == nil {
		return false
	}
	_, has := s[e]
	return has
}

// Names returns the names for all of the endpoints in the set, sorted
// lexicographically.
//
// This is primarily a test-assertion utility.
func (s EndpointSet) Names() []string {
	var ret []string
	for endpoint := range s {
		ret = append(ret, endpoint.Name)
	}
	sort.Strings(ret)
	return ret
}

func (s EndpointSet) Add(e *Endpoint) {
	s[e] = struct{}{}
}

func (s EndpointSet) Remove(e *Endpoint) {
	if s == nil {
		return
	}
	delete(s, e)
}

func (s EndpointSet) List() []*Endpoint {
	if s == nil {
		return nil
	}

	ret := make([]*Endpoint, 0, len(s))
	for e := range s {
		ret = append(ret, e)
	}
	return ret
}
<|endoftext|>


<commit_before>package domain

import "time"

// Trace represents a full trace of a request
// comprised of a number of events and annotations
type Trace struct {
	Events      []Event
	Annotations []Annotation
}

// An Event represents a section of an RPC call between systems
type Event struct {
	TraceId       string // Global Trace Identifier
	EventId       string // Identifier for this event, non unique - eg. RPC calls would have 4 of these
	ParentEventId string // Parent event - eg. nested RPC calls

	Timestamp time.Time     // Timestamp the event occured, can only be compared on the same machine
	Duration  time.Duration // Optional: duration of the event, eg. RPC call

	Hostname    string // Hostname this event originated from
	Origin      string // Fully qualified name of the message origin
	Destination string // Fully qualified name of the message destination

	EventType   string // The type of Event
	Payload     string // The returned payload (if possible)
	PayloadSize int32  // Bytes of payload
}

// Annotation describes an optional additional annotation which occurs within a call
type Annotation struct {
	TraceId       string
	EventId       string
	ParentEventId string

	Timestamp time.Time // Timestamp the event occured, can only be compared on the same machine

	Hostname string // Hostname this event originated from

	Content  string            // Arbitrary content, eg. debug output
	KeyValue map[string]string // Key value debug information
}
<commit_msg>Simplify domain<commit_after>package domain

import "time"

// Trace represents a full trace of a request
// comprised of a number of events and annotations
type Trace []Event

// EventType represents an Enum of types of Events which Phosphor can record
type EventType int

const (
	// RPC Calls
	Req = EventType(1) // Client Request dispatch
	Rsp = EventType(2) // Client Response received
	In  = EventType(3) // Server Request received
	Out = EventType(4) // Server Response dispatched

	// Developer initiated annotations
	Annotation = EventType(5)
)

// An Event represents a section of an RPC call between systems
type Event struct {
	TraceId       string // Global Trace Identifier
	EventId       string // Identifier for this event, non unique - eg. RPC calls would have 4 of these
	ParentEventId string // Parent event - eg. nested RPC calls

	Timestamp time.Time     // Timestamp the event occured, can only be compared on the same machine
	Duration  time.Duration // Optional: duration of the event, eg. RPC call

	Hostname    string // Hostname this event originated from
	Origin      string // Fully qualified name of the message origin
	Destination string // Fully qualified name of the message destination

	EventType EventType // The type of Event

	Payload     string            // The payload, eg. RPC body, or Annotation
	PayloadSize int32             // Bytes of payload
	KeyValue    map[string]string // Key value debug information
}
<|endoftext|>


<commit_before>package jsonrpc

import (
	"encoding/json"

	"github.com/nbusy/neptulon"
)

// Client is a client implementation for JSON-RPC 2.0 protocol for Neptulon framework.
// Client implementations in other programming languages might be provided in separate repositories so check the documentation.
type Client struct {
	conn *neptulon.Conn
}

// Dial creates a new client connection to a given network address with optional root CA and/or a client certificate (PEM encoded X.509 cert/key).
// Debug mode logs all raw TCP communication.
func Dial(addr string, rootCA []byte, clientCert []byte, clientCertKey []byte, debug bool) (*Client, error) {
	c, err := neptulon.Dial(addr, rootCA, clientCert, clientCertKey, debug)
	if err != nil {
		return nil, err
	}

	return &Client{conn: c}, nil
}

// ReadMsg reads a message off of a client connection and returns a JSON-RPC Message object.
func (c *Client) ReadMsg() (*Message, error) {
	_, data, err := c.conn.Read()
	if err != nil {
		return nil, err
	}

	var msg Message
	if err = json.Unmarshal(data, &msg); err != nil {
		return nil, err
	}

	return &msg, nil
}

// WriteRequest writes a JSON-RPC request to a client connection with structured params object and auto generated request ID.
func (c *Client) WriteRequest(method string, params struct{}) (reqID string, err error) {
	id, err := neptulon.GenUID()
	if err != nil {
		return "", err
	}

	return id, c.WriteMsg(Request{ID: id, Method: method, Params: params})
}

// WriteMsg writes any JSON-RPC message to a client connection.
func (c *Client) WriteMsg(msg interface{}) error {
	data, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	if _, err := c.conn.Write(data); err != nil {
		return err
	}

	return nil
}

// Close closes a client connection.
func (c *Client) Close() error {
	return c.conn.Close()
}
<commit_msg>add client.writerequestarray<commit_after>package jsonrpc

import (
	"encoding/json"

	"github.com/nbusy/neptulon"
)

// Client is a client implementation for JSON-RPC 2.0 protocol for Neptulon framework.
// Client implementations in other programming languages might be provided in separate repositories so check the documentation.
type Client struct {
	conn *neptulon.Conn
}

// Dial creates a new client connection to a given network address with optional root CA and/or a client certificate (PEM encoded X.509 cert/key).
// Debug mode logs all raw TCP communication.
func Dial(addr string, rootCA []byte, clientCert []byte, clientCertKey []byte, debug bool) (*Client, error) {
	c, err := neptulon.Dial(addr, rootCA, clientCert, clientCertKey, debug)
	if err != nil {
		return nil, err
	}

	return &Client{conn: c}, nil
}

// ReadMsg reads a message off of a client connection and returns a JSON-RPC Message object.
func (c *Client) ReadMsg() (*Message, error) {
	_, data, err := c.conn.Read()
	if err != nil {
		return nil, err
	}

	var msg Message
	if err = json.Unmarshal(data, &msg); err != nil {
		return nil, err
	}

	return &msg, nil
}

// WriteRequest writes a JSON-RPC request to a client connection with structured params object and auto generated request ID.
func (c *Client) WriteRequest(method string, params struct{}) (reqID string, err error) {
	id, err := neptulon.GenUID()
	if err != nil {
		return "", err
	}

	return id, c.WriteMsg(Request{ID: id, Method: method, Params: params})
}

// WriteRequestArr writes a JSON-RPC request to a client connection with array params object and auto generated request ID.
func (c *Client) WriteRequestArr(method string, params ...interface{}) (reqID string, err error) {
	id, err := neptulon.GenUID()
	if err != nil {
		return "", err
	}

	return id, c.WriteMsg(Request{ID: id, Method: method, Params: params})
}

// WriteMsg writes any JSON-RPC message to a client connection.
func (c *Client) WriteMsg(msg interface{}) error {
	data, err := json.Marshal(msg)
	if err != nil {
		return err
	}

	if _, err := c.conn.Write(data); err != nil {
		return err
	}

	return nil
}

// Close closes a client connection.
func (c *Client) Close() error {
	return c.conn.Close()
}
<|endoftext|>


<commit_before>// Tideland Go REST Server Library - JSON Web Token - Unit Tests
//
// Copyright (C) 2016 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package jwt_test

//--------------------
// IMPORTS
//--------------------

import (
	"testing"
	"time"

	"github.com/tideland/golib/audit"

	"github.com/tideland/gorest/jwt"
)

//--------------------
// TESTS
//--------------------

// TestCachePutGet tests the putting and getting of tokens
// to the cache.
func TestCachePutGet(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	assert.Logf("testing cache put and get")
	cache := jwt.NewCache(time.Minute, time.Minute)
	key := []byte("secret")
	claims := initClaims()
	jwtIn, err := jwt.Encode(claims, key, jwt.HS512)
	assert.Nil(err)
	cache.Put(jwtIn)
	token := jwtIn.String()
	jwtOut, ok := cache.Get(token)
	assert.True(ok)
	assert.Equal(jwtIn, jwtOut)
	jwtOut, ok = cache.Get("is.not.there")
	assert.False(ok)
	assert.Nil(jwtOut)
	err = cache.Stop()
	assert.Nil(err)
}

// EOF
<commit_msg>Added test for cache cleanup<commit_after>// Tideland Go REST Server Library - JSON Web Token - Unit Tests
//
// Copyright (C) 2016 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package jwt_test

//--------------------
// IMPORTS
//--------------------

import (
	"testing"
	"time"

	"github.com/tideland/golib/audit"

	"github.com/tideland/gorest/jwt"
)

//--------------------
// TESTS
//--------------------

// TestCachePutGet tests the putting and getting of tokens
// to the cache.
func TestCachePutGet(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	assert.Logf("testing cache put and get")
	cache := jwt.NewCache(time.Minute, time.Minute)
	key := []byte("secret")
	claims := initClaims()
	jwtIn, err := jwt.Encode(claims, key, jwt.HS512)
	assert.Nil(err)
	cache.Put(jwtIn)
	token := jwtIn.String()
	jwtOut, ok := cache.Get(token)
	assert.True(ok)
	assert.Equal(jwtIn, jwtOut)
	jwtOut, ok = cache.Get("is.not.there")
	assert.False(ok)
	assert.Nil(jwtOut)
	err = cache.Stop()
	assert.Nil(err)
}

// TestCacheCleanup tests the cleanup of the JWT cache.
func TestCacheCleanup(t *testing.T) {
	assert := audit.NewTestingAssertion(t, true)
	assert.Logf("testing cache cleanup")
	reset := jwt.SetCleanupInterval(time.Second)
	defer reset()
	cache := jwt.NewCache(time.Second, time.Second)
	key := []byte("secret")
	claims := initClaims()
	jwtIn, err := jwt.Encode(claims, key, jwt.HS512)
	assert.Nil(err)
	cache.Put(jwtIn)
	token := jwtIn.String()
	jwtOut, ok := cache.Get(token)
	assert.True(ok)
	assert.Equal(jwtIn, jwtOut)
	// Now wait a bit an try again.
	time.Sleep(5 * time.Second)
	jwtOut, ok = cache.Get(token)
	assert.False(ok)
	assert.Nil(jwtOut)
}

// EOF
<|endoftext|>


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

package bufio_test

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func ExampleWriter() {
	w := bufio.NewWriter(os.Stdout)
	fmt.Fprint(w, "Hello, ")
	fmt.Fprint(w, "world!")
	w.Flush() // Don't forget to flush!
	// Output: Hello, world!
}

// The simplest use of a Scanner, to read standard input as a set of lines.
func ExampleScanner_lines() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fmt.Println(scanner.Text()) // Println will add back the final '\n'
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}

// Use a Scanner to implement a simple word-count utility by scanning the
// input as a sequence of space-delimited tokens.
func ExampleScanner_words() {
	// An artificial input source.
	const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
	scanner := bufio.NewScanner(strings.NewReader(input))
	// Set the split function for the scanning operation.
	scanner.Split(bufio.ScanWords)
	// Count the words.
	count := 0
	for scanner.Scan() {
		count++
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading input:", err)
	}
	fmt.Printf("%d\n", count)
	// Output: 15
}

// Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
// 32-bit decimal input.
func ExampleScanner_custom() {
	// An artificial input source.
	const input = "1234 5678 1234567901234567890"
	scanner := bufio.NewScanner(strings.NewReader(input))
	// Create a custom split function by wrapping the existing ScanWords function.
	split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		advance, token, err = bufio.ScanWords(data, atEOF)
		if err == nil && token != nil {
			_, err = strconv.ParseInt(string(token), 10, 32)
		}
		return
	}
	// Set the split function for the scanning operation.
	scanner.Split(split)
	// Validate the input
	for scanner.Scan() {
		fmt.Printf("%s\n", scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		fmt.Printf("Invalid input: %s", err)
	}
	// Output:
	// 1234
	// 5678
	// Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
}

// Use a Scanner with a custom split function to parse a comma-separated
// list with an empty final value.
func ExampleScanner_emptyFinalToken() {
	// Comma-separated list; last entry is empty.
	const input = "1,2,3,4,"
	scanner := bufio.NewScanner(strings.NewReader(input))
	// Define a split function that separates on commas.
	onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		for i := 0; i < len(data); i++ {
			if data[i] == ',' {
				return i + 1, data[:i], nil
			}
		}
		if !atEOF {
			return 0, nil, nil
		}
		// There is one final token to be delivered, which may be the empty string.
		// Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
		// but does not trigger an error to be returned from Scan itself.
		return 0, data, bufio.ErrFinalToken
	}
	scanner.Split(onComma)
	// Scan.
	for scanner.Scan() {
		fmt.Printf("%q ", scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading input:", err)
	}
	// Output: "1" "2" "3" "4" ""
}
<commit_msg>bufio: add example for Scanner.Bytes<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package bufio_test

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func ExampleWriter() {
	w := bufio.NewWriter(os.Stdout)
	fmt.Fprint(w, "Hello, ")
	fmt.Fprint(w, "world!")
	w.Flush() // Don't forget to flush!
	// Output: Hello, world!
}

// The simplest use of a Scanner, to read standard input as a set of lines.
func ExampleScanner_lines() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fmt.Println(scanner.Text()) // Println will add back the final '\n'
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}

// Use return the most recent call to Scan as a []byte
func ExampleScanner_Bytes() {
	scanner := bufio.NewScanner(strings.NewReader("gopher"))
	for scanner.Scan() {
		fmt.Println(len(scanner.Bytes()) == 6)
	}
	// Output:
	// true
}

// Use a Scanner to implement a simple word-count utility by scanning the
// input as a sequence of space-delimited tokens.
func ExampleScanner_words() {
	// An artificial input source.
	const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
	scanner := bufio.NewScanner(strings.NewReader(input))
	// Set the split function for the scanning operation.
	scanner.Split(bufio.ScanWords)
	// Count the words.
	count := 0
	for scanner.Scan() {
		count++
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading input:", err)
	}
	fmt.Printf("%d\n", count)
	// Output: 15
}

// Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
// 32-bit decimal input.
func ExampleScanner_custom() {
	// An artificial input source.
	const input = "1234 5678 1234567901234567890"
	scanner := bufio.NewScanner(strings.NewReader(input))
	// Create a custom split function by wrapping the existing ScanWords function.
	split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		advance, token, err = bufio.ScanWords(data, atEOF)
		if err == nil && token != nil {
			_, err = strconv.ParseInt(string(token), 10, 32)
		}
		return
	}
	// Set the split function for the scanning operation.
	scanner.Split(split)
	// Validate the input
	for scanner.Scan() {
		fmt.Printf("%s\n", scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		fmt.Printf("Invalid input: %s", err)
	}
	// Output:
	// 1234
	// 5678
	// Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
}

// Use a Scanner with a custom split function to parse a comma-separated
// list with an empty final value.
func ExampleScanner_emptyFinalToken() {
	// Comma-separated list; last entry is empty.
	const input = "1,2,3,4,"
	scanner := bufio.NewScanner(strings.NewReader(input))
	// Define a split function that separates on commas.
	onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		for i := 0; i < len(data); i++ {
			if data[i] == ',' {
				return i + 1, data[:i], nil
			}
		}
		if !atEOF {
			return 0, nil, nil
		}
		// There is one final token to be delivered, which may be the empty string.
		// Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
		// but does not trigger an error to be returned from Scan itself.
		return 0, data, bufio.ErrFinalToken
	}
	scanner.Split(onComma)
	// Scan.
	for scanner.Scan() {
		fmt.Printf("%q ", scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading input:", err)
	}
	// Output: "1" "2" "3" "4" ""
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/flynn/flynn-host/types"
	"github.com/flynn/go-discoverd"
	"github.com/flynn/go-dockerclient"
	"github.com/flynn/go-flynn/cluster"
)

var cmdSchedule = &Command{
	Run:   runSchedule,
	Usage: "schedule <image>",
	Short: "schedules a job to run",
	Long:  `Schedules a (service) job to run by image name.`,
}

func runSchedule(cmd *Command, args []string) {
	if len(args) != 1 {
		cmd.printUsage()
		os.Exit(2)
	}
	err := discoverd.Connect(getTarget() + ":55002") // TODO: fix this
	assert(err)
	client, err := cluster.NewClient()
	assert(err)

	hosts, err := client.ListHosts()
	assert(err)
	var hostid string
	for id, _ := range hosts {
		hostid = id
		break
	}

	jobid := cluster.RandomJobID(args[0])
	config := docker.Config{
		Image: args[0],
		//Cmd:          []string{"start", "web"},
		Tty:          false,
		AttachStdin:  false,
		AttachStdout: false,
		AttachStderr: false,
		OpenStdin:    false,
		StdinOnce:    false,
	}

	jobReq := &host.AddJobsReq{
		Incremental: true,
		HostJobs: map[string][]*host.Job{
			hostid: {{ID: jobid, Config: &config, TCPPorts: 1}}},
	}

	hostClient, err := client.ConnectHost(hostid)
	assert(err)

	events := make(chan *host.Event)
	addr := make(chan string)
	hostClient.StreamEvents(jobid, events)
	go func() {
		for event := range events {
			if event.Event == "start" {
				addr <- getAddr(hostClient, hostid, jobid)
			} else {
				fmt.Println("Service was not scheduled")
				os.Exit(1)
			}
		}
	}()
	_, err = client.AddJobs(jobReq)
	assert(err)

	if a := <-addr; a != "" {
		fmt.Println(jobid + " created, listening at " + a)
	} else {
		fmt.Println("Service was scheduled but no exposed port found")
		os.Exit(1)
	}

}

func getAddr(host cluster.Host, hostid, jobid string) string {
	services, err := discoverd.Services("flynn-host", discoverd.DefaultTimeout)
	var service *discoverd.Service
	for _, s := range services {
		if s.Attrs["id"] == hostid {
			service = s
			break
		}
	}
	if service == nil {
		return ""
	}
	job, err := host.GetJob(jobid)
	assert(err)
	for portspec := range job.Job.Config.ExposedPorts {
		return service.Host + ":" + strings.Split(portspec, "/")[0]
	}
	return ""
}
<commit_msg>Handle event stream properly<commit_after>package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/flynn/flynn-host/types"
	"github.com/flynn/go-discoverd"
	"github.com/flynn/go-dockerclient"
	"github.com/flynn/go-flynn/cluster"
)

var cmdSchedule = &Command{
	Run:   runSchedule,
	Usage: "schedule <image>",
	Short: "schedules a job to run",
	Long:  `Schedules a (service) job to run by image name.`,
}

func runSchedule(cmd *Command, args []string) {
	if len(args) != 1 {
		cmd.printUsage()
		os.Exit(2)
	}
	err := discoverd.Connect(getTarget() + ":55002") // TODO: fix this
	assert(err)
	client, err := cluster.NewClient()
	assert(err)

	hosts, err := client.ListHosts()
	assert(err)
	var hostid string
	for id, _ := range hosts {
		hostid = id
		break
	}

	jobid := cluster.RandomJobID(args[0])
	config := docker.Config{
		Image: args[0],
		//Cmd:          []string{"start", "web"},
		Tty:          false,
		AttachStdin:  false,
		AttachStdout: false,
		AttachStderr: false,
		OpenStdin:    false,
		StdinOnce:    false,
	}

	jobReq := &host.AddJobsReq{
		Incremental: true,
		HostJobs: map[string][]*host.Job{
			hostid: {{ID: jobid, Config: &config, TCPPorts: 1}}},
	}

	hostClient, err := client.ConnectHost(hostid)
	assert(err)

	events := make(chan *host.Event)
	addr := make(chan string)
	hostClient.StreamEvents(jobid, events)
	go func() {
		for event := range events {
			switch event.Event {
			case "start":
				addr <- getAddr(hostClient, hostid, jobid)
				return
			case "error", "stop":
				fmt.Println("Scheduling error")
				// TODO: read error from host
				os.Exit(1)
			}
		}
	}()
	_, err = client.AddJobs(jobReq)
	assert(err)

	if a := <-addr; a != "" {
		fmt.Println(jobid + " created, listening at " + a)
	} else {
		fmt.Println("Service was scheduled but no exposed port found")
		os.Exit(1)
	}

}

func getAddr(host cluster.Host, hostid, jobid string) string {
	services, err := discoverd.Services("flynn-host", discoverd.DefaultTimeout)
	var service *discoverd.Service
	for _, s := range services {
		if s.Attrs["id"] == hostid {
			service = s
			break
		}
	}
	if service == nil {
		return ""
	}
	job, err := host.GetJob(jobid)
	assert(err)
	for portspec := range job.Job.Config.ExposedPorts {
		return service.Host + ":" + strings.Split(portspec, "/")[0]
	}
	return ""
}
<|endoftext|>


<commit_before>// The package provides methods for converting amounts between currencies. The
// exchange rates are provided by the ECB (http://www.ecb.europa.eu/).
//
// Author: Michael Banzon
package currency

import (
	"time"
)

type CurrencyConverter struct {
	date       time.Time
	currencies map[string]float64
}

func NewConverter() (*CurrencyConverter, error) {
	currencyTime, currencies, err := parseEcbData()
	if err != nil {
		return nil, err
	}
	converter := CurrencyConverter{date: currencyTime, currencies: currencies}
	return &converter, nil
}
<commit_msg>Added constants for euro currency and error message.<commit_after>// The package provides methods for converting amounts between currencies. The
// exchange rates are provided by the ECB (http://www.ecb.europa.eu/).
//
// Author: Michael Banzon
package currency

import (
	"time"
)

const (
	eur     = "EUR"
	unknown = "Unknown currency: %s"
)

type CurrencyConverter struct {
	date       time.Time
	currencies map[string]float64
}

func NewConverter() (*CurrencyConverter, error) {
	currencyTime, currencies, err := parseEcbData()
	if err != nil {
		return nil, err
	}
	converter := CurrencyConverter{date: currencyTime, currencies: currencies}
	return &converter, nil
}

func (c *CurrencyConverter) Convert(amount float64, to string, from string) (float64, error) {
	return 0, nil
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Nicolas Lamirault <nicolas.lamirault@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.

package travisci

import (
	"testing"
)

func TestTravisClient(t *testing.T) {
	client := NewClient("0246813579")
	if client.UserAgent != "guzuta/0.2.0" {
		t.Fatalf("Invalid user agent : %s", client.UserAgent)
	}
}
<commit_msg>FIX user agent test<commit_after>// Copyright (C) 2015 Nicolas Lamirault <nicolas.lamirault@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.

package travisci

import (
	"testing"
)

func TestTravisClient(t *testing.T) {
	client := NewClient("0246813579")
	if client.UserAgent != "guzuta/0.3.0" {
		t.Fatalf("Invalid user agent : %s", client.UserAgent)
	}
}
<|endoftext|>


<commit_before>package generate

const modelTemplate = `package {{package_name}}

import (
	{{#each model.Imports as |i|}}"{{i}}"
	{{/each}}
)

type {{model_name}} struct {
	{{#each model.Attributes as |a|}}{{a}}
	{{/each}}
}

// String is not required by pop and may be deleted
func ({{char}} {{model_name}}) String() string {
	b, _ := json.Marshal({{char}})
	return string(b)
}

// {{plural_model_name}} is not required by pop and may be deleted
type {{plural_model_name}} []{{model_name}}

// String is not required by pop and may be deleted
func ({{char}} {{plural_model_name}}) String() string {
	b, _ := json.Marshal({{char}})
	return string(b)
}

// Validate gets run everytime you call a "pop.Validate" method.
// This method is not required and may be deleted.
func ({{char}} *{{model_name}}) Validate(tx *pop.Connection) (*validate.Errors, error) {
	{{#if model.ValidatableAttributes }}
	return validate.Validate(
		{{#each model.ValidatableAttributes as |a|}}
		&validators.{{capitalize a.GoType}}IsPresent{Field: {{char}}.{{a.Names.Proper}}, Name: "{{a.Names.Proper}}"},{{/each}}
	), nil
	{{ else }}
		return validate.NewErrors(), nil
	{{/if}}
}

// ValidateSave gets run everytime you call "pop.ValidateSave" method.
// This method is not required and may be deleted.
func ({{char}} *{{model_name}}) ValidateSave(tx *pop.Connection) (*validate.Errors, error) {
	return validate.NewErrors(), nil
}

// ValidateUpdate gets run everytime you call "pop.ValidateUpdate" method.
// This method is not required and may be deleted.
func ({{char}} *{{model_name}}) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
	return validate.NewErrors(), nil
}
`

const modelTestTemplate = `package {{package_name}}_test

import "testing"

func Test_{{model_name}}(t *testing.T) {
	t.Fatal("This test needs to be implemented!")
}
`
<commit_msg>Fixed issue #38.<commit_after>package generate

const modelTemplate = `package {{package_name}}

import (
	{{#each model.Imports as |i|}}"{{i}}"
	{{/each}}
)

type {{model_name}} struct {
	{{#each model.Attributes as |a|}}{{a}}
	{{/each}}
}

// String is not required by pop and may be deleted
func ({{char}} {{model_name}}) String() string {
	j{{char}}, _ := json.Marshal({{char}})
	return string(j{{char}})
}

// {{plural_model_name}} is not required by pop and may be deleted
type {{plural_model_name}} []{{model_name}}

// String is not required by pop and may be deleted
func ({{char}} {{plural_model_name}}) String() string {
	j{{char}}, _ := json.Marshal({{char}})
	return string(j{{char}})
}

// Validate gets run everytime you call a "pop.Validate" method.
// This method is not required and may be deleted.
func ({{char}} *{{model_name}}) Validate(tx *pop.Connection) (*validate.Errors, error) {
	{{#if model.ValidatableAttributes }}
	return validate.Validate(
		{{#each model.ValidatableAttributes as |a|}}
		&validators.{{capitalize a.GoType}}IsPresent{Field: {{char}}.{{a.Names.Proper}}, Name: "{{a.Names.Proper}}"},{{/each}}
	), nil
	{{ else }}
		return validate.NewErrors(), nil
	{{/if}}
}

// ValidateSave gets run everytime you call "pop.ValidateSave" method.
// This method is not required and may be deleted.
func ({{char}} *{{model_name}}) ValidateSave(tx *pop.Connection) (*validate.Errors, error) {
	return validate.NewErrors(), nil
}

// ValidateUpdate gets run everytime you call "pop.ValidateUpdate" method.
// This method is not required and may be deleted.
func ({{char}} *{{model_name}}) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
	return validate.NewErrors(), nil
}
`

const modelTestTemplate = `package {{package_name}}_test

import "testing"

func Test_{{model_name}}(t *testing.T) {
	t.Fatal("This test needs to be implemented!")
}
`
<|endoftext|>


<commit_before>package tarantool

type BinaryPacketPool struct {
	queue chan *BinaryPacket
}

func newPackedPacketPool() *BinaryPacketPool {
	return &BinaryPacketPool{
		queue: make(chan *BinaryPacket, 512),
	}
}

func (p *BinaryPacketPool) GetWithID(requestID uint64) (pp *BinaryPacket) {
	select {
	case pp = <-p.queue:
		pp.Reset()
		pp.pool = p
	default:
		pp = &BinaryPacket{}
		pp.Reset()
	}
	pp.packet.requestID = requestID
	return
}

func (p *BinaryPacketPool) Get() *BinaryPacket {
	return p.GetWithID(0)
}

func (p *BinaryPacketPool) Put(pp *BinaryPacket) {
	pp.pool = nil
	p.queue <- pp
}

func (p *BinaryPacketPool) Close() {
	close(p.queue)
}
<commit_msg>Fix the binary packet pool and x2 its capacity<commit_after>package tarantool

type BinaryPacketPool struct {
	queue chan *BinaryPacket
}

func newPackedPacketPool() *BinaryPacketPool {
	return &BinaryPacketPool{
		queue: make(chan *BinaryPacket, 1024),
	}
}

func (p *BinaryPacketPool) GetWithID(requestID uint64) (pp *BinaryPacket) {
	select {
	case pp = <-p.queue:
	default:
		pp = &BinaryPacket{}
	}

	pp.Reset()
	pp.pool = p
	pp.packet.requestID = requestID
	return
}

func (p *BinaryPacketPool) Get() *BinaryPacket {
	return p.GetWithID(0)
}

func (p *BinaryPacketPool) Put(pp *BinaryPacket) {
	pp.pool = nil
	select {
	case p.queue <- pp:
	default:
	}
}

func (p *BinaryPacketPool) Close() {
	close(p.queue)
}
<|endoftext|>