func MustNewWinPdhCollector(name, prefix string, opts config.Config_win_pdh_collector) *win_pdh_collector { c := &win_pdh_collector{ name: name, enabled: true, prefix: prefix, interval: opts.Interval.MustDuration(time.Second), config: opts, hPdh: pdh.NewPdhCollector(), map_queries: make(map[string]config.Config_win_pdh_query), } for _, q := range opts.Queries { if q.Metric == "" { logging.Errorf("Error Phd Collector metric is empty: %# v", pretty.Formatter(q)) continue } c.hPdh.AddEnglishCounter(q.Query) if q.Tags == nil { q.Tags = newcore.AddTags.Copy() } if opts.Query_to_tag == true || q.Query_to_tag == true { q.Tags["query"] = q.Query } c.map_queries[q.Query] = q } logging.Tracef("MustNewWinPdhCollector:opts.Queries: %# v", pretty.Formatter(opts.Queries)) logging.Tracef("MustNuewWinPdhCollector c.map_queries: %# v", pretty.Formatter(c.map_queries)) return c }
func TestGetChart(t *testing.T) { server, zillow := testFixtures(t, chartPath, func(values url.Values) { assertOnlyParam(t, values, zpidParam, zpid) assertOnlyParam(t, values, unitTypeParam, unitType) assertOnlyParam(t, values, widthParam, strconv.Itoa(width)) assertOnlyParam(t, values, heightParam, strconv.Itoa(height)) }) defer server.Close() request := ChartRequest{Zpid: zpid, UnitType: unitType, Width: width, Height: height} result, err := zillow.GetChart(request) if err != nil { t.Fatal(err) } expected := &ChartResult{ XMLName: xml.Name{Space: "http://www.zillowstatic.com/vstatic/8d9b5f1/static/xsd/Chart.xsd", Local: "chart"}, Request: request, Message: Message{ Text: "Request successfully processed", Code: 0, }, Url: "http://www.zillow.com/app?chartDuration=1year&chartType=partner&height=150&page=webservice%2FGetChart&service=chart&showPercent=true&width=300&zpid=48749425", } if !reflect.DeepEqual(result, expected) { t.Fatalf("expected:\n %#v\n\n but got:\n %#v\n\n diff:\n %s\n", pretty.Formatter(expected), pretty.Formatter(result), pretty.Diff(expected, result)) } }
func TestCopy_MakeTarStream_SingleFileToDir(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "foo.txt": "hello", }) defer os.RemoveAll(tmpDir) assertions := [][3]string{ {"foo.txt", "foo", "foo"}, {"foo.txt", "foo/", "foo/foo.txt"}, } for _, a := range assertions { includes := []string{a[0]} excludes := []string{} dest := a[1] t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("dest: %# v", pretty.Formatter(dest)) stream, err := makeTarStream(tmpDir, dest, "COPY", includes, excludes, nil) if err != nil { t.Fatal(err) } out := writeReadTar(t, tmpDir, stream.tar) assertion := strings.Join([]string{a[2]}, "\n") + "\n" assert.Equal(t, assertion, out, "bad tar content for COPY %s %s", a[0], a[1]) } }
func main() { r := Rocket{ name: "Audrey Mark 0", mass: Measurement{value: 0.05, units: "kg"}, area: Measurement{value: 0.0004, units: "m^2"}, drag: Measurement{value: 0.75, units: ""}, //seems reasonable max_velocity: Measurement{value: 0, units: "m/s"}, max_altitude: Measurement{value: 0, units: "m"}, //https://en.wikipedia.org/wiki/Drag_coefficient } //estimated rocket e := Engine{ product_number: 1598, name: "A8-3", max_payload: Measurement{value: 0.085, units: "kg"}, delay: Measurement{value: 3, units: "s"}, impulse: Measurement{value: 2.5, units: "N-s"}, thrust: Measurement{value: 10.7, units: "N"}, mass: Measurement{value: 0.0162, units: "kg"}, propellant_mass: Measurement{value: 0.00312, units: "kg"}, burn_time: Measurement{value: 0.5, units: "s"}, } //example for A8-3 compute_terminal_conditons(&r, &e) fmt.Printf("%# v\n", pretty.Formatter(r)) fmt.Printf("%# v\n", pretty.Formatter(e)) fmt.Printf("You're going to reach %v maximum velocity\n", r.max_velocity) fmt.Println("Your maximum altitude will be:", r.max_altitude) }
func TestCopy_ListFiles_Dir_Simple(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "dir/foo.txt": "hello", "dir/bar.txt": "hello", }) defer os.RemoveAll(tmpDir) includes := []string{ "dir", } excludes := []string{} matches, err := listFiles(tmpDir, includes, excludes, "COPY", nil) if err != nil { t.Fatal(err) } t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("matches: %# v", pretty.Formatter(matches)) assertions := [][2]string{ {tmpDir + "/dir/bar.txt", "dir/bar.txt"}, {tmpDir + "/dir/foo.txt", "dir/foo.txt"}, } assert.Len(t, matches, len(assertions)) for i, a := range assertions { assert.Equal(t, a[0], matches[i].src, "bad match src at index %d", i) assert.Equal(t, a[1], matches[i].dest, "bad match dest at index %d", i) } }
func TestCopy_MakeTarStream_SingleFileDirRename(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "c/foo.txt": "hello", }) defer os.RemoveAll(tmpDir) // ADD ./c /src --> /src // ADD ./a/b[/1,2] /src -> /src[/1,2] includes := []string{ "./c", } excludes := []string{} dest := "/src" t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("dest: %# v", pretty.Formatter(dest)) stream, err := makeTarStream(tmpDir, dest, "COPY", includes, excludes, nil) if err != nil { t.Fatal(err) } out := writeReadTar(t, tmpDir, stream.tar) assertion := strings.Join([]string{ "src/foo.txt", }, "\n") + "\n" assert.Equal(t, assertion, out, "bad tar content") }
func TestSNSMessageNotFound(t *testing.T) { server := server.MockDBServer() defer server.Close() snsString := fmt.Sprintf(`{ "Type" : "Notification", "MessageId" : "12", "TopicArn" : "arn", "Subject" : "Amazon S3 Notification", "Message" : "{\"Records\":[{\"s3\":{\"bucket\":{\"name\":\"sc-gallery\"},\"object\":{\"key\":\"%v\",\"size\":71501}}}]}", "Timestamp" : "2015-04-14T03:48:23.584Z", "SignatureVersion" : "1", "Signature" : "liP1M" }`, "original_file/134444") req := tests.MockRequest{} req.Url = "/notify/sns/" req.Method = "post" req.Data = map[string]interface{}{} utils.Decoder([]byte(snsString), &req.Data) server.Test(&req, func(msg *tests.MockResponse) { exception := "This message should be ignored." if msg.Status != 200 { fmt.Printf("%# v", pretty.Formatter(msg)) t.Error(exception) } if msg.Message != "" { fmt.Printf("%# v", pretty.Formatter(msg)) t.Error(exception) } }) }
func TestCreatePDFCollection(t *testing.T) { server := server.MockDBServer() defer server.Close() req := tests.MockRequest{} req.Url = "/assets" req.Method = "post" req.Data = map[string]interface{}{ "mime_type": "application/pdf", "name": randSeq(10), "collection": randSeq(5), } server.Test(&req, func(msg *tests.MockResponse) { utils.Convert(&msg.Data, &assetRet) if msg.Status != 200 { fmt.Printf("%# v", pretty.Formatter(msg)) t.Error("Asset creation should return status 200.") } for _, key := range []string{"upload_url", "url", "_id"} { if val, ok := assetRet[key]; !ok || len(val) == 0 { fmt.Printf("%# v", pretty.Formatter(msg)) t.Error(key + " should be a valid string in creation return.") } } }) }
func TestCopy_MakeTarStream_SubDirRenameWildcard(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "a/c/foo.txt": "hello", "a/c/x/1.txt": "hello", "a/c/x/2.txt": "hello", }) defer os.RemoveAll(tmpDir) includes := []string{ "a/*", } excludes := []string{} dest := "/src" t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("dest: %# v", pretty.Formatter(dest)) stream, err := makeTarStream(tmpDir, dest, "COPY", includes, excludes) if err != nil { t.Fatal(err) } out := writeReadTar(t, tmpDir, stream.tar) assertion := strings.Join([]string{ "src/c/foo.txt", "src/c/x/1.txt", "src/c/x/2.txt", }, "\n") + "\n" assert.Equal(t, assertion, out, "bad tar content") }
func TestSNSMessageIgnoredPath(t *testing.T) { server := server.MockDBServer() defer server.Close() snsString := fmt.Sprintf(`{ "Type" : "Notification", "MessageId" : "12", "TopicArn" : "arn", "Subject" : "Amazon S3 Notification", "Message" : "{\"Records\":[{\"s3\":{\"bucket\":{\"name\":\"sc-gallery\"},\"object\":{\"key\":\"%v\",\"size\":71501}}}]}", "Timestamp" : "2015-04-14T03:48:23.584Z", "SignatureVersion" : "1", "Signature" : "liP1M" }`, "/hello/world/") req := tests.MockRequest{} req.Url = "/notify/sns/" req.Method = "post" req.Data = map[string]interface{}{} utils.Decoder([]byte(snsString), &req.Data) server.Test(&req, func(msg *tests.MockResponse) { exception := "This path should have been ignroed." if msg.Status != 400 { fmt.Printf("%# v", pretty.Formatter(msg)) t.Error(exception) } if !strings.Contains(msg.Message, "not meant to be monitored") { fmt.Printf("%# v", pretty.Formatter(msg)) t.Error(exception) } }) }
func TestCopy_ListFiles_Excludes_FileInAnyDir(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "a/test1.txt": "hello", "b/test2.txt": "hello", "c/d/e/test2.txt": "hello", }) defer os.RemoveAll(tmpDir) includes := []string{ ".", } excludes := []string{ "**/test2.txt", } matches, err := listFiles(tmpDir, includes, excludes) if err != nil { t.Fatal(err) } t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("matches: %# v", pretty.Formatter(matches)) assertions := [][2]string{ {tmpDir + "/a/test1.txt", "a/test1.txt"}, } assert.Len(t, matches, len(assertions)) for i, a := range assertions { assert.Equal(t, a[0], matches[i].src, "bad match src at index %d", i) assert.Equal(t, a[1], matches[i].dest, "bad match dest at index %d", i) } }
// ExampleProxy shows a chain of servers and clients. func ExampleProxy() { log.Println("\n***** ExampleProxy *****\n") // Real var realServer = offers.MustNewServer(configure("Real Server"), offers.Offers{Configuration: configure("Server")}, ":4030") // Use s as the service. go func() { if err := realServer.Start(); err != nil { panic(err) } }() var realClient = offers.MustNewClient(configure("Real Client"), ":4030") // Proxy var proxyServer = offers.MustNewServer(configure("Proxy Server"), realClient, ":4031") // Use realClient as the service. go func() { if err := proxyServer.Start(); err != nil { panic(err) } }() var proxyClient = offers.MustNewClient(configure("Proxy Client"), ":4031").ForContext(offers.Context{ID: tigertonic.RandomBase62String(8)}).(offers.Client) // Use m, err := proxyClient.New(offer.Offer{Name: "nerddomo"}) if err != nil { panic(err) } log.Printf("New: Got: %# v\n\n", pretty.Formatter(simplify(m))) m, err = proxyClient.Get(m.ID) if err != nil { panic(err) } log.Printf("Get: Got: %# v\n\n", pretty.Formatter(simplify(m))) m.Name = "test" m, err = proxyClient.Set(m) if err != nil { panic(err) } log.Printf("Set: Got: %# v\n\n", pretty.Formatter(simplify(m))) m, err = proxyClient.Delete(m) if err != nil { panic(err) } log.Printf("Delete: Got: %# v\n\n", pretty.Formatter(simplify(m))) // Proxy if err := proxyClient.Close(); err != nil { panic(err) } if err := proxyServer.Stop(); err != nil { panic(err) } // Real if err := realClient.Close(); err != nil { panic(err) } if err := realServer.Stop(); err != nil { panic(err) } }
func TestGetRateSummary(t *testing.T) { server, zillow := testFixtures(t, rateSummaryPath, func(values url.Values) { assertOnlyParam(t, values, stateParam, state) }) defer server.Close() request := RateSummaryRequest{State: state} result, err := zillow.GetRateSummary(request) if err != nil { t.Fatal(err) } expected := &RateSummary{ XMLName: xml.Name{Space: "http://www.zillow.com/static/xsd/RateSummary.xsd", Local: "rateSummary"}, Message: Message{ Text: "Request successfully processed", Code: 0, }, Today: []Rate{ Rate{LoanType: "thirtyYearFixed", Count: 1252, Value: 5.91}, Rate{LoanType: "fifteenYearFixed", Count: 839, Value: 5.68}, Rate{LoanType: "fiveOneARM", Count: 685, Value: 5.49}, }, LastWeek: []Rate{ Rate{LoanType: "thirtyYearFixed", Count: 8933, Value: 6.02}, Rate{LoanType: "fifteenYearFixed", Count: 5801, Value: 5.94}, Rate{LoanType: "fiveOneARM", Count: 3148, Value: 5.71}, }, } if !reflect.DeepEqual(result, expected) { t.Fatalf("expected:\n %#v\n\n but got:\n %#v\n\n diff:\n %s\n", pretty.Formatter(expected), pretty.Formatter(result), pretty.Diff(expected, result)) } }
func TestCopy_MakeTarStream_WierdWildcards(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "abc.txt": "hello", "adf.txt": "hello", "bvz.txt": "hello", }) defer os.RemoveAll(tmpDir) includes := []string{ "a*.txt", } excludes := []string{} dest := "./" t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("dest: %# v", pretty.Formatter(dest)) stream, err := makeTarStream(tmpDir, dest, "COPY", includes, excludes, nil) if err != nil { t.Fatal(err) } out := writeReadTar(t, tmpDir, stream.tar) assertion := strings.Join([]string{ "./abc.txt", "./adf.txt", }, "\n") + "\n" assert.Equal(t, assertion, out, "bad tar content") }
func main() { var ( mongoSession *mgo.Session database *mgo.Database collection *mgo.Collection changeInfo *mgo.ChangeInfo err error ) if mongoSession, err = mgo.Dial("localhost"); err != nil { panic(err) } database = mongoSession.DB("mgo_examples_03") collection = database.C("todos") // START OMIT var todo = Todo{ Id: bson.NewObjectId(), Task: "Demo mgo", Created: time.Now(), } // This is a shortcut to collection.Upsert(bson.M{"_id": todo.id}, &todo) if changeInfo, err = collection.UpsertId(todo.Id, &todo); err != nil { panic(err) } // END OMIT fmt.Printf("Todo: %# v", pretty.Formatter(todo)) fmt.Printf("Change Info: %# v", pretty.Formatter(changeInfo)) }
func TestConnGrant(t *testing.T) { for _, tst := range grantTests { ok := tst.c.grant(tst.sk) assert.Equalf(t, tst.ok, ok, "%# v", pretty.Formatter(tst)) assert.Equalf(t, tst.r, tst.c.raccess, "%# v", pretty.Formatter(tst)) assert.Equalf(t, tst.w, tst.c.waccess, "%# v", pretty.Formatter(tst)) } }
func TestCopy_MakeTarStream_DirRenameDestLeadingSlash(t *testing.T) { tmpDir := makeTmpDir(t, map[string]string{ "lib/foo.txt": "hello", "lib/x/1.txt": "hello", "lib/x/2.txt": "hello", }) defer os.RemoveAll(tmpDir) // WORKDIR /app // COPY lib lib // COPY lib lib/ // COPY lib/ lib // COPY lib/ lib/ // /app // /app/lib // /app/lib/foo.txt // /app/lib/x/1.txt // /app/lib/x/2.txt assertions := [][2]string{ {"lib", "lib"}, {"lib", "lib/"}, {"lib/", "lib"}, {"lib/", "lib/"}, } for _, a := range assertions { includes := []string{a[0]} excludes := []string{} dest := a[1] t.Logf("includes: %# v", pretty.Formatter(includes)) t.Logf("excludes: %# v", pretty.Formatter(excludes)) t.Logf("dest: %# v", pretty.Formatter(dest)) stream, err := makeTarStream(tmpDir, dest, "COPY", includes, excludes, nil) if err != nil { t.Fatal(err) } out := writeReadTar(t, tmpDir, stream.tar) assertion := strings.Join([]string{ "lib/foo.txt", "lib/x/1.txt", "lib/x/2.txt", }, "\n") + "\n" assert.Equal(t, assertion, out, "bad tar content for COPY %s %s", a[0], a[1]) } }
func TestGetMonthlyPayments(t *testing.T) { server, zillow := testFixtures(t, monthlyPaymentsPath, func(values url.Values) { assertOnlyParam(t, values, priceParam, strconv.Itoa(price)) assertOnlyParam(t, values, downParam, strconv.Itoa(down)) assertOnlyParam(t, values, zipParam, zip) }) defer server.Close() request := MonthlyPaymentsRequest{Price: price, Down: down, Zip: zip} result, err := zillow.GetMonthlyPayments(request) if err != nil { t.Fatal(err) } expected := &MonthlyPayments{ XMLName: xml.Name{Space: "http://www.zillow.com/static/xsd/MonthlyPayments.xsd", Local: "paymentsSummary"}, Request: request, Message: Message{ Text: "Request successfully processed", Code: 0, }, Payments: []Payment{ { LoanType: "thirtyYearFixed", Rate: 5.9, MonthlyPrincipalAndInterest: 1512, MonthlyMortgageInsurance: 68, }, { LoanType: "fifteenYearFixed", Rate: 5.68, MonthlyPrincipalAndInterest: 1477, MonthlyMortgageInsurance: 68, }, { LoanType: "fiveOneARM", Rate: 5.71, MonthlyPrincipalAndInterest: 1482, MonthlyMortgageInsurance: 74, }, }, DownPayment: 45000, MonthlyPropertyTaxes: 193, MonthlyHazardInsurance: 49, } if !reflect.DeepEqual(result, expected) { t.Fatalf("expected:\n %#v\n\n but got:\n %#v\n\n diff:\n %s\n", pretty.Formatter(expected), pretty.Formatter(result), pretty.Diff(expected, result)) } }
// Run runs the build following the given Plan func (b *Build) Run(plan Plan) (err error) { for k := 0; k < len(plan); k++ { c := plan[k] log.Debugf("Step %d: %# v", k+1, pretty.Formatter(c)) var doRun bool if doRun, err = c.ShouldRun(b); err != nil { return err } if !doRun { continue } // Replace env for the command if appropriate if c, ok := c.(EnvReplacableCommand); ok { c.ReplaceEnv(b.state.Config.Env) } log.Infof("%s", color.New(color.FgWhite, color.Bold).SprintFunc()(c)) if b.state, err = c.Execute(b); err != nil { return err } log.Debugf("State after step %d: %# v", k+1, pretty.Formatter(b.state)) // Here we need to inject ONBUILD commands on the fly, // build sub plan and merge it with the main plan. // Not very beautiful, because Run uses Plan as the argument // and then it builds its own. But. if len(b.state.InjectCommands) > 0 { commands, err := parseOnbuildCommands(b.state.InjectCommands) if err != nil { return err } subPlan, err := NewPlan(commands, false) if err != nil { return err } tail := append(subPlan, plan[k+1:]...) plan = append(plan[:k+1], tail...) b.state.InjectCommands = []string{} } } return nil }
// ExampleMethod shows using a method. func ExampleMethod() { log.Println("\n***** ExampleMethod *****\n") // Server var server = offers.MustNewServer(configure("Server"), offers.Offers{Configuration: configure("Server")}, ":4020") go func() { if err := server.Start(); err != nil { panic(err) } }() // Client var client = offers.MustNewClient(configure("Client"), ":4020").ForContext(offers.Context{ID: tigertonic.RandomBase62String(8)}).(offers.Client) // Use var m = offer.Offer{Interface: client, Name: "nerddomo"} m, err := m.New() if err != nil { panic(err) } log.Printf("New: Got: %# v\n\n", pretty.Formatter(simplify(m))) m, err = client.Get(m.ID) if err != nil { panic(err) } log.Printf("Get: Got: %# v\n\n", pretty.Formatter(simplify(m))) m.Name = "bar" m, err = m.Set() if err != nil { panic(err) } log.Printf("Set: Got: %# v\n\n", pretty.Formatter(simplify(m))) m, err = m.Delete() if err != nil { panic(err) } log.Printf("Delete: Got: %# v\n\n", pretty.Formatter(simplify(m))) // Client if err := client.Close(); err != nil { panic(err) } // Server if err := server.Stop(); err != nil { panic(err) } }
func TestNilAnnotator_multiLineTokens(t *testing.T) { for _, tt := range []struct { src string want [][]string }{ { src: "/* I am\na multiline\ncomment\n*/", want: [][]string{ []string{"/* I am"}, []string{"a multiline"}, []string{"comment"}, []string{"*/"}, }, }, { src: "a := `I am\na multiline\nstring literal\n`", want: [][]string{ []string{"a", " ", ":", "=", " ", "`I am"}, []string{"a multiline"}, []string{"string literal"}, []string{"`"}, }, }, } { e := newFileWithRange([]byte(tt.src)) ann := NewNilAnnotator(e) _, err := Annotate(e.Contents, ann) if err != nil { t.Fatal(err) } if !codeEquals(ann.Code, tt.want) { t.Errorf("Expected %# v\n\nGot %# v", tt.want, pretty.Formatter(ann.Code.Lines)) } } }
func TestNSResolution(t *testing.T) { root, err := Parse(doc) if err != nil { t.Fatal(err) } for _, el := range root.Search("http://schemas.xmlsoap.org/wsdl/", "definitions") { for _, prefix := range []string{"soap", "wsdl", "s", "soap12"} { if name, ok := el.ResolveNS(prefix + ":foo"); !ok { t.Errorf("Failed to resolve %s: prefix at <%s>", prefix, el.Name.Local) } else { t.Logf("Resoved prefix %s to %q at <%s name=%q>", prefix, name.Space, el.Name.Local, el.Attr("", "name")) } } } defaultns := root.SearchFunc(func(el *Element) bool { if (el.Name != xml.Name{"http://schemas.xmlsoap.org/wsdl/", "binding"}) { return false } return el.Attr("", "name") == "wseDocReciboSoap12" })[0] name := defaultns.Resolve("foo") if name.Space != "http://custom/" { t.Errorf("Resolve default namespace at <%s name=%q>: wanted %q, got %q", defaultns.Prefix(defaultns.Name), defaultns.Attr("", "name"), defaultns.Attr("", "xmlns"), name.Space) t.Logf("NS stack is %# v", pretty.Formatter(defaultns.Scope)) } }
// ValidateAndHandleJsonInput is the main entry point into this package for the // API server (i.e. given a POST'ed JSON body). It loads JSON into struct and // essentially just calls the Simulate() method. // Receiver: None // Params: j io.ReadCloser (via r.Body) // Returns: ApiResponse {Response/StatusCode} func ValidateAndHandleJsonInput(j io.ReadCloser) ApiResponse { decoder := json.NewDecoder(j) var simulationData SimulationData err := decoder.Decode(&simulationData) if err != nil { return ApiResponse{ Response: map[string]interface{}{ "success": false, "message": "Invalid JSON structure.", }, StatusCode: http.StatusBadRequest, } } log.Printf("%# v", pretty.Formatter(simulationData)) resp := Simulate(&simulationData) return ApiResponse{ Response: map[string]interface{}{ "success": true, "timesteps": resp, }, StatusCode: http.StatusOK, } }
func (c *Conn) sendLoop() { defer c.wg.Done() sendc := c.Send for { select { case msg := <-sendc: log.Printf("ws-conn-%04d: send-> %# v", c.ID, pretty.Formatter(msg)) err := websocket.JSON.Send(c.WSConn, msg) if err != nil { if !isUseOfClosed(err) { log.Printf("ws-conn-%04d: send error: %v", c.ID, err) c.errors.Push(errors.Wrap(err, "send error")) } c.Close() sendc = nil // stop sending messages after an error } case <-c.shutdown: err := c.WSConn.Close() if err != nil && !isUseOfClosed(err) { log.Printf("ws-conn-%04d: close error: %v", c.ID, err) c.errors.Push(errors.Wrap(err, "close error")) } log.Printf("ws-conn-%04d: closed", c.ID) return case <-c.Done: c.Close() } } }
func TestComplexSchema(t *testing.T) { ty := &types{ schemas: []*XSDSchema{}, } data := []byte(complex) err := xml.Unmarshal(data, &ty.schemas) if err != nil { t.Error(err) } err = xml.Unmarshal(data, &ty.schemaMetas) if err != nil { t.Error(err) } if ty.schemaMetas[0].xsdPrefix() != "" { t.Error("should have got xsd prefix \"\" got", ty.schemaMetas[0].xsdPrefix()) } if ty.schemaMetas[0].tnsPrefix() != "tns" { t.Error("should have got prefix \"tns\" got", ty.schemaMetas[0].tnsPrefix()) } // ty.genTypes() t.Log(fmt.Printf("%# v\n\n", pretty.Formatter(ty))) }
func makeTempDir(t *testing.T, prefix string, files map[string]string) string { // We produce tmp dirs within home to make integration tests work within // Mac OS and VirtualBox home, err := homedir.Dir() if err != nil { log.Fatal(err) } baseTmpDir := path.Join(home, ".rocker-integ-tmp") if err := os.MkdirAll(baseTmpDir, 0755); err != nil { log.Fatal(err) } tmpDir, err := ioutil.TempDir(baseTmpDir, prefix) if err != nil { t.Fatal(err) } if err := test.MakeFiles(tmpDir, files); err != nil { os.RemoveAll(tmpDir) t.Fatal(err) } if *verbosityLevel >= 2 { fmt.Printf("temp directory: %s\n", tmpDir) fmt.Printf(" with files: %# v\n", pretty.Formatter(files)) } return tmpDir }
func TestCommandCopy_Simple(t *testing.T) { // TODO: do we need to check the dest is always a directory? b, c := makeBuild(t, "", Config{}) cmd := NewCommand(ConfigCommand{ name: "copy", args: []string{"testdata/Rockerfile", "/Rockerfile"}, }) c.On("CreateContainer", mock.AnythingOfType("State")).Return("456", nil).Run(func(args mock.Arguments) { arg := args.Get(0).(State) // TODO: a better check assert.True(t, len(arg.Config.Cmd) > 0) }).Once() c.On("UploadToContainer", "456", mock.AnythingOfType("*io.PipeReader"), "/").Return(nil).Once() state, err := cmd.Execute(b) if err != nil { t.Fatal(err) } t.Logf("state: %# v", pretty.Formatter(state)) c.AssertExpectations(t) assert.Equal(t, "456", state.NoCache.ContainerID) }
// RunContainer implements creating and optionally running a container // depending on its state preference. func (client *DockerClient) RunContainer(container *Container) error { log.Infof("Create container %s", container.Name) opts, err := container.CreateContainerOptions() if err != nil { return fmt.Errorf("Failed to initialize container options, error: %s", err) } log.Debugf("Creating container with opts: %# v", pretty.Formatter(opts)) apiContainer, err := client.Docker.CreateContainer(*opts) if err != nil { return fmt.Errorf("Failed to create container, error: %s", err) } container.ID = apiContainer.ID if container.State.Running || container.Config.State.IsRan() { if client.Attach { if err := client.AttachToContainer(container); err != nil { return err } } if err := client.StartContainer(container); err != nil { return err } } return nil }
// CreateContainer creates docker container func (c *DockerClient) CreateContainer(s State) (string, error) { s.Config.Image = s.ImageID // TODO: assign human readable name? opts := docker.CreateContainerOptions{ Config: &s.Config, HostConfig: &s.NoCache.HostConfig, } c.log.Debugf("Create container: %# v", pretty.Formatter(opts)) container, err := c.client.CreateContainer(opts) if err != nil { return "", err } imageStr := fmt.Sprintf("(image %.12s)", s.ImageID) if s.ImageID == "" { imageStr = "(from scratch)" } c.log.Infof("| Created container %.12s %s", container.ID, imageStr) return container.ID, nil }
func main() { var todo = Todo{ Task: "Demo mgo", Created: time.Now(), } fmt.Printf("Todo: %# v", pretty.Formatter(todo)) }