"testing"

	. "github.com/ably/ably-go/Godeps/_workspace/src/github.com/onsi/ginkgo"
	. "github.com/ably/ably-go/Godeps/_workspace/src/github.com/onsi/gomega"
)

func TestAbly(t *testing.T) {
	t.Parallel()
	RegisterFailHandler(Fail)
	RunSpecs(t, "Ably Suite")
}

var (
	testApp *testutil.Sandbox
	client  *ably.RestClient
	channel *ably.RestChannel
)

var _ = BeforeSuite(func() {
	app, err := testutil.NewSandbox(nil)
	Expect(err).NotTo(HaveOccurred())
	testApp = app
})

var _ = BeforeEach(func() {
	cl, err := ably.NewRestClient(testApp.Options(nil))
	Expect(err).NotTo(HaveOccurred())
	client = cl
	channel = client.Channel("test")
})
var _ = Describe("RestClient", func() {
	var (
		server *httptest.Server

		newHTTPClientMock = func(srv *httptest.Server) *http.Client {
			return &http.Client{
				Transport: &http.Transport{
					Proxy: func(*http.Request) (*url.URL, error) { return url.Parse(srv.URL) },
				},
			}
		}
	)

	Context("with a failing request", func() {
		var client *ably.RestClient

		BeforeEach(func() {
			server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(404)
				w.Header().Set("Content-Type", "application/json")
				fmt.Fprintf(w, `{"message":"Not Found"}`)
			}))

			options := &ably.ClientOptions{NoTLS: true, HTTPClient: newHTTPClientMock(server)}

			var err error
			client, err = ably.NewRestClient(testApp.Options(options))
			Expect(err).NotTo(HaveOccurred())

			Expect(err).NotTo(HaveOccurred())