func TestNestedField(t *testing.T) {
	d := makeData()
	orig := d.B

	p := Parse("B")
	err := p.Set(d, &B{
		S: "10",
		I: 10,
	})

	assert.NoError(t, err, "Setting struct should succeed")
	assert.Equal(t, "10", d.B.S, "string field should reflect value from new struct")
	assert.Equal(t, 10, d.B.I, "int field should reflect value from new struct")
	assert.NotEqual(t, d.B, orig, "struct should change")

	gotten, err := Parse("B/S").Get(d)
	assert.NoError(t, err, "Getting nested string should succeed")
	assert.Equal(t, "10", gotten, "Getting nested string should have gotten right value")

	err = p.Clear(d)
	assert.NoError(t, err, "Clearing struct should succeed")
	assert.Nil(t, d.B, "struct should be nil after clearing")

	zv, err := p.ZeroValue(d)
	assert.NoError(t, err, "Getting zero value of struct should succeed")
	assert.Equal(t, &B{}, zv, "Zero value of struct should match expected")
}
func TestNestedMapEntry(t *testing.T) {
	d := makeData()
	orig := d.MapB["3"]

	p := Parse("MapB/3")
	err := p.Set(d, &B{
		S: "10",
		I: 10,
	})

	assert.NoError(t, err, "Setting struct should succeed")
	assert.Equal(t, "10", d.MapB["3"].S, "string field should reflect value from new struct")
	assert.Equal(t, 10, d.MapB["3"].I, "int field should reflect value from new struct")
	assert.NotEqual(t, d.B, orig, "struct should change")

	gotten, err := Parse("MapB/3/S").Get(d)
	assert.NoError(t, err, "Getting nested string should succeed")
	assert.Equal(t, "10", gotten, "Getting nested string should have gotten right value")

	err = p.Clear(d)
	assert.NoError(t, err, "Clearing struct should succeed")
	_, found := d.MapB["3"]
	assert.False(t, found, "struct should be gone from map after clearing")

	zv, err := p.ZeroValue(d)
	assert.NoError(t, err, "Getting zero value of struct should succeed")
	assert.Equal(t, &B{}, zv, "Zero value of struct should match expected")
}
Beispiel #3
0
func TestConcurrent(t *testing.T) {
	v := NewValue()

	var sets int32 = 0

	go func() {
		var wg sync.WaitGroup
		wg.Add(1)
		// Do some concurrent setting to make sure that it works
		for i := 0; i < concurrency; i++ {
			go func() {
				// Wait for waitGroup so that all goroutines run at basically the same
				// time.
				wg.Wait()
				v.Set("hi")
				atomic.AddInt32(&sets, 1)
			}()
		}
		wg.Done()
	}()

	time.Sleep(50 * time.Millisecond)
	r, ok := v.Get(20 * time.Millisecond)
	assert.True(t, ok, "Get should have succeed")
	assert.Equal(t, "hi", r, "Wrong result")
	assert.Equal(t, concurrency, atomic.LoadInt32(&sets), "Wrong number of successful Sets")
}
Beispiel #4
0
func doTestConn(t *testing.T, conn net.Conn) {
	defer func() {
		if err := conn.Close(); err != nil {
			log.Debugf("Unable to close connection: %v", err)
		}
	}()

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		n, err := conn.Write(msg)
		assert.NoError(t, err, "Writing should have succeeded")
		assert.Equal(t, len(msg), n, "Should have written full message")
		wg.Done()
	}()
	go func() {
		b := make([]byte, len(msg))
		n, err := io.ReadFull(conn, b)
		assert.NoError(t, err, "Read should have succeeded")
		assert.Equal(t, len(msg), n, "Should have read full message")
		assert.Equal(t, msg, b[:n], "Read should have matched written")
		wg.Done()
	}()

	wg.Wait()
}
Beispiel #5
0
func TestLoggly(t *testing.T) {
	var buf bytes.Buffer
	var result map[string]interface{}
	loggly := loggly.New("token not required")
	loggly.Writer = &buf
	lw := logglyErrorWriter{client: loggly}
	golog.SetOutputs(lw, nil)
	log := golog.LoggerFor("test")

	log.Error("")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Regexp(t, regexp.MustCompile("logging_test.go:([0-9]+)"), result["message"])
	}

	buf.Reset()
	log.Error("short message")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Regexp(t, regexp.MustCompile("logging_test.go:([0-9]+) short message"), result["message"])
	}

	buf.Reset()
	log.Error("message with: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Regexp(t, "logging_test.go:([0-9]+) message with: reason", result["message"])
	}

	buf.Reset()
	log.Error("deep reason: message with: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Equal(t, "message with: reason", result["message"], "message should be last 2 chunks")
	}

	buf.Reset()
	log.Error("deep reason: an url https://a.com in message: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "an url https://a.com in message: reason", result["message"], "should not truncate url")
	}

	buf.Reset()
	log.Error("deep reason: an url 127.0.0.1:8787 in message: reason")
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])
		assert.Equal(t, "an url 127.0.0.1:8787 in message: reason", result["message"], "should not truncate url")
	}

	buf.Reset()
	longPrefix := "message with: really l"
	longMsg := longPrefix + strings.Repeat("o", 100) + "ng reason"
	log.Error(longMsg)
	if assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), "Unmarshal error") {
		assert.Equal(t, "ERROR test", result["locationInfo"])

		assert.Regexp(t, regexp.MustCompile("logging_test.go:([0-9]+) "+longPrefix+"(o+)"), result["message"])
		assert.Equal(t, 100, len(result["message"].(string)))
	}
}
Beispiel #6
0
func TestConfigureAndPAC(t *testing.T) {
	expectedDeltaA := &Delta{
		Additions: []string{"A", "B", "D"},
	}
	expectedDeltaB := &Delta{
		Additions: []string{"E"},
		Deletions: []string{"B", "D"},
	}

	delta := Configure(&Config{
		Cloud: []string{"A", "B", "C"},
		Delta: &Delta{
			Additions: []string{"D"},
			Deletions: []string{"C"},
		},
	})
	assert.Equal(t, expectedDeltaA, delta)

	delta = Configure(&Config{
		Cloud: []string{"A", "B", "C"},
		Delta: &Delta{
			Additions: []string{"E"},
			Deletions: []string{"B", "C"},
		},
	})
	assert.Equal(t, expectedDeltaB, delta)
}
Beispiel #7
0
func TestLines(t *testing.T) {
	buf := bytes.NewBuffer(nil)
	i := int32(0)
	w := LinePrepender(buf, func(w io.Writer) (int, error) {
		j := atomic.AddInt32(&i, 1)
		return fmt.Fprintf(w, "%d ", j)
	})

	n, err := fmt.Fprint(w, "A")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 1, n, "Wrong bytes written for A")
	}
	n, err = fmt.Fprintln(w, "")
	if assert.NoError(t, err, "Error writing newline after A") {
		assert.Equal(t, 1, n, "Wrong bytes written for newline after A")
	}
	n, err = fmt.Fprintf(w, "B\nC")
	if assert.NoError(t, err, "Error writing BC") {
		assert.Equal(t, 3, n, "Wrong bytes written for BC")
	}
	n, err = fmt.Fprintln(w, "\nD")
	if assert.NoError(t, err, "Error writing D") {
		assert.Equal(t, 3, n, "Wrong bytes written for D")
	}

	assert.Equal(t, expected, string(buf.Bytes()))
}
Beispiel #8
0
func TestCreateAndRefresh(t *testing.T) {
	if true {
		t.Log("We don't currently use peerscanner, so this test is disabled. To reenable, we'll need to delete test distributions to avoid hitting our limit")
		return
	}
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	// Deleting cloudfront distributions is actually quite an involved process.
	// Fortunately, distributions per se cost us nothing.  A separate service
	// will be implemented to delete test and otherwise unused distributions.
	name := uuid.NewV4().String()
	dist, err := CreateDistribution(cfr, name, name+"-grey.flashlightproxy.org", COMMENT)
	assert.NoError(t, err, "Should be able to create distribution")
	assert.Equal(t, "InProgress", dist.Status, "New distribution should have Status: \"InProgress\"")
	assert.Equal(t, dist.Comment, COMMENT, "New distribution should have the comment we've set for it")
	assert.Equal(t, name, dist.InstanceId, "New distribution should have the right InstanceId")
	assert.True(t, strings.HasSuffix(dist.Domain, ".cloudfront.net"), "Domain should be a .cloudfront.net subdomain, not '"+dist.Domain+"'")
	dist.Status = "modified to check it really gets overwritten"
	err = RefreshStatus(cfr, dist)
	assert.NoError(t, err, "Should be able to refresh status")
	// Just check that Status stays a valid one.  Checking that it eventually
	// gets refreshed to "Deployed" would take a few minutes, and thus is out
	// of the scope of this unit test.
	assert.Equal(t, "InProgress", dist.Status, "New distribution should have Status: \"InProgress\" even after refreshing right away")
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Beispiel #9
0
func TestIgnoreEmpty(t *testing.T) {
	tarString := bytes.NewBuffer(nil)
	err := EncodeToTarString("resources", tarString)
	if err != nil {
		t.Fatalf("Unable to encode to tar string: %v", err)
	}

	fs, err := New(tarStringToBytes(t, tarString), "localresources")
	if err != nil {
		t.Fatalf("Unable to open filesystem: %v", err)
	}

	// Test to make sure we get the file if we're not ignoring empty.
	// Note empty on disk actually has a single space to allow us to
	// check it into git, but the method ignores whitespace.
	a, err := fs.Get("empty.txt")
	if assert.NoError(t, err, "empty.txt should have loaded") {
		assert.Equal(t, " \n", string(a), "A should have matched expected")
	}

	// We artificially change the entry for empty byte in the file system
	// to make sure we get the file system and not the local version.
	emptyBytes := []byte("empty")
	fs.files["empty.txt"] = emptyBytes

	a, err = fs.GetIgnoreLocalEmpty("empty.txt")
	if assert.NoError(t, err, "empty.txt should have loaded") {
		assert.Equal(t, string(emptyBytes), string(a), "A should have matched expected")
	}
}
Beispiel #10
0
func TestSuccess(t *testing.T) {
	text, timedOut, err := Do(1*time.Second, func() (interface{}, error) {
		return expectedText, expectedErr
	})
	assert.False(t, timedOut, "Should not have timed out")
	assert.Equal(t, expectedText, text, "Text should match expected")
	assert.Equal(t, expectedErr, err, "Error should match expected")
}
Beispiel #11
0
func TestConfigServer(t *testing.T) {
	file, err := ioutil.TempFile("", "yamlconf_test_")
	if err != nil {
		t.Fatalf("Unable to create temp file: %s", err)
	}
	defer os.Remove(file.Name())

	m := &Manager{
		EmptyConfig: func() Config {
			return &TestCfg{}
		},
		FilePath:         file.Name(),
		FilePollInterval: pollInterval,
		ConfigServerAddr: ConfigSrvAddr,
	}

	_, err = m.Init()
	if err != nil {
		t.Fatalf("Unable to init manager: %s", err)
	}
	m.StartPolling()

	newNested := &Nested{
		S: "900",
		I: 900,
	}
	nny, err := yaml.Marshal(newNested)
	if err != nil {
		t.Fatalf("Unable to marshal new nested into yaml: %s", err)
	}

	_, err = http.Post(fmt.Sprintf("http://%s/N", ConfigSrvAddr), "text/yaml", bytes.NewReader(nny))
	assert.NoError(t, err, "POSTing to config server should succeed")

	updated := m.Next()

	assert.Equal(t, &TestCfg{
		Version: 2,
		N:       newNested,
	}, updated, "Nested should have been updated by POST")

	req, err := http.NewRequest("DELETE", fmt.Sprintf("http://%s/N/I", ConfigSrvAddr), bytes.NewReader(nny))
	if err != nil {
		t.Fatalf("Unable to construct DELETE request: %s", err)
	}
	_, err = (&http.Client{}).Do(req)
	assert.NoError(t, err, "DELETEing to config server should succeed")

	updated = m.Next()

	assert.Equal(t, &TestCfg{
		Version: 3,
		N: &Nested{
			S: newNested.S,
			I: FIXED_I,
		},
	}, updated, "Nested I should have reverted to default value after clearing")
}
Beispiel #12
0
func TestWriteTooLong(t *testing.T) {
	w := NewWriter(ioutil.Discard)
	b := make([]byte, MaxFrameLength+1)
	n, err := w.Write(b)
	assert.Error(t, err, "Writing too long message should result in error")
	assert.Equal(t, 0, n, "Writing too long message should result in 0 bytes written")
	n, err = w.Write(b[:len(b)-1])
	assert.NoError(t, err, "Writing message of MaxFrameLength should be allowed")
	assert.Equal(t, MaxFrameLength, n, "Writing message of MaxFrameLength should have written MaxFrameLength bytes")
}
Beispiel #13
0
func TestRoundTrip(t *testing.T) {
	defer func() {
		if err := os.Remove(PK_FILE); err != nil {
			log.Debugf("Unable to remove file: %v", err)
		}
	}()
	defer func() {
		if err := os.Remove(CERT_FILE); err != nil {
			log.Debugf("Unable to remove file: %v", err)
		}
	}()

	pk, err := GeneratePK(1024)
	assert.NoError(t, err, "Unable to generate PK")

	err = pk.WriteToFile(PK_FILE)
	assert.NoError(t, err, "Unable to save PK")

	pk2, err := LoadPKFromFile(PK_FILE)
	assert.NoError(t, err, "Unable to load PK")
	assert.Equal(t, pk.PEMEncoded(), pk2.PEMEncoded(), "Loaded PK didn't match saved PK")

	cert, err := pk.TLSCertificateFor("Test Org", "127.0.0.1", time.Now().Add(TWO_WEEKS), true, nil)
	assert.NoError(t, err, "Unable to generate self-signed certificate")

	numberOfIPSANs := len(cert.X509().IPAddresses)
	if numberOfIPSANs != 1 {
		t.Errorf("Wrong number of SANs, expected 1 got %d", numberOfIPSANs)
	} else {
		ip := cert.X509().IPAddresses[0]
		expectedIP := net.ParseIP("127.0.0.1")
		assert.Equal(t, expectedIP.String(), ip.String(), "Wrong IP SAN")
	}

	err = cert.WriteToFile(CERT_FILE)
	assert.NoError(t, err, "Unable to write certificate to file")

	cert2, err := LoadCertificateFromFile(CERT_FILE)
	assert.NoError(t, err, "Unable to load certificate from file")
	assert.Equal(t, cert.PEMEncoded(), cert2.PEMEncoded(), "Loaded certificate didn't match saved certificate")

	_, err = pk.Certificate(cert.X509(), cert)
	assert.NoError(t, err, "Unable to generate certificate signed by original certificate")

	pk3, err := GeneratePK(1024)
	assert.NoError(t, err, "Unable to generate PK 3")

	_, err = pk.CertificateForKey(cert.X509(), cert, &pk3.rsaKey.PublicKey)
	assert.NoError(t, err, "Unable to generate certificate for pk3")

	x509rt, err := LoadCertificateFromX509(cert.X509())
	assert.NoError(t, err, "Unable to load certificate from X509")
	assert.Equal(t, cert, x509rt, "X509 round tripped cert didn't match original")
}
Beispiel #14
0
func TestSimplePrepender(t *testing.T) {
	buf := bytes.NewBuffer(nil)
	w := SimplePrepender(buf, func(w io.Writer) (int, error) {
		return fmt.Fprintf(w, "++ ")
	})

	n, err := fmt.Fprint(w, "##")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 5, n, "Wrong bytes written for A")
	}

	n, err = fmt.Fprint(w, "##\n\n")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 7, n, "Wrong bytes written for A")
	}

	n, err = fmt.Fprint(w, "\n\n##\n\n")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 9, n, "Wrong bytes written for A")
	}

	w = SimplePrepender(buf, func(w io.Writer) (int, error) {
		return fmt.Fprintf(w, "")
	})

	n, err = fmt.Fprint(w, "##")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 2, n, "Wrong bytes written for A")
	}

	n, err = fmt.Fprint(w, "##\n\n")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 4, n, "Wrong bytes written for A")
	}

	n, err = fmt.Fprint(w, "\n\n##\n\n")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 6, n, "Wrong bytes written for A")
	}

	w = SimplePrepender(buf, func(w io.Writer) (int, error) {
		return fmt.Fprintf(w, "\n\n")
	})

	n, err = fmt.Fprint(w, "##")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 4, n, "Wrong bytes written for A")
	}

	n, err = fmt.Fprint(w, "##\n\n")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 6, n, "Wrong bytes written for A")
	}

	n, err = fmt.Fprint(w, "\n\n##\n\n")
	if assert.NoError(t, err, "Error writing A") {
		assert.Equal(t, 8, n, "Wrong bytes written for A")
	}
}
Beispiel #15
0
func compareReports(t *testing.T, expected report, actual report, index string) {
	expectedDims := expected["dims"].(map[string]string)
	actualDims := actual["dims"].(map[string]string)

	assert.Equal(t, expectedDims["a"], actualDims["a"], fmt.Sprintf("On %s, dim a should match", index))
	assert.Equal(t, expectedDims["b"], actualDims["b"], fmt.Sprintf("On %s, dim b should match", index))

	assert.Equal(t, expected["increments"], actual["increments"], fmt.Sprintf("On %s, increments should match", index))
	assert.Equal(t, expected["gauges"], actual["gauges"], fmt.Sprintf("On %s, gauges should match", index))
	assert.Equal(t, expected["multiMembers"], actual["multiMembers"], fmt.Sprintf("On %s, members should match", index))
}
Beispiel #16
0
// Test tests a Dialer.
func Test(t *testing.T, dialer Dialer) {
	// Set up listener for server endpoint
	sl, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatalf("Unable to listen: %s", err)
	}

	// Server that responds to ping
	go func() {
		conn, err := sl.Accept()
		if err != nil {
			t.Fatalf("Unable to accept connection: %s", err)
			return
		}
		defer func() {
			if err := conn.Close(); err != nil {
				t.Logf("Unable to close connection: %v", err)
			}
		}()
		b := make([]byte, 4)
		_, err = io.ReadFull(conn, b)
		if err != nil {
			t.Fatalf("Unable to read from client: %s", err)
		}
		assert.Equal(t, ping, b, "Didn't receive correct ping message")
		_, err = conn.Write(pong)
		if err != nil {
			t.Fatalf("Unable to write to client: %s", err)
		}
	}()

	conn, err := dialer.Dial("connect", sl.Addr().String())
	if err != nil {
		t.Fatalf("Unable to dial via proxy: %s", err)
	}
	defer func() {
		if err := conn.Close(); err != nil {
			t.Logf("Unable to close connection: %v", err)
		}
	}()

	_, err = conn.Write(ping)
	if err != nil {
		t.Fatalf("Unable to write to server via proxy: %s", err)
	}

	b := make([]byte, 4)
	_, err = io.ReadFull(conn, b)
	if err != nil {
		t.Fatalf("Unable to read from server: %s", err)
	}
	assert.Equal(t, pong, b, "Didn't receive correct pong message")
}
Beispiel #17
0
func doTestPlainText(buffered bool, useHostFn bool, t *testing.T) {
	var counter *fdcount.Counter
	var err error

	startServers(t, useHostFn)

	err = fdcount.WaitUntilNoneMatch("CLOSE_WAIT", 5*time.Second)
	if err != nil {
		t.Fatalf("Unable to wait until no more connections are in CLOSE_WAIT: %v", err)
	}

	_, counter, err = fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get fdcount: %v", err)
	}

	var reportedHost string
	var reportedHostMutex sync.Mutex
	onResponse := func(resp *http.Response) {
		reportedHostMutex.Lock()
		reportedHost = resp.Header.Get(X_ENPROXY_PROXY_HOST)
		reportedHostMutex.Unlock()
	}

	conn, err := prepareConn(httpAddr, buffered, false, t, onResponse)
	if err != nil {
		t.Fatalf("Unable to prepareConn: %s", err)
	}
	defer func() {
		err := conn.Close()
		assert.Nil(t, err, "Closing conn should succeed")
		if !assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed") {
			DumpConnTrace()
		}
	}()

	doRequests(conn, t)

	assert.Equal(t, 208, bytesReceived, "Wrong number of bytes received")
	assert.Equal(t, 284, bytesSent, "Wrong number of bytes sent")
	assert.True(t, destsSent[httpAddr], "http address wasn't recorded as sent destination")
	assert.True(t, destsReceived[httpAddr], "http address wasn't recorded as received destination")

	reportedHostMutex.Lock()
	rh := reportedHost
	reportedHostMutex.Unlock()
	assert.Equal(t, "localhost", rh, "Didn't get correct reported host")
}
Beispiel #18
0
func TestStringOK(t *testing.T) {
	id1 := Random()
	id1String := id1.String()
	id2, err := FromString(id1String)
	assert.NoError(t, err, "Unable to read from string")
	assert.Equal(t, id1.ToBytes(), id2.ToBytes(), "Read didn't match written")
}
Beispiel #19
0
func connectAndRead(t *testing.T, p Pool, loops int) {
	var wg sync.WaitGroup

	for i := 0; i < loops; i++ {
		wg.Add(1)

		func(wg *sync.WaitGroup) {
			c, err := p.Get()
			if err != nil {
				t.Fatalf("Error getting connection: %s", err)
			}
			read, err := ioutil.ReadAll(c)
			if err != nil {
				t.Fatalf("Error reading from connection: %s", err)
			}
			assert.Equal(t, msg, read, "Should have received %s from server", string(msg))
			if err := c.Close(); err != nil {
				t.Fatalf("Unable to close connection: %v", err)
			}

			wg.Done()
		}(&wg)
	}

	wg.Wait()
}
Beispiel #20
0
func TestTCP(t *testing.T) {
	// Lower maxAssertAttempts to keep this test from running too long
	maxAssertAttempts = 2

	l0, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := l0.Close(); err != nil {
			t.Fatalf("Unable to close listener: %v", err)
		}
	}()

	start, fdc, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 1, start, "Starting count should have been 1")

	err = fdc.AssertDelta(0)
	if err != nil {
		t.Fatal(err)
	}
	assert.NoError(t, err, "Initial TCP count should be 0")

	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	_, middle, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.True(t, len(err.Error()) > 100)
	}
	err = fdc.AssertDelta(1)
	assert.NoError(t, err, "Ending TCP count should be 1")

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.Contains(t, err.Error(), "New")
		assert.True(t, len(err.Error()) > 100)
	}

	if err := l.Close(); err != nil {
		t.Fatalf("Unable to close listener: %v", err)
	}
	err = middle.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have -1")
		assert.Contains(t, err.Error(), "Removed")
		assert.True(t, len(err.Error()) > 100)
	}
}
Beispiel #21
0
func closeAndCountFDs(t *testing.T, conn *tls.Conn, err error, fdStart int) {
	if err == nil {
		conn.Close()
	}
	fdEnd := countTCPFiles()
	assert.Equal(t, fdStart, fdEnd, "Number of open TCP files should be the same after test as before")
}
Beispiel #22
0
func TestCustomPoll(t *testing.T) {
	file, err := ioutil.TempFile("", "yamlconf_test_")
	if err != nil {
		t.Fatalf("Unable to create temp file: %s", err)
	}
	defer func() {
		if err := os.Remove(file.Name()); err != nil {
			t.Fatalf("Unable to remove file: %s", err)
		}
	}()

	poll := 0
	m := &Manager{
		EmptyConfig: func() Config {
			return &TestCfg{}
		},
		FilePath:         file.Name(),
		FilePollInterval: pollInterval,
		CustomPoll: func(currentCfg Config) (func(cfg Config) error, time.Duration, error) {
			defer func() {
				poll = poll + 1
			}()
			switch poll {
			case 0:
				// Return an error on the poll
				return nil, 10 * time.Millisecond, fmt.Errorf("I don't wanna poll")
			case 1:
				// Return an error in the mutator
				return func(cfg Config) error {
					return fmt.Errorf("I don't wanna mutate")
				}, 10 * time.Millisecond, nil
			default:
				// Return a good mutator
				return func(cfg Config) error {
					tc := cfg.(*TestCfg)
					tc.N.S = "Modified"
					return nil
				}, 100 * time.Hour, nil
			}
		},
	}

	_, err = m.Init()
	m.StartPolling()
	if err != nil {
		t.Fatalf("Unable to init manager: %s", err)
	}
	m.StartPolling()

	updated := m.Next()

	assert.Equal(t, &TestCfg{
		Version: 2,
		N: &Nested{
			S: "Modified",
			I: FIXED_I,
		},
	}, updated, "Custom polled config should contain correct data")
}
Beispiel #23
0
func TestDialFailure(t *testing.T) {
	fail := int32(1)
	dialAttempts := int32(0)

	addr, err := startTestServer()
	if err != nil {
		t.Fatalf("Unable to start test server: %s", err)
	}

	_, fdc, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	poolSize := 10

	p := New(Config{
		Size: poolSize,
		Dial: func() (net.Conn, error) {
			atomic.AddInt32(&dialAttempts, 1)
			if fail == int32(1) {
				return nil, fmt.Errorf("I'm failing intentionally!")
			}
			return net.DialTimeout("tcp", addr, 15*time.Millisecond)
		},
	})

	// Try to get connection, make sure it fails
	conn, err := p.Get()
	if !assert.Error(t, err, "Dialing should have failed") {
		if err := conn.Close(); err != nil {
			t.Fatalf("Unable to close connection: %v", err)
		}
	}

	// Wait for fill to run for a while with a failing connection
	time.Sleep(1 * time.Second)
	assert.Equal(t, 1, atomic.LoadInt32(&dialAttempts), fmt.Sprintf("There should have been only 1 dial attempt"))
	assert.NoError(t, fdc.AssertDelta(0), "There should be no additional file descriptors open")

	// Now make connection succeed and verify that it works
	atomic.StoreInt32(&fail, 0)
	time.Sleep(100 * time.Millisecond)
	connectAndRead(t, p, 1)

	time.Sleep(fillTime)
	log.Debug("Testing")
	assert.NoError(t, fdc.AssertDelta(10), "Pool should have filled")

	// Now make the connection fail again so that when we stop, we're stopping
	// while failing (tests a different code path for stopping)
	atomic.StoreInt32(&fail, 1)
	time.Sleep(100 * time.Millisecond)

	p.Close()

	assert.NoError(t, fdc.AssertDelta(0), "All connections should be closed")
}
Beispiel #24
0
func TestReadWriteOK(t *testing.T) {
	id1 := Random()
	b := make([]byte, EncodedLength)
	err := id1.Write(b)
	assert.NoError(t, err, "Unable to write")
	id2, err := Read(b)
	assert.NoError(t, err, "Unable to read")
	assert.Equal(t, id1.ToBytes(), id2.ToBytes(), "Read didn't match written")
}
Beispiel #25
0
func TestError(t *testing.T) {
	out := bytes.NewBuffer(nil)
	l := LoggerFor("myprefix")
	l.(*logger).errorOut = out
	l.Error("Hello world")
	l.Errorf("Hello %d", 5)

	assert.Equal(t, expectedLog, string(out.Bytes()), "Logged information didn't match expected")
}
Beispiel #26
0
func TestError(t *testing.T) {
	out := bytes.NewBuffer(nil)
	SetOutputs(out, ioutil.Discard)
	l := LoggerFor("myprefix")
	l.Error("Hello world")
	l.Errorf("Hello %d", 5)

	assert.Equal(t, expectedLog, string(out.Bytes()), "Logged information didn't match expected")
}
Beispiel #27
0
// TestIntegration tests against existing domain-fronted servers running on
// CloudFlare.
func TestIntegration(t *testing.T) {
	dialedDomain := ""
	dialedAddr := ""
	actualResolutionTime := time.Duration(0)
	actualConnectTime := time.Duration(0)
	actualHandshakeTime := time.Duration(0)
	var statsMutex sync.Mutex

	statsFunc := func(success bool, domain, addr string, resolutionTime, connectTime, handshakeTime time.Duration) {
		if success {
			statsMutex.Lock()
			defer statsMutex.Unlock()
			dialedDomain = domain
			dialedAddr = addr
			actualResolutionTime = resolutionTime
			actualConnectTime = connectTime
			actualHandshakeTime = handshakeTime
		}
	}

	d := integrationDialer(t, statsFunc)
	defer func() {
		if err := d.Close(); err != nil {
			t.Fatalf("Unable to close dialer: %v", err)
		}
	}()

	hc := &http.Client{
		Transport: &http.Transport{
			Dial: d.Dial,
		},
	}

	resp, err := hc.Get("https://www.google.com/humans.txt")
	if err != nil {
		t.Fatalf("Unable to fetch from Google: %s", err)
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			t.Fatalf("Unable to close response body: %v", err)
		}
	}()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Unable to read response from Google: %s", err)
	}
	assert.Equal(t, expectedGoogleResponse, string(b), "Didn't get expected response from Google")

	statsMutex.Lock()
	defer statsMutex.Unlock()
	assert.True(t, dialedDomain == "100partnerprogramme.de" || dialedDomain == "10minutemail.com", "Dialed domain didn't match one of the masquerade domains", dialedDomain)
	assert.NotEqual(t, "", dialedAddr, "Should have received an addr")
	assert.NotEqual(t, time.Duration(0), actualResolutionTime, "Should have received a resolutionTime")
	assert.NotEqual(t, time.Duration(0), actualConnectTime, "Should have received a connectTime")
	assert.NotEqual(t, time.Duration(0), actualHandshakeTime, "Should have received a handshakeTime")
}
Beispiel #28
0
func TestTimeout(t *testing.T) {
	text, timedOut, err := Do(10*time.Millisecond, func() (interface{}, error) {
		time.Sleep(11 * time.Millisecond)
		return expectedText, expectedErr
	})
	assert.True(t, timedOut, "Should have timed out")
	assert.NotNil(t, err, "There should be an error")
	assert.Nil(t, text, "Text should be nil")
	assert.Equal(t, timeoutErrorString, err.Error(), "Error should contain correct string")
}
Beispiel #29
0
func TestNestedSliceEntry(t *testing.T) {
	d := makeData()
	orig := d.SliceB[1]

	p := Parse("SliceB/1")
	err := p.Set(d, &B{
		S: "10",
		I: 10,
	})

	assert.NoError(t, err, "Setting struct should succeed")
	assert.Equal(t, "10", d.SliceB[1].S, "string field should reflect value from new struct")
	assert.Equal(t, 10, d.SliceB[1].I, "int field should reflect value from new struct")
	assert.NotEqual(t, d.B, orig, "struct should change")

	err = p.Clear(d)
	assert.NoError(t, err, "Clearing struct should succeed")
	assert.Nil(t, d.SliceB[1], "struct should be gone from slice after clearing")
}
Beispiel #30
0
func TestZeroValue(t *testing.T) {
	d := map[string]map[string]int{
		"a": map[string]int{},
	}

	p := Parse("a/a2")
	zv, err := p.ZeroValue(d)
	assert.NoError(t, err, "Getting zero value for nonexistent element should succeed")
	assert.Equal(t, 0, zv, "Zero value for nonexistent element should be correct")
}