func TestValidateResponse(t *testing.T) { valid := &http.Response{ Request: &http.Request{}, StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader("OK")), } if err := validateResponse(valid); err != nil { t.Errorf("ValidateResponse with valid response returned error %+v", err) } invalid := &http.Response{ Request: &http.Request{}, StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(strings.NewReader(`{ "error" : { "statuscode": 400, "statusdesc": "Bad Request", "errormessage": "This is an error" } }`)), } want := &PingdomError{400, "Bad Request", "This is an error"} if err := validateResponse(invalid); !reflect.DeepEqual(err, want) { t.Errorf("ValidateResponse with invalid response returned %+v, want %+v", err, want) } }
func TestLambda(t *testing.T) { env := environment.New(nil) environment.Define(env, &types.Symbol{"+"}, &types.Builtin{add}) environment.Define(env, &types.Symbol{"begin"}, &types.Builtin{begin}) f, _ := parser.Parse(strings.NewReader("(lambda (n) n)")) if a, err := Eval(env, f); err != nil { t.Error("Evaluating lambda failed:", err, f) } else if !types.IsSFunction(a) { t.Error("Evaluating lambda didn't return an SFunction:", a) } f, _ = parser.Parse(strings.NewReader("(define add1 (lambda (n) (+ 1 n)))")) if _, err := Eval(env, f); err != nil { t.Error("Evaluating define lambda failed:", err) } if a, err := environment.Get(env, &types.Symbol{"add1"}); err != nil { t.Error("'Get'ting add1 caused an error: ", err) } else if !types.IsSFunction(a) { t.Error("add1 is not an SFunction:", a) } f, _ = parser.Parse(strings.NewReader("(add1 1)")) if a, err := Eval(env, f); err != nil { t.Error("Evaluating (add1 1) failed:", err) } else if !types.Eqv(a, &types.Number{2}) { t.Error("(add1 1) != 2", a) } }
func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) { var req *http.Request var err error switch c.authMethod { case AuthMethodClientSecretPost: values.Set("client_secret", c.creds.Secret) req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) if err != nil { return nil, err } case AuthMethodClientSecretBasic: req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode())) if err != nil { return nil, err } encodedID := url.QueryEscape(c.creds.ID) encodedSecret := url.QueryEscape(c.creds.Secret) req.SetBasicAuth(encodedID, encodedSecret) default: panic("misconfigured client: auth method not supported") } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") return req, nil }
func TestNewRequestContentLength(t *testing.T) { readByte := func(r io.Reader) io.Reader { var b [1]byte r.Read(b[:]) return r } tests := []struct { r io.Reader want int64 }{ {bytes.NewReader([]byte("123")), 3}, {bytes.NewBuffer([]byte("1234")), 4}, {strings.NewReader("12345"), 5}, // Not detected: {struct{ io.Reader }{strings.NewReader("xyz")}, 0}, {io.NewSectionReader(strings.NewReader("x"), 0, 6), 0}, {readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), 0}, } for _, tt := range tests { req, err := NewRequest("POST", "http://localhost/", tt.r) if err != nil { t.Fatal(err) } if req.ContentLength != tt.want { t.Errorf("ContentLength(%T) = %d; want %d", tt.r, req.ContentLength, tt.want) } } }
func TestReadTriggerParams(t *testing.T) { t.Parallel() h := newHarness(t) defer h.Stop() h.env.In = ioutil.NopCloser(strings.NewReader("\n")) _, err := readTriggerName(h.env) ensure.Err(t, err, regexp.MustCompile("Class name cannot be empty")) h.env.In = ioutil.NopCloser(strings.NewReader("foo\n")) _, err = readTriggerName(h.env) ensure.Err(t, err, regexp.MustCompile("Trigger name cannot be empty")) h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave")) hook, err := readTriggerName(h.env) ensure.Nil(t, err) ensure.DeepEqual(t, *hook, triggerHook{ClassName: "foo", TriggerName: "beforeSave"}) h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/foo/beforeSave\n")) hook, err = readTriggerParams(h.env) ensure.Nil(t, err) ensure.DeepEqual(t, *hook, triggerHook{ ClassName: "foo", TriggerName: "beforeSave", URL: "https://api.example.com/foo/beforeSave", }) }
func main() { br := bufio.NewReader(os.Stdin) line, _ := br.ReadString('\n') taxa := strings.Fields(line) taxaInv := map[string]int{} for i, taxon := range taxa { taxaInv[taxon] = i } line, _ = br.ReadString('\n') t1, _ := tree.ReadNewick(strings.NewReader(line)) line, _ = br.ReadString('\n') t2, _ := tree.ReadNewick(strings.NewReader(line)) splits1 := phylo.Splits(t1, taxaInv) splits2 := phylo.Splits(t2, taxaInv) normalize(splits1) normalize(splits2) m1 := map[string]bool{} for _, a := range splits1 { m1[string(a)] = true } shared := 0 for _, a := range splits2 { if m1[string(a)] { shared++ } } d := 2 * (len(taxa) - 3 - shared) fmt.Println(d) }
func NewTokenHarness(t testing.TB) *Harness { h := NewHarness(t) ht := TransportFunc(func(r *http.Request) (*http.Response, error) { ensure.DeepEqual(t, r.URL.Path, "/1/accountkey") ensure.DeepEqual(t, r.Method, "POST") key := &struct { AccountKey string `json:"accountKey"` }{} ensure.Nil(t, json.NewDecoder(ioutil.NopCloser(r.Body)).Decode(key)) if key.AccountKey != "token" { return &http.Response{ StatusCode: http.StatusUnauthorized, Body: ioutil.NopCloser(strings.NewReader(`{"error": "incorrect token"}`)), }, nil } return &http.Response{ StatusCode: http.StatusOK, Body: ioutil.NopCloser(strings.NewReader(`{"email": "email"}`)), }, nil }) h.Env.ParseAPIClient = &ParseAPIClient{APIClient: &parse.Client{Transport: ht}} return h }
func TestOVirtCloudConfiguration(t *testing.T) { config1 := (io.Reader)(nil) _, err1 := cloudprovider.GetCloudProvider("ovirt", config1) if err1 == nil { t.Fatalf("An error is expected when the configuration is missing") } config2 := strings.NewReader("") _, err2 := cloudprovider.GetCloudProvider("ovirt", config2) if err2 == nil { t.Fatalf("An error is expected when the configuration is empty") } config3 := strings.NewReader(` [connection] `) _, err3 := cloudprovider.GetCloudProvider("ovirt", config3) if err3 == nil { t.Fatalf("An error is expected when the uri is missing") } config4 := strings.NewReader(` [connection] uri = https://localhost:8443/ovirt-engine/api `) _, err4 := cloudprovider.GetCloudProvider("ovirt", config4) if err4 != nil { t.Fatalf("Unexpected error creating the provider: %s", err4) } }
func TestCopyNEOF(t *testing.T) { // Test that EOF behavior is the same regardless of whether // argument to CopyN has ReadFrom. b := new(bytes.Buffer) n, err := CopyN(&noReadFrom{b}, strings.NewReader("foo"), 3) if n != 3 || err != nil { t.Errorf("CopyN(noReadFrom, foo, 3) = %d, %v; want 3, nil", n, err) } n, err = CopyN(&noReadFrom{b}, strings.NewReader("foo"), 4) if n != 3 || err != EOF { t.Errorf("CopyN(noReadFrom, foo, 4) = %d, %v; want 3, EOF", n, err) } n, err = CopyN(b, strings.NewReader("foo"), 3) // b has read from if n != 3 || err != nil { t.Errorf("CopyN(bytes.Buffer, foo, 3) = %d, %v; want 3, nil", n, err) } n, err = CopyN(b, strings.NewReader("foo"), 4) // b has read from if n != 3 || err != EOF { t.Errorf("CopyN(bytes.Buffer, foo, 4) = %d, %v; want 3, EOF", n, err) } }
func (ps BoltPostStore) GetPosts(channelID string) StoreChannel { storeChannel := make(StoreChannel) go func() { var result StoreResult posts := make(map[string]*model.Post) channelPostsJson, err := ps.postsByChannel.Get([]byte(channelID)) if err != nil { result.Err = model.NewAppError("BoltPostStore.", "Post is not valid", "") } else { channelPosts := model.BoolMapFromJson(strings.NewReader(string(channelPostsJson))) postItems, err := ps.postStore.Items() if err != nil { result.Err = model.NewAppError("BoltPostStore.", "Post is not valid", "") storeChannel <- result close(storeChannel) return } for _, postItem := range postItems { if channelPosts[string(postItem.Key)] { postString := string(postItem.Value) posts[string(postItem.Key)] = model.PostFromJson(strings.NewReader(postString)) } } result.Data = posts } storeChannel <- result close(storeChannel) return }() return storeChannel }
func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) { br := bufio.NewReader(strings.NewReader("")) sr := &simpleReaderCloser{ Reader: strings.NewReader("foobar"), closed: false, } reader := BufioReader32KPool.NewReadCloserWrapper(br, sr) if reader == nil { t.Fatalf("NewReadCloserWrapper should not return a nil reader.") } // Verify the content of reader buf := make([]byte, 3) _, err := reader.Read(buf) if err != nil { t.Fatal(err) } if actual := string(buf); actual != "foo" { t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual) } reader.Close() // Read 3 more bytes "bar" _, err = reader.Read(buf) if err != nil { t.Fatal(err) } if actual := string(buf); actual != "bar" { t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual) } if !sr.closed { t.Fatalf("The ReaderCloser should have been closed, it is not.") } }
func TestUpload(t *testing.T) { fs := NewFileStore("./") id := "yyy" info := &FileInfo{} info.ID = id info.Offset = 0 info.Size = 10 info.Type = ".jpg" if offset, isCompleted, _ := fs.NewUpload(info); offset != 0 || isCompleted { t.Fatal() } if n, isCompleted, _ := fs.WriteChunk(id, 0, strings.NewReader("hello")); n != 5 || isCompleted { t.Fatal() } if offset, isCompleted, _ := fs.NewUpload(info); offset != 5 || isCompleted { t.Fatal() } if n, isCompleted, _ := fs.WriteChunk(id, 5, strings.NewReader("world")); n != 5 || !isCompleted { t.Fatal() } if n, isCompleted, _ := fs.WriteChunk(id, 5, strings.NewReader("abc")); n != 0 || !isCompleted { t.Fatal() } os.Remove(id + ".bin") os.Remove(id + ".info") }
func (test *ServerTest) TestShortcut(c *C) { w := httptest.NewRecorder() r, _ := http.NewRequest("PUT", "https://idp.example.com/shortcuts/bob", strings.NewReader("{\"url_suffix_as_relay_state\": true, \"service_provider\": \"https://sp.example.com/saml2/metadata\"}")) test.Server.ServeHTTP(w, r) c.Assert(w.Code, Equals, http.StatusNoContent) w = httptest.NewRecorder() r, _ = http.NewRequest("PUT", "https://idp.example.com/users/alice", strings.NewReader(`{"name": "alice", "password": "******"}`+"\n")) test.Server.ServeHTTP(w, r) c.Assert(w.Code, Equals, http.StatusNoContent) w = httptest.NewRecorder() r, _ = http.NewRequest("POST", "https://idp.example.com/login", strings.NewReader("user=alice&password=hunter2")) r.Header.Set("Content-type", "application/x-www-form-urlencoded") test.Server.ServeHTTP(w, r) c.Assert(w.Code, Equals, http.StatusOK) w = httptest.NewRecorder() r, _ = http.NewRequest("GET", "https://idp.example.com/login/bob/whoami", nil) r.Header.Set("Cookie", "session=AAIEBggKDA4QEhQWGBocHiAiJCYoKiwuMDI0Njg6PD4=") test.Server.ServeHTTP(w, r) c.Assert(w.Code, Equals, http.StatusOK) body := string(w.Body.Bytes()) c.Assert(strings.Contains(body, "<input type=\"hidden\" name=\"RelayState\" value=\"/whoami\" />"), Equals, true) c.Assert(strings.Contains(body, "<script>document.getElementById('SAMLResponseForm').submit();</script>"), Equals, true) }
func TestConfigureAcessToken(t *testing.T) { t.Parallel() h, _ := newAppHarness(t) defer h.Stop() c := configureCmd{login: login{tokenReader: strings.NewReader("")}} h.env.In = ioutil.NopCloser(strings.NewReader("n\ntoken\n")) ensure.Nil(t, c.accessToken(h.env)) ensure.DeepEqual(t, h.Out.String(), `Please enter an access token if you already generated it. If you do not have an access token or would like to generate a new one, please type: "y" to open the browser or "n" to continue: Access Token: Successfully stored credentials. `, ) h.env.In = ioutil.NopCloser(strings.NewReader("n\nemail\ninvalid\n")) ensure.Err(t, c.accessToken(h.env), regexp.MustCompile("Please try again")) ensure.DeepEqual(t, h.Err.String(), `Sorry, the access token you provided is not valid. Please follow instructions at https://www.parse.com/account_keys to generate a new access token. `, ) }
func TestPostBadData(t *testing.T) { handler := NewHandler("") req, _ := http.NewRequest("POST", "/", strings.NewReader("[]")) w := httptest.NewRecorder() handler.ServeHTTP(w, req) if http.StatusInternalServerError != w.Code { t.Errorf( "Expected internal server error on non-\"dict\" post, got response\n%s", w.Body.String(), ) } req, _ = http.NewRequest("POST", "/", strings.NewReader("500")) w = httptest.NewRecorder() handler.ServeHTTP(w, req) if http.StatusInternalServerError != w.Code { t.Errorf( "Expected internal server error on non-\"dict\" post, got response\n%s", w.Body.String(), ) } req, _ = http.NewRequest("POST", "/", strings.NewReader(`{"from":"reader"}`)) w = httptest.NewRecorder() handler.ServeHTTP(w, req) if http.StatusCreated != w.Code { t.Errorf("Expected %d on valid \"dict\" data, got %d", http.StatusCreated, w.Code) } }
func TestCheckExcuse(t *testing.T) { if testing.Verbose() { log.SetLogThreshold(log.LevelInfo) log.SetStdoutThreshold(log.LevelInfo) } createEmptyGitRepo(t) runCheckP(t, "foobar", true, "foo,5") // Increase on "barfoo" prefix is okay runCheckP(t, "barfoo", true, "foo,6") t.Logf("Running check command p: %s w: %t i: %s", "foobar", false, "foo,6") errCode := Check("foobar", 0, false, "csv", false, strings.NewReader("foo,6")) if errCode != 50 { t.Fatalf("Check command passed unexpectedly!") } writeExcuse(t, "foobar", "foo", "PROD's down right now, I'll clean foo up later") runCheckP(t, "foobar", true, "foo,6") t.Logf("Running check command p: %s w: %t i: %s", "barfoo", false, "foo,7") errCode = Check("barfoo", 0, false, "csv", false, strings.NewReader("foo,7")) if errCode != 50 { t.Fatalf("Check command passed unexpectedly!") } }
func TestZeroMissing(t *testing.T) { if testing.Verbose() { log.SetLogThreshold(log.LevelInfo) log.SetStdoutThreshold(log.LevelInfo) } createEmptyGitRepo(t) runCheck(t, true, "foo,5") t.Logf("Running check command w: %t i: %s", false, "") errCode := Check("", 0, true, "csv", false, strings.NewReader("")) if errCode != 50 { t.Fatalf("Check command passed unexpectedly!") } t.Logf("Running check command zero on missing w: %t i: %s", false, "") errCode = Check("", 0, true, "csv", false, strings.NewReader("")) if errCode != 0 { t.Fatalf("Check command failed unexpectedly!") } }
func (t *SyncerTest) SetUp(ti *TestInfo) { var err error t.ctx = ti.Ctx // Set up dependencies. t.bucket = gcsfake.NewFakeBucket(&t.clock, "some_bucket") t.syncer = newSyncer( appendThreshold, &t.fullCreator, &t.appendCreator) t.clock.SetTime(time.Date(2015, 4, 5, 2, 15, 0, 0, time.Local)) // Set up a source object. t.srcObject, err = t.bucket.CreateObject( t.ctx, &gcs.CreateObjectRequest{ Name: "foo", Contents: strings.NewReader(srcObjectContents), }) AssertEq(nil, err) // Wrap a TempFile around it. t.content, err = NewTempFile( strings.NewReader(srcObjectContents), "", &t.clock) AssertEq(nil, err) // Return errors from the fakes by default. t.fullCreator.err = errors.New("Fake error") t.appendCreator.err = errors.New("Fake error") }
func TestPickerAttr(t *testing.T) { anchor := &PickerAttr{ TagName: "a", Attr: "href", } a, err := anchor.Pick(strings.NewReader("<a href='http://ddo.me'>test</a><a href='http://ddict.me'>test</a>")) if err != nil { t.Fail() return } if !reflect.DeepEqual(a, []string{"http://ddo.me", "http://ddict.me"}) { t.Fail() } script := &PickerAttr{ TagName: "script", Attr: "src", } s, err := script.Pick(strings.NewReader("<script src='haha'></script>")) if err != nil { t.Fail() return } if !reflect.DeepEqual(s, []string{"haha"}) { t.Fail() } }
func TestUnpackIntoStruct(t *testing.T) { dst := &testStruct{} expect := &testStruct{ A: 1, B: 2, C: 3, } err := UnpackInto(dst).From(Unpickle(strings.NewReader(input0))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", *dst, *expect) } //Test with python long type in input. Generates *big.Int //with value 1 dst = &testStruct{} err = UnpackInto(dst).From(Unpickle(strings.NewReader(input0WithLong))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", *dst, *expect) } }
func TestProjectType(t *testing.T) { t.Parallel() h := parsecli.NewHarness(t) defer h.Stop() h.MakeEmptyRoot() ensure.Nil(t, parsecli.CloneSampleCloudCode(h.Env, false)) c := &configureCmd{} err := c.projectType(h.Env, []string{"1", "2"}) ensure.Err(t, err, regexp.MustCompile("only an optional project type argument is expected")) h.Env.In = ioutil.NopCloser(strings.NewReader("invalid\n")) err = c.projectType(h.Env, nil) ensure.StringContains(t, h.Err.String(), "Invalid selection. Please enter a number") ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again.")) h.Err.Reset() h.Out.Reset() h.Env.In = ioutil.NopCloser(strings.NewReader("0\n")) err = c.projectType(h.Env, nil) ensure.StringContains(t, h.Err.String(), "Please enter a number between 1 and") ensure.Err(t, err, regexp.MustCompile("Could not make a selection. Please try again.")) h.Err.Reset() h.Out.Reset() h.Env.In = ioutil.NopCloser(strings.NewReader("1\n")) err = c.projectType(h.Env, nil) ensure.StringContains(t, h.Out.String(), "Successfully set project type to: parse") ensure.Nil(t, err) }
func TestAllowMismatchedFieldsInStruct(t *testing.T) { dest := &testStruct{} //Key "C" has value "Meow" const input = "(dp0\nS'A'\np1\nI1\nsS'C'\np2\nS'Meow'\np3\nsS'B'\np4\nI2\ns." err := UnpackInto(dest).From(Unpickle(strings.NewReader(input))) if err == nil { t.Fatal("Should fail") } unpackErr := err.(UnpackingError) expectErr := ErrTargetTypeMismatch if expectErr != unpackErr.Err { t.Fatalf("Wrong error:%v", err) } expect := &testStruct{A: 1, B: 2, C: 0} dest.C = 133000 unpacker := UnpackInto(dest) unpacker.AllowMismatchedFields = true err = unpacker.From(Unpickle(strings.NewReader(input))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(expect, dest) { t.Fatalf("Got %v expected %v", *dest, *expect) } }
func TestReadTruncated(t *testing.T) { const data = "0123456789abcdef" var b1 = make([]int32, 4) var b2 struct { A, B, C, D byte E int32 F float64 } for i := 0; i <= len(data); i++ { var errWant error switch i { case 0: errWant = io.EOF case len(data): errWant = nil default: errWant = io.ErrUnexpectedEOF } if err := Read(strings.NewReader(data[:i]), LittleEndian, &b1); err != errWant { t.Errorf("Read(%d) with slice: got %v, want %v", i, err, errWant) } if err := Read(strings.NewReader(data[:i]), LittleEndian, &b2); err != errWant { t.Errorf("Read(%d) with struct: got %v, want %v", i, err, errWant) } } }
func TestUnpackStructB(t *testing.T) { dst := &testStructB{} expect := &testStructB{ A: 42, B: 13.37, C: "foobar", D: *big.NewInt(1), E: true, } err := UnpackInto(dst).From(Unpickle(strings.NewReader(inputB))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", *dst, *expect) } dstP := &testStructBWithPointers{} err = UnpackInto(dstP).From(Unpickle(strings.NewReader(inputB))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", *dst, *expect) } }
func TestTriggerHooksUpdate(t *testing.T) { t.Parallel() h := newTriggersHarness(t) var tr triggerHooksCmd h.env.In = ioutil.NopCloser(strings.NewReader("foo\nbeforeSave\napi.example.com/_foo/beforeSave\n")) ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil)) ensure.DeepEqual(t, h.Out.String(), `Please enter following details about the trigger webhook Class name: Trigger name: URL: https://Successfully update the "beforeSave" trigger for class "foo" to point to "https://api.example.com/_foo/beforeSave" `) ensure.DeepEqual(t, h.Err.String(), "WARNING: beforeSave trigger already exists for class: foo\n") h.Out.Reset() h.Err.Reset() h.env.In = ioutil.NopCloser(strings.NewReader("bar\nafterSave\napi.example.com/_bar/afterSave\n")) ensure.Nil(t, tr.triggerHooksUpdate(h.env, nil)) ensure.DeepEqual(t, h.Out.String(), `Please enter following details about the trigger webhook Class name: Trigger name: URL: https://Successfully update the "afterSave" trigger for class "bar" to point to "https://api.example.com/_bar/afterSave" `) ensure.DeepEqual(t, h.Err.String(), "") }
func TestUnpackStructDWithStruct(t *testing.T) { dst := &testStructDWithStruct{} expect := &testStructDWithStruct{ Aardvark: 1, Bolus: 3.0, } expect.Cat.Apple = 2 expect.Cat.Banana = 3 err := UnpackInto(dst).From(Unpickle(strings.NewReader(inputD))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", *dst, *expect) } dst = &testStructDWithStruct{} err = UnpackInto(dst).From(Unpickle(strings.NewReader(inputDWithUnicode))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", *dst, *expect) } }
func TestPublisherType(t *testing.T) { var cases = []struct { name string reader io.Reader }{ {"default", bytes.NewReader(defaultConfig)}, {"notype", strings.NewReader("publishers: {memory: {}}")}, {"caseinsensitive", strings.NewReader("publishers: {memory: {type: MEMORYPUBLISHER}}")}, } for _, testcase := range cases { cfg, err := ReadConfig(testcase.reader) if err != nil { t.Fatalf("ReadConfig returned error for case %q: %s", testcase.name, err) } _, ok := cfg.Publishers["memory"] if !ok { t.Errorf("Expected 'memory' publisher not found (case %q)", testcase.name) continue } v, ok := cfg.Publishers["memory"]["type"] if !ok { t.Errorf("Expected 'type' element under 'memory' publisher (case %q)", testcase.name) } switch publisherType := v.(type) { case string: if publisherType != "memorypublisher" { t.Errorf("Expected 'type' to have value 'memorypublisher', not %q (case %q)", publisherType, testcase.name) } default: t.Errorf("Expected 'type' element to be a string, not %T (case %q)", publisherType, testcase.name) } } }
func TestUnpackSliceOfInts(t *testing.T) { dst := make([]int64, 0) expect := []int64{0, 1, 2, 3, 4} err := UnpackInto(&dst).From(Unpickle(strings.NewReader(inputF))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", dst, expect) } //Test that slices are re used and trimmed when needed for i := range dst { dst[i] = -1 } dst = append(dst, 42) err = UnpackInto(&dst).From(Unpickle(strings.NewReader(inputF))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", dst, expect) } }
func TestUnpackHeterogeneousList(t *testing.T) { dst := []interface{}{} expect := []interface{}{"meow", int64(42), "awesome"} err := UnpackInto(&dst).From(Unpickle(strings.NewReader(inputH))) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(dst, expect) { t.Fatalf("Got %v expected %v", dst, expect) } dst2 := []string{} err = UnpackInto(&dst2).From(Unpickle(strings.NewReader(inputH))) if err == nil { t.Fatal(err) } upe, ok := err.(UnpackingError) if !ok { t.Fatalf("Got wrong error type %T:%v", err, err) } i, ok := upe.Source.(int64) if !ok && i == 42 { t.Fatalf("Failed on wrong value %v(%T)", upe.Source, upe.Source) } }
func TestScoping(t *testing.T) { env := environment.New(nil) environment.Define(env, &types.Symbol{"begin"}, &types.Builtin{begin}) environment.Define(env, &types.Symbol{"+"}, &types.Builtin{add}) funcString := "(begin (define a 0) (define get-num ((lambda (a b) (define c 4) (lambda (b) (+ a b c))) 1 2)))" f, err := parser.Parse(strings.NewReader(funcString)) if err != nil { t.Error("Parsing funcString failed:", err) } if _, err := Eval(env, f); err != nil { t.Error("Evaluating funcString failed:", err) } f, _ = parser.Parse(strings.NewReader("a")) if a, err := Eval(env, f); err != nil { t.Error("Evaluating 'a' failed:", err) } else if !types.Eqv(a, &types.Number{0}) { t.Error("a != 0", a) } f, _ = parser.Parse(strings.NewReader("(get-num 8)")) if a, err := Eval(env, f); err != nil { t.Error("Evaluating (get-num) failed:", err) } else if !types.Eqv(a, &types.Number{13}) { t.Error("(get-num 8) != 13:", a) } }