func NewWebSocketApp(urls []route.Uri, rPort uint16, mbusClient yagnats.NATSConn, delay time.Duration) *TestApp { app := NewTestApp(urls, rPort, mbusClient, nil, "") app.AddHandler("/", func(w http.ResponseWriter, r *http.Request) { defer ginkgo.GinkgoRecover() Expect(r.Header.Get("Upgrade")).To(Equal("websocket")) Expect(r.Header.Get("Connection")).To(Equal("upgrade")) conn, _, err := w.(http.Hijacker).Hijack() x := test_util.NewHttpConn(conn) resp := test_util.NewResponse(http.StatusSwitchingProtocols) resp.Header.Set("Upgrade", "websocket") resp.Header.Set("Connection", "upgrade") time.Sleep(delay) x.WriteResponse(resp) Expect(err).ToNot(HaveOccurred()) x.CheckLine("hello from client") x.WriteLine("hello from server") }) return app }
// NewSampleRepoTest creates a function for a new ginkgo test case that will instantiate a template // from a url, kick off the buildconfig defined in that template, wait for the build/deploy, // and then confirm the application is serving an expected string value. func NewSampleRepoTest(c SampleRepoConfig) func() { return func() { defer g.GinkgoRecover() var oc = exutil.NewCLI(c.repoName+"-repo-test", exutil.KubeConfigPath()) g.JustBeforeEach(func() { g.By("Waiting for builder service account") err := exutil.WaitForBuilderAccount(oc.KubeREST().ServiceAccounts(oc.Namespace())) o.Expect(err).NotTo(o.HaveOccurred()) }) g.Describe("Building "+c.repoName+" app from new-app", func() { g.It(fmt.Sprintf("should build a "+c.repoName+" image and run it in a pod"), func() { oc.SetOutputDir(exutil.TestContext.OutputDir) exutil.CheckOpenShiftNamespaceImageStreams(oc) g.By(fmt.Sprintf("calling oc new-app with the " + c.repoName + " example template")) err := oc.Run("new-app").Args("-f", c.templateURL).Execute() o.Expect(err).NotTo(o.HaveOccurred()) // all the templates automatically start a build. buildName := c.buildConfigName + "-1" g.By("expecting the build is in the Complete phase") err = exutil.WaitForABuild(oc.REST().Builds(oc.Namespace()), buildName, exutil.CheckBuildSuccessFn, exutil.CheckBuildFailedFn) if err != nil { exutil.DumpBuildLogs(c.buildConfigName, oc) } o.Expect(err).NotTo(o.HaveOccurred()) g.By("expecting the app deployment to be complete") err = exutil.WaitForADeploymentToComplete(oc.KubeREST().ReplicationControllers(oc.Namespace()), c.deploymentConfigName, oc) o.Expect(err).NotTo(o.HaveOccurred()) if len(c.dbDeploymentConfigName) > 0 { g.By("expecting the db deployment to be complete") err = exutil.WaitForADeploymentToComplete(oc.KubeREST().ReplicationControllers(oc.Namespace()), c.dbDeploymentConfigName, oc) o.Expect(err).NotTo(o.HaveOccurred()) } g.By("expecting the service is available") serviceIP, err := oc.Run("get").Args("service", c.serviceName).Template("{{ .spec.clusterIP }}").Output() o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(serviceIP).ShouldNot(o.Equal("")) g.By("expecting an endpoint is available") err = oc.KubeFramework().WaitForAnEndpoint(c.serviceName) o.Expect(err).NotTo(o.HaveOccurred()) g.By("verifying string from app request") response, err := exutil.FetchURL("http://"+serviceIP+":8080"+c.appPath, time.Duration(30*time.Second)) o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(response).Should(o.ContainSubstring(c.expectedString)) }) }) } }
package images import ( "fmt" g "github.com/onsi/ginkgo" o "github.com/onsi/gomega" "time" exutil "github.com/openshift/origin/test/extended/util" "github.com/openshift/origin/test/extended/util/db" ) var _ = g.Describe("[images][mongodb] openshift mongodb image", func() { defer g.GinkgoRecover() templatePath := exutil.FixturePath("..", "..", "examples", "db-templates", "mongodb-ephemeral-template.json") oc := exutil.NewCLI("mongodb-create", exutil.KubeConfigPath()).Verbose() g.Describe("creating from a template", func() { g.It(fmt.Sprintf("should process and create the %q template", templatePath), func() { g.By("creating a new app") o.Expect(oc.Run("new-app").Args("-f", templatePath).Execute()).Should(o.Succeed()) g.By("waiting for the deployment to complete") err := exutil.WaitForADeploymentToComplete(oc.KubeREST().ReplicationControllers(oc.Namespace()), "mongodb") if err != nil { exutil.DumpDeploymentLogs("mongodb", oc) }
func (runner Runner) Run(signals <-chan os.Signal, ready chan<- struct{}) error { defer ginkgo.GinkgoRecover() tmpdir, err := ioutil.TempDir("", "postgres") Expect(err).NotTo(HaveOccurred()) currentUser, err := user.Current() Expect(err).NotTo(HaveOccurred()) var initCmd, startCmd *exec.Cmd initdbPath, err := exec.LookPath("initdb") Expect(err).NotTo(HaveOccurred()) postgresPath, err := exec.LookPath("postgres") Expect(err).NotTo(HaveOccurred()) initdb := initdbPath + " -U postgres -D " + tmpdir postgres := fmt.Sprintf("%s -D %s -h 127.0.0.1 -p %d", postgresPath, tmpdir, runner.Port) if currentUser.Uid == "0" { pgUser, err := user.Lookup("postgres") Expect(err).NotTo(HaveOccurred()) uid, err := strconv.Atoi(pgUser.Uid) Expect(err).NotTo(HaveOccurred()) gid, err := strconv.Atoi(pgUser.Gid) Expect(err).NotTo(HaveOccurred()) err = os.Chown(tmpdir, uid, gid) Expect(err).NotTo(HaveOccurred()) initCmd = exec.Command("su", "postgres", "-c", initdb) startCmd = exec.Command("su", "postgres", "-c", postgres) } else { initCmd = exec.Command("bash", "-c", initdb) startCmd = exec.Command("bash", "-c", postgres) } session, err := gexec.Start( initCmd, gexec.NewPrefixedWriter("[o][initdb] ", ginkgo.GinkgoWriter), gexec.NewPrefixedWriter("[e][initdb] ", ginkgo.GinkgoWriter), ) Expect(err).NotTo(HaveOccurred()) <-session.Exited Expect(session).To(gexec.Exit(0)) ginkgoRunner := &ginkgomon.Runner{ Name: "postgres", Command: startCmd, AnsiColorCode: "90m", StartCheck: "database system is ready to accept connections", Cleanup: func() { os.RemoveAll(tmpdir) }, } return ginkgoRunner.Run(signals, ready) }
func (r *Runner) Run(sigChan <-chan os.Signal, ready chan<- struct{}) error { defer ginkgo.GinkgoRecover() allOutput := gbytes.NewBuffer() debugWriter := gexec.NewPrefixedWriter( fmt.Sprintf("\x1b[32m[d]\x1b[%s[%s]\x1b[0m ", r.AnsiColorCode, r.Name), ginkgo.GinkgoWriter, ) session, err := gexec.Start( r.Command, gexec.NewPrefixedWriter( fmt.Sprintf("\x1b[32m[o]\x1b[%s[%s]\x1b[0m ", r.AnsiColorCode, r.Name), io.MultiWriter(allOutput, ginkgo.GinkgoWriter), ), gexec.NewPrefixedWriter( fmt.Sprintf("\x1b[91m[e]\x1b[%s[%s]\x1b[0m ", r.AnsiColorCode, r.Name), io.MultiWriter(allOutput, ginkgo.GinkgoWriter), ), ) Ω(err).ShouldNot(HaveOccurred()) fmt.Fprintf(debugWriter, "spawned %s (pid: %d)\n", r.Command.Path, r.Command.Process.Pid) r.session = session if r.sessionReady != nil { close(r.sessionReady) } startCheckDuration := r.StartCheckTimeout if startCheckDuration == 0 { startCheckDuration = 5 * time.Second } var startCheckTimeout <-chan time.Time if r.StartCheck != "" { startCheckTimeout = time.After(startCheckDuration) } detectStartCheck := allOutput.Detect(r.StartCheck) for { select { case <-detectStartCheck: // works even with empty string allOutput.CancelDetects() startCheckTimeout = nil detectStartCheck = nil close(ready) case <-startCheckTimeout: // clean up hanging process session.Kill().Wait() // fail to start return fmt.Errorf( "did not see %s in command's output within %s. full output:\n\n%s", r.StartCheck, startCheckDuration, string(allOutput.Contents()), ) case signal := <-sigChan: session.Signal(signal) case <-session.Exited: if r.Cleanup != nil { r.Cleanup() } if session.ExitCode() == 0 { return nil } return fmt.Errorf("exit status %d", session.ExitCode()) } } }
func (h *TestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer ginkgo.GinkgoRecover() if len(h.Requests) <= h.CallCount { h.logError("Index out of range! Test server called too many times. Final Request:", r.Method, r.RequestURI) return } tester := h.Requests[h.CallCount] h.CallCount++ // match method if tester.Method != r.Method { h.logError("Method does not match.\nExpected: %s\nActual: %s", tester.Method, r.Method) } // match path paths := strings.Split(tester.Path, "?") if paths[0] != r.URL.Path { h.logError("Path does not match.\nExpected: %s\nActual: %s", paths[0], r.URL.Path) } // match query string if len(paths) > 1 { actualValues, _ := url.ParseQuery(r.URL.RawQuery) expectedValues, _ := url.ParseQuery(paths[1]) if !urlQueryContains(actualValues, expectedValues) { h.logError("Query string does not match.\nExpected: %s\nActual: %s", paths[1], r.URL.RawQuery) } } for key, values := range tester.Header { key = http.CanonicalHeaderKey(key) actualValues := strings.Join(r.Header[key], ";") expectedValues := strings.Join(values, ";") if key == "Authorization" && !strings.Contains(actualValues, expectedValues) { h.logError("%s header is not contained in actual value.\nExpected: %s\nActual: %s", key, expectedValues, actualValues) } if key != "Authorization" && actualValues != expectedValues { h.logError("%s header did not match.\nExpected: %s\nActual: %s", key, expectedValues, actualValues) } } // match custom request matcher if tester.Matcher != nil { tester.Matcher(r) } // set response headers header := w.Header() for name, values := range tester.Response.Header { if len(values) < 1 { continue } header.Set(name, values[0]) } // write response w.WriteHeader(tester.Response.Status) fmt.Fprintln(w, tester.Response.Body) }