func compareFiles(t *testing.T, expectedFN string, actualFN string) { var expectedBytes []byte var actualBytes []byte var err error expectedBytes, err = ioutil.ReadFile(expectedFN) if err != nil { t.Logf("Failed to open for compare: %s\n", err.Error()) t.Fail() return } actualBytes, err = ioutil.ReadFile(actualFN) if err != nil { t.Logf("Failed to open for compare: %s\n", err.Error()) t.FailNow() return } if len(expectedBytes) != len(actualBytes) { t.Logf("%s and %s differ in size\n", expectedFN, actualFN) t.Fail() return } if 0 != bytes.Compare(actualBytes, expectedBytes) { t.Logf("%s and %s differ\n", expectedFN, actualFN) t.Fail() return } }
func TestSecureSecretoxKey(t *testing.T) { key1, ok := secretbox.GenerateKey() if !ok { fmt.Println("pwkey: failed to generate test key") t.FailNow() } skey, ok := SecureSecretboxKey(testPass, key1) if !ok { fmt.Println("pwkey: failed to secure secretbox key") t.FailNow() } key, ok := RecoverSecretboxKey(testPass, skey) if !ok { fmt.Println("pwkey: failed to recover box private key") t.FailNow() } if !bytes.Equal(key[:], key1[:]) { fmt.Println("pwkey: recovered key doesn't match original") t.FailNow() } if _, ok = RecoverBoxKey([]byte("Password"), skey); ok { fmt.Println("pwkey: recover should fail with bad password") t.FailNow() } }
func TestVersion(t *testing.T) { v := new(Version) v.Version = uint16(1) v.Timestamp = time.Unix(0, 0) v.IpAddress = net.ParseIP("1.2.3.4") v.Port = uint16(4444) v.UserAgent = "Hello World!" verBytes := v.GetBytes() if len(verBytes) != verLen+12 { fmt.Println("Incorrect Byte Length: ", verBytes) t.Fail() } v2 := new(Version) err := v2.FromBytes(verBytes) if err != nil { fmt.Println("Error Decoding: ", err) t.FailNow() } if v2.Version != 1 || v2.Timestamp != time.Unix(0, 0) || v2.IpAddress.String() != "1.2.3.4" || v2.Port != 4444 || v2.UserAgent != "Hello World!" { fmt.Println("Incorrect decoded version: ", v2) t.Fail() } }
func TestDockerCommandBuildCancel(t *testing.T) { if helpers.SkipIntegrationTests(t, "docker", "info") { return } build := &common.Build{ GetBuildResponse: common.LongRunningBuild, Runner: &common.RunnerConfig{ RunnerSettings: common.RunnerSettings{ Executor: "docker", Docker: &common.DockerConfig{ Image: "alpine", }, }, }, } trace := &common.Trace{Writer: os.Stdout, Abort: make(chan interface{}, 1)} abortTimer := time.AfterFunc(time.Second, func() { t.Log("Interrupt") trace.Abort <- true }) defer abortTimer.Stop() timeoutTimer := time.AfterFunc(time.Minute, func() { t.Log("Timedout") t.FailNow() }) defer timeoutTimer.Stop() err := build.Run(&common.Config{}, trace) assert.IsType(t, err, &common.BuildError{}) assert.EqualError(t, err, "canceled") }
func TestQueue_EvenNumberOfPushesAndPops_GivesZeroFinalLength(t *testing.T) { underTest := NewQueue("Test") numberOfRounds := 200 for i := 0; i < numberOfRounds; i++ { dummyMessagePayLoad := []byte{byte(i)} dummyMessage := message.NewHeaderlessMessage(&dummyMessagePayLoad) underTest.InputChannel <- dummyMessage } gomega.Eventually(func() int { return underTest.length }).Should(gomega.Equal(numberOfRounds)) for i := 0; i < numberOfRounds; i++ { message := <-underTest.OutputChannel if int((*message.Body)[0]) != i { t.Logf("Expected %d, got %d", i, int((*message.Body)[0])) t.FailNow() } } gomega.Eventually(func() int { return underTest.length }).Should(gomega.Equal(0)) }
// Validate the ECDH component. func TestSharedKey(t *testing.T) { prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil) if err != nil { fmt.Println(err.Error()) t.FailNow() } skLen = MaxSharedKeyLength(&prv1.PublicKey) / 2 prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil) if err != nil { fmt.Println(err.Error()) t.FailNow() } sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen) if err != nil { fmt.Println(err.Error()) t.FailNow() } sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen) if err != nil { fmt.Println(err.Error()) t.FailNow() } if !bytes.Equal(sk1, sk2) { fmt.Println(ErrBadSharedKeys.Error()) t.FailNow() } }
func TestListen_available1(t *testing.T) { pm := newPortManager(portLow, portLow) l1, err := pm.listen() if err != nil { t.Fatal(err) } if l1.port() != portLow { t.Logf("Expected port %d, got port %d", portLow, l1.port()) l1.Close() t.FailNow() } l2, err := pm.listen() if err == nil { l1.Close() l2.Close() t.Fatal("Expected error when too many ports opened") } err = l1.Close() if err != nil { t.Fatal(err) } l3, err := pm.listen() if err != nil { t.Fatal(err) } if l3.port() != portLow { t.Logf("Expected port %d, got port %d", portLow, l3.port()) } l3.Close() }
func Test_BrHtmlTag(t *testing.T) { tests := testutils.ConversionTests{ { In: `a<br/> b<br/> c`, Want: `a \\ b \\ c`, }, { In: `a<br> b<br> c`, Want: `a \\ b \\ c`, }, } for _, test := range tests { got := BrHtmlTagToLatexLinebreak(test.In) if !reflect.DeepEqual(test.Want, got) { _, file, line, _ := runtime.Caller(0) fmt.Printf("%s:%d:\n\ncall BrHtmlTag(%#v)\n\texp: %#v\n\n\tgot: %#v\n\n", filepath.Base(file), line, test.In, test.Want, got) t.FailNow() } } testutils.Cleanup() }
func TestSymbolTable(t *testing.T) { o := vm.NewObject() o.AddSymbol("foo", vm.DATA, uint16(0xabcd)) o.AddSymbol("bar", vm.TEXT, uint16(0x1234)) b := o.SymTab.Bytes() expect := []byte{ 0xab, 0xcd, byte(vm.DATA), 0x3, 'f', 'o', 'o', 0x12, 0x34, byte(vm.TEXT), 0x3, 'b', 'a', 'r', } if !bytes.Equal(b, expect) { t.Log("expected:", expect, "got:", b) t.FailNow() } o2 := vm.NewObject() o2.ScanSymbolTable(b) for i, s := range o2.SymTab { if s != o.SymTab[i] { t.Log("expected:", o.SymTab, "got:", o2.SymTab) t.FailNow() } } }
func TestLinkNew(t *testing.T) { ports := make(nat.PortSet) ports[nat.Port("6379/tcp")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", nil, ports, nil) if err != nil { t.Fatal(err) } if link == nil { t.FailNow() } if link.Name != "/db/docker" { t.Fail() } if link.Alias() != "docker" { t.Fail() } if link.ParentIP != "172.0.17.3" { t.Fail() } if link.ChildIP != "172.0.17.2" { t.Fail() } for _, p := range link.Ports { if p != nat.Port("6379/tcp") { t.Fail() } } }
func TestLinkNaming(t *testing.T) { ports := make(nat.PortSet) ports[nat.Port("6379/tcp")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker-1", nil, ports, nil) if err != nil { t.Fatal(err) } rawEnv := link.ToEnv() env := make(map[string]string, len(rawEnv)) for _, e := range rawEnv { parts := strings.Split(e, "=") if len(parts) != 2 { t.FailNow() } env[parts[0]] = parts[1] } value, ok := env["DOCKER_1_PORT"] if !ok { t.Fatalf("DOCKER_1_PORT not found in env") } if value != "tcp://172.0.17.2:6379" { t.Fatalf("Expected 172.0.17.2:6379, got %s", env["DOCKER_1_PORT"]) } }
func TestCopyToSlicedArray(t *testing.T) { var arr [5]byte CopyExact(arr[:], "hello") if !bytes.Equal(arr[:], []byte("hello")) { t.FailNow() } }
// RequestOneAttempt gets a single attempt from the test's worker, or // fails the test immediately if not exactly one attempt was returned. func (sts *SimpleTestSetup) RequestOneAttempt(t *testing.T) coordinate.Attempt { attempts, err := sts.Worker.RequestAttempts(coordinate.AttemptRequest{}) if !(assert.NoError(t, err) && assert.Len(t, attempts, 1)) { t.FailNow() } return attempts[0] }
func TestServer(t *testing.T) { out := make(chan *Message) svr, err := NewServer(":7686", out) if err != nil { t.Log(err) t.FailNow() return } lis := Lis{svr, t} svr.Run() for !stop { select { case msg := <-out: switch msg.Type { case Type_connect: lis.OnConnect(msg.Id) case Type_message: lis.OnMessage(msg.Id, msg.Data) case Type_close: lis.OnClose(msg.Id, msg.Err) default: println("UNKONW MESSAGE", msg) } } } fmt.Println(stop) svr.Close() svr.Wait() }
func parseProfile(t *testing.T, bytes []byte, f func(uintptr, []uintptr)) { // Convert []byte to []uintptr. l := len(bytes) / int(unsafe.Sizeof(uintptr(0))) val := *(*[]uintptr)(unsafe.Pointer(&bytes)) val = val[:l] // 5 for the header, 2 for the per-sample header on at least one sample, 3 for the trailer. if l < 5+2+3 { t.Logf("profile too short: %#x", val) if badOS[runtime.GOOS] { t.Skipf("ignoring failure on %s; see golang.org/issue/6047", runtime.GOOS) return } t.FailNow() } hd, val, tl := val[:5], val[5:l-3], val[l-3:] if hd[0] != 0 || hd[1] != 3 || hd[2] != 0 || hd[3] != 1e6/100 || hd[4] != 0 { t.Fatalf("unexpected header %#x", hd) } if tl[0] != 0 || tl[1] != 1 || tl[2] != 0 { t.Fatalf("malformed end-of-data marker %#x", tl) } for len(val) > 0 { if len(val) < 2 || val[0] < 1 || val[1] < 1 || uintptr(len(val)) < 2+val[1] { t.Fatalf("malformed profile. leftover: %#x", val) } f(val[0], val[2:2+val[1]]) val = val[2+val[1]:] } }
func TestSectionTable(t *testing.T) { st := vm.SectionTable{ vm.TEXT: []byte{0x1, 0x2, 0x3, 0x4, 0x5}, vm.DATA: []byte{0xa, 0xb, 0xc, 0xd, 0xe, 0xf}, } b := st.Bytes() expect := []byte{0x2, byte(vm.TEXT), 0x0, 0xb, 0x0, 0x5, byte(vm.DATA), 0x0, 0x10, 0x0, 0x6, 0x1, 0x2, 0x3, 0x4, 0x5, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, } if !bytes.Equal(b, expect) { t.Log("expected:", expect, "got:", b) t.FailNow() } o := vm.NewObject() o.ScanSectionTable(b) for i, sec := range o.SecTab { if !bytes.Equal(st[i], sec) { t.Log("expected:", st[i], "got:", sec) t.FailNow() } } }
func TestBackAndForth(t *testing.T) { pt := pointerMapTest{42, 1, &simpleTest{66}} m := make(map[string]interface{}) if err := Map(&m, pt); err != nil { t.FailNow() } var ( v interface{} ok bool ) if v, ok = m["a"]; v.(int) != pt.A || !ok { t.Fatalf("pt not merged properly: m[`a`](%d) != pt.A(%d)", v, pt.A) } if v, ok = m["b"]; !ok { t.Fatalf("pt not merged properly: B is missing in m") } var st *simpleTest if st = v.(*simpleTest); st.Value != 66 { t.Fatalf("something went wrong while mapping pt on m, B wasn't copied") } bpt := pointerMapTest{} if err := Map(&bpt, m); err != nil { t.Fatal(err) } if bpt.A != pt.A { t.Fatalf("pt not merged properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A) } if bpt.hidden == pt.hidden { t.Fatalf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden) } if bpt.B.Value != pt.B.Value { t.Fatalf("pt not merged properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value) } }
func TestKMinValuesUnion(t *testing.T) { kmv1 := NewKMinValues(1000) kmv2 := NewKMinValues(1000) kmv3 := NewKMinValues(1000) for i := 0; i < 1500; i++ { hash := GetHash([]byte(fmt.Sprintf("%d", i))) kmv1.AddHash(hash) } for i := 100; i < 1000; i++ { hash := GetHash([]byte(fmt.Sprintf("%d", i))) kmv2.AddHash(hash) } for i := 400; i < 1500; i++ { hash := GetHash([]byte(fmt.Sprintf("%d", i))) kmv3.AddHash(hash) } kmv4 := kmv1.Union(kmv2) kmv5 := kmv1.Union(kmv2, kmv3) for i := 0; i < kmv3.Len(); i++ { if kmv4.GetHash(i) != kmv1.GetHash(i) { t.Errorf("Union(1) broke on index %d / %d", i, kmv4.Len()) t.FailNow() } if kmv5.GetHash(i) != kmv1.GetHash(i) { t.Errorf("Union(2) broke on index %d / %d", i, kmv4.Len()) t.FailNow() } } }
func TestSummary(t *testing.T) { file, err := os.Open("t-data/status.dat") if err != nil { t.Logf("%s", err) t.FailNow() } s, err := LoadStatus(file) _ = err Convey("get summary from status", t, func() { So(err, ShouldEqual, nil) Convey("host stats", func() { So(s.Summary.HostCount.All, ShouldEqual, 4) So(s.Summary.HostCount.Up, ShouldEqual, 2) So(s.Summary.HostCount.Down, ShouldEqual, 1) So(s.Summary.HostCount.Unreachable, ShouldEqual, 1) }) Convey("service stats", func() { So(s.Summary.ServiceCount.All, ShouldEqual, 7) So(s.Summary.ServiceCount.Ok, ShouldEqual, 4) So(s.Summary.ServiceCount.Warning, ShouldEqual, 1) So(s.Summary.ServiceCount.Critical, ShouldEqual, 1) So(s.Summary.ServiceCount.Unknown, ShouldEqual, 1) }) }) }
// Results are from http://www.lorem-ipsum.co.uk/hasher.php func Test_StaticCalculationSalting(t *testing.T) { var testsForABCDA1B2 = []testHash{{sha1.New, 1, "f877eed103f74c751952861e0630e643c4ec1eaa"}, {md5.New, 1, "dcfdf079664f00c2ad0d1e348b070bd5"}, {sha256.New, 1, "a193d7d1ba2253b712d13a0dd27bd7dfddcf04a6c8d904ae7e0e9ba2ced0f8fb"}} for i, test := range testsForABCDA1B2 { salt, err := NewSalt([]byte("ABCD"), 4, 128, []byte("A1B2")) if err != nil { t.Error("Test fail: Can't initialize Salt, error:", err) t.FailNow() } salt.Iterations = test.Iteration salt.Digest = test.Digest ref, err := hex.DecodeString(test.Password) if err != nil { t.Error("Test fail, can't convert", test.Password, "to bytes") } ok, err := salt.Match(ref, testMinPwdLen, testMaxPwdLen) if err != nil { t.Error("Test fail, error:", err) } else if !ok { t.Error("Test", i, "Fail: Expected external password", ref, "did not matched calculated password") } } }
func TestPipelineString(t *testing.T) { adaptor.Register("source", "description", NewTestadaptor, struct{}{}) data := []struct { in *Node terminalNode *Node out string }{ { fakesourceCN, nil, " - Source: source1 source ", }, { fakesourceCN, fileNode, " - Source: source1 source \n - Sink: localfile file file:///tmp/foo", }, } for _, v := range data { if v.terminalNode != nil { v.in.Add(v.terminalNode) } p, err := NewDefaultPipeline(v.in, "", "", "", 100*time.Millisecond) if err != nil { t.Errorf("can't create pipeline, got %s", err.Error()) t.FailNow() } if p.String() != v.out { t.Errorf("\nexpected:\n%s\ngot:\n%s\n", v.out, p.String()) } } }
func initThirdPartyMultiple(t *testing.T, versions, names []string) (*Master, *etcdtesting.EtcdTestServer, *httptest.Server, *assert.Assertions) { master, etcdserver, _, assert := newMaster(t) _, master.ServiceClusterIPRange, _ = net.ParseCIDR("10.0.0.0/24") for ix := range names { api := &extensions.ThirdPartyResource{ ObjectMeta: api.ObjectMeta{ Name: names[ix], }, Versions: []extensions.APIVersion{ { Name: versions[ix], }, }, } err := master.InstallThirdPartyResource(api) if !assert.NoError(err) { t.Logf("Failed to install API: %v", err) t.FailNow() } } server := httptest.NewServer(master.HandlerContainer.ServeMux) return master, etcdserver, server, assert }
func TestDockerCommandBuildAbort(t *testing.T) { if helpers.SkipIntegrationTests(t, "docker", "info") { return } build := &common.Build{ GetBuildResponse: common.LongRunningBuild, Runner: &common.RunnerConfig{ RunnerSettings: common.RunnerSettings{ Executor: "docker", Docker: &common.DockerConfig{ Image: "alpine", }, }, }, SystemInterrupt: make(chan os.Signal, 1), } abortTimer := time.AfterFunc(time.Second, func() { t.Log("Interrupt") build.SystemInterrupt <- os.Interrupt }) defer abortTimer.Stop() timeoutTimer := time.AfterFunc(time.Minute, func() { t.Log("Timedout") t.FailNow() }) defer timeoutTimer.Stop() err := build.Run(&common.Config{}, &common.Trace{Writer: os.Stdout}) assert.EqualError(t, err, "aborted: interrupt") }
func TestNewDoc(t *testing.T) { doc := golucy.NewDocument() doc.Add("foo", "bar") if val, ok := doc["foo"]; !ok || val != "bar" { t.Log("not what we expected", doc) t.FailNow() } doc = golucy.NewDocument() doc["foo"] = "bar" if val, ok := doc["foo"]; !ok || val != "bar" { t.Log("not what we expected", doc) t.FailNow() } doc = golucy.Document{"foo": "bar"} if val, ok := doc["foo"]; !ok || val != "bar" { t.Log("not what we expected", doc) t.FailNow() } fields := doc.GetFields() if len(fields) != 1 && cap(fields) != 1 { t.Log("not what we expected", len(fields), cap(fields), len(doc)) t.FailNow() } if fields[0] != "foo" { t.Log("not what we expected", fields[0], fields) t.FailNow() } }
func TestAssignConfig_03(t *testing.T) { jcf := &config.JSONConfig{} ac, _ := jcf.ParseData([]byte(`{"AppName":"beego"}`)) ac.Set("AppName", "test_app") ac.Set("RunMode", "online") ac.Set("StaticDir", "download:down download2:down2") ac.Set("StaticExtensionsToGzip", ".css,.js,.html,.jpg,.png") assignConfig(ac) t.Logf("%#v", BConfig) if BConfig.AppName != "test_app" { t.FailNow() } if BConfig.RunMode != "online" { t.FailNow() } if BConfig.WebConfig.StaticDir["/download"] != "down" { t.FailNow() } if BConfig.WebConfig.StaticDir["/download2"] != "down2" { t.FailNow() } if len(BConfig.WebConfig.StaticExtensionsToGzip) != 5 { t.FailNow() } }
func initThirdParty(t *testing.T, version string) (*tools.FakeEtcdClient, *httptest.Server) { master := &Master{} api := &expapi.ThirdPartyResource{ ObjectMeta: api.ObjectMeta{ Name: "foo.company.com", }, Versions: []expapi.APIVersion{ { APIGroup: "group", Name: version, }, }, } master.handlerContainer = restful.NewContainer() fakeClient := tools.NewFakeEtcdClient(t) fakeClient.Machines = []string{"http://machine1:4001", "http://machine2", "http://machine3:4003"} master.thirdPartyStorage = etcdstorage.NewEtcdStorage(fakeClient, explatest.Codec, etcdtest.PathPrefix()) if err := master.InstallThirdPartyAPI(api); err != nil { t.Errorf("unexpected error: %v", err) t.FailNow() } server := httptest.NewServer(master.handlerContainer.ServeMux) return fakeClient, server }
func TestMessage(t *testing.T) { log := make(chan string, 100) priv, x, y := encryption.CreateKey(log) pub := elliptic.Marshal(elliptic.P256(), x, y) address := encryption.GetAddress(log, x, y) msg := new(Message) msg.AddrHash = MakeHash(address) msg.TxidHash = MakeHash([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}) msg.Timestamp = time.Now().Round(time.Second) msg.Content = *encryption.Encrypt(log, pub, "Hello World!") mBytes := msg.GetBytes() if mBytes == nil { fmt.Println("Error Encoding Message!") t.FailNow() } msg2 := new(Message) msg2.FromBytes(mBytes) if string(msg2.AddrHash.GetBytes()) != string(msg.AddrHash.GetBytes()) || string(msg2.TxidHash.GetBytes()) != string(msg.TxidHash.GetBytes()) || msg2.Timestamp.Unix() != msg.Timestamp.Unix() { fmt.Println("Message Header incorrect: ", msg2) t.FailNow() } if string(encryption.Decrypt(log, priv, &msg.Content)[:12]) != "Hello World!" { fmt.Println("Message content incorrect: ", string(encryption.Decrypt(log, priv, &msg.Content)[:12])) t.Fail() } }
func TestLoadEntities(t *testing.T) { config := exampleConfig() extractor := NewExtractor(config) err := extractor.LoadEntities() if err != nil { fmt.Println(err) t.FailNow() } expectedTerms := [...]string{ "Government digital service", "GDS", "Ministry of Justice", "MoJ", } require.Equal(t, len(expectedTerms), len(extractor.entities.terms)) for i, expectedTerm := range expectedTerms { assert.Equal(t, expectedTerm, extractor.entities.terms[i]) } expectedIds := [...]string{ "1", "1", "2", "2", } for i, expectedId := range expectedIds { assert.Equal(t, expectedId, extractor.entities.termOffsetToEntity[i].id) } }
func TestObj(t *testing.T) { o := new(Obj) o.HashList = make([]Hash, 2, 2) o.HashList[0] = MakeHash([]byte{'a', 'b', 'c', 'd'}) o.HashList[1] = MakeHash([]byte{'e', 'f', 'g', 'h'}) o2 := new(Obj) oBytes := o.GetBytes() if len(oBytes) != 2*hashLen { fmt.Println("Incorrect Obj Length! ", oBytes) t.FailNow() } err := o2.FromBytes(oBytes) if err != nil { fmt.Println("Error while decoding obj: ", err) t.FailNow() } if string(o2.HashList[0].GetBytes()) != string(o.HashList[0].GetBytes()) || string(o2.HashList[1].GetBytes()) != string(o.HashList[1].GetBytes()) { fmt.Println("Incorrect decoding of obj: ", o2) t.Fail() } }
func writeImageToFile(t *testing.T, img image.Image, dstFilename string, fileFmt string, bmpOpts *EncoderOptions) { var err error file, err := os.Create(dstFilename) if err != nil { t.Logf("%s\n", err.Error()) t.FailNow() return } defer file.Close() if fileFmt == "png" { err = png.Encode(file, img) } else { if bmpOpts != nil { err = EncodeWithOptions(file, img, bmpOpts) } else { err = Encode(file, img) } } if err != nil { t.Logf("%s\n", err.Error()) t.FailNow() return } }