<commit_before>package main_test

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"code.cloudfoundry.org/cf-tcp-router/cmd/router-configurer/testrunner"
	"code.cloudfoundry.org/cf-tcp-router/testutil"
	"code.cloudfoundry.org/cf-tcp-router/utils"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"code.cloudfoundry.org/routing-api"
	routingtestrunner "code.cloudfoundry.org/routing-api/cmd/routing-api/testrunner"
	"code.cloudfoundry.org/routing-api/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
	"github.com/onsi/gomega/ghttp"
	"github.com/tedsuo/ifrit"
)

var _ = Describe("Main", func() {

	var (
		routerGroupGuid string
	)

	getServerPort := func(serverURL string) string {
		endpoints := strings.Split(serverURL, ":")
		Expect(endpoints).To(HaveLen(3))
		return endpoints[2]
	}

	oAuthServer := func(logger lager.Logger) *ghttp.Server {
		server := ghttp.NewUnstartedServer()
		var basePath = path.Join("..", "..", "fixtures", "certs")
		absPath, err := filepath.Abs(basePath)
		Expect(err).ToNot(HaveOccurred())
		cert, err := tls.LoadX509KeyPair(filepath.Join(absPath, "server.pem"), filepath.Join(absPath, "server.key"))
		Expect(err).ToNot(HaveOccurred())

		tlsConfig := &tls.Config{
			Certificates: []tls.Certificate{cert},
		}
		server.HTTPTestServer.TLS = tlsConfig
		server.AllowUnhandledRequests = true
		server.HTTPTestServer.StartTLS()

		publicKey := "-----BEGIN PUBLIC KEY-----\\n" +
			"<KEY>" +
			"<KEY>" +
			"<KEY>" +
			"<KEY>" +
			"-----END PUBLIC KEY-----"

		data := fmt.Sprintf("{\"alg\":\"rsa\", \"value\":\"%s\"}", publicKey)
		server.RouteToHandler("GET", "/token_key",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/token_key"),
				ghttp.RespondWith(http.StatusOK, data)),
		)

		server.RouteToHandler("POST", "/oauth/token",
			func(w http.ResponseWriter, req *http.Request) {
				jsonBytes := []byte(`{"access_token":"some-token", "expires_in":10}`)
				w.Write(jsonBytes)
			},
		)
		logger.Info("starting-oauth-server", lager.Data{"address": server.URL()})
		return server
	}

	getRouterGroupGuid := func(port uint16) string {
		client := routing_api.NewClient(fmt.Sprintf("http://127.0.0.1:%d", port), false)
		routerGroups, err := client.RouterGroups()
		Expect(err).NotTo(HaveOccurred())
		Expect(routerGroups).ToNot(HaveLen(0))
		return routerGroups[0].Guid
	}

	routingApiServer := func(logger lager.Logger) ifrit.Process {
		server := routingtestrunner.New(routingAPIBinPath, routingAPIArgs)
		logger.Info("starting-routing-api-server")
		process := ifrit.Invoke(server)
		routerGroupGuid = getRouterGroupGuid(routingAPIArgs.Port)
		return process
	}

	generateConfigFile := func(oauthServerPort, routingApiServerPort string, routingApiAuthDisabled bool) string {
		randomConfigFileName := testutil.RandomFileName("router_configurer", ".yml")
		configFile := path.Join(os.TempDir(), randomConfigFileName)

		cfgString := `---
oauth:
  token_endpoint: "127.0.0.1"
  skip_ssl_validation: false
  ca_certs: %s
  client_name: "someclient"
  client_secret: "somesecret"
  port: %s
routing_api:
  auth_disabled: %t
  uri: http://127.0.0.1
  port: %s
`
		var caCertsPath = path.Join("..", "..", "fixtures", "certs", "uaa-ca.pem")<commit_msg>Added retry logic to routing_api connection in unit test<commit_after>package main_test

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"code.cloudfoundry.org/cf-tcp-router/cmd/router-configurer/testrunner"
	"code.cloudfoundry.org/cf-tcp-router/testutil"
	"code.cloudfoundry.org/cf-tcp-router/utils"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"code.cloudfoundry.org/routing-api"
	routingtestrunner "code.cloudfoundry.org/routing-api/cmd/routing-api/testrunner"
	"code.cloudfoundry.org/routing-api/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gbytes"
	"github.com/onsi/gomega/gexec"
	"github.com/onsi/gomega/ghttp"
	"github.com/tedsuo/ifrit"
)

var _ = Describe("Main", func() {

	var (
		routerGroupGuid string
	)

	getServerPort := func(serverURL string) string {
		endpoints := strings.Split(serverURL, ":")
		Expect(endpoints).To(HaveLen(3))
		return endpoints[2]
	}

	oAuthServer := func(logger lager.Logger) *ghttp.Server {
		server := ghttp.NewUnstartedServer()
		var basePath = path.Join("..", "..", "fixtures", "certs")
		absPath, err := filepath.Abs(basePath)
		Expect(err).ToNot(HaveOccurred())
		cert, err := tls.LoadX509KeyPair(filepath.Join(absPath, "server.pem"), filepath.Join(absPath, "server.key"))
		Expect(err).ToNot(HaveOccurred())

		tlsConfig := &tls.Config{
			Certificates: []tls.Certificate{cert},
		}
		server.HTTPTestServer.TLS = tlsConfig
		server.AllowUnhandledRequests = true
		server.HTTPTestServer.StartTLS()

		publicKey := "-----BEGIN PUBLIC KEY-----\\n" +
			"<KEY>" +
			"<KEY>" +
			"<KEY>" +
			"spULZVNRxq7veq/fzwIDAQAB\\n" +
			"-----END PUBLIC KEY-----"

		data := fmt.Sprintf("{\"alg\":\"rsa\", \"value\":\"%s\"}", publicKey)
		server.RouteToHandler("GET", "/token_key",
			ghttp.CombineHandlers(
				ghttp.VerifyRequest("GET", "/token_key"),
				ghttp.RespondWith(http.StatusOK, data)),
		)

		server.RouteToHandler("POST", "/oauth/token",
			func(w http.ResponseWriter, req *http.Request) {
				jsonBytes := []byte(`{"access_token":"<PASSWORD>-token", "expires_in":10}`)
				w.Write(jsonBytes)
			},
		)
		logger.Info("starting-oauth-server", lager.Data{"address": server.URL()})
		return server
	}

	getRouterGroupGuid := func(port uint16) string {
		client := routing_api.NewClient(fmt.Sprintf("http://127.0.0.1:%d", port), false)
		var routerGroups []models.RouterGroup
		Eventually(func() error {
			var err error
			routerGroups, err = client.RouterGroups()
			return err
		}, "30s", "1s").ShouldNot(HaveOccurred(), "Failed to connect to Routing API server after 30s.")
		Expect(routerGroups).ToNot(HaveLen(0))
		return routerGroups[0].Guid
	}

	routingApiServer := func(logger lager.Logger) ifrit.Process {
		server := routingtestrunner.New(routingAPIBinPath, routingAPIArgs)
		logger.Info("starting-routing-api-server")
		process := ifrit.Invoke(server)
		routerGroupGuid = getRouterGroupGuid(routingAPIArgs.Port)
		return process
	}

	generateConfigFile := func(oauthServerPort, routingApiServerPort string, routingApiAuthDisabled bool) string {
		randomConfigFileName := testutil.RandomFileName("router_configurer", ".yml")
		configFile := path.Join(os.TempDir(), randomConfigFileName)

		cfgString := `---
oauth:
  token_endpoint: "127.0.0.1"
  skip_ssl_validation: false
  ca_certs: %s
  client_name: "someclient"
  client_secret: "somesecret"
  port: %s
routing_api:
  auth_disabled: %t
  uri: http://127.0.0.1
  port: %s
`
		var caCertsPath = path.Join("..", "..", "fixtures", "certs", "uaa-ca.pem")
{'fraction_non_alphanumeric': 0.172279792746114, 'fraction_numerical': 0.009211283822682787, 'mean_word_length': 4.501979414093428, 'pattern_counts': {'":': 12, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 6, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4918825', 'n_tokens_mistral': 2766, 'n_tokens_neox': 2555, 'n_words': 385}