Esempio n. 1
0
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")
}
Esempio n. 2
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")
}
Esempio n. 3
0
func TestTranslate(t *testing.T) {
	assertTranslation(t, "", "HELLO")
	UseOSLocale()
	assertTranslation(t, "I speak America English!", "ONLY_IN_EN_US")
	assertTranslation(t, "I speak Generic English!", "ONLY_IN_EN")
	assertTranslation(t, "", "NOT_EXISTED")

	SetMessagesDir("not-existed-dir")
	err := SetLocale("en_US")
	assert.Error(t, err, "should error if dir is not existed")

	SetMessagesDir("locale")
	assert.Error(t, SetLocale("e0"), "should error on malformed locale")
	assert.Error(t, SetLocale("e0-DO"), "should error on malformed locale")
	assert.Error(t, SetLocale("e0-DO.C"), "should error on malformed locale")
	assert.NoError(t, SetLocale("en"), "should change locale")
	if assert.NoError(t, SetLocale("en_US"), "should change locale") {
		// formatting
		assertTranslation(t, "Hello An Argument!", "HELLO", "An Argument")
		assertTranslation(t, "", "NOT_EXISTED", "extra args")
	}
	if assert.NoError(t, SetLocale("zh_CN"), "should change locale") {
		assertTranslation(t, "An Argument你好!", "HELLO", "An Argument")
		// fallbacks
		assertTranslation(t, "I speak Mandarin!", "ONLY_IN_ZH_CN")
		assertTranslation(t, "I speak Chinese!", "ONLY_IN_ZH")
		assertTranslation(t, "I speak America English!", "ONLY_IN_EN_US")
		assertTranslation(t, "I speak Generic English!", "ONLY_IN_EN")
	}
}
Esempio n. 4
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")
	}
}
Esempio n. 5
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)
	}
}
Esempio n. 6
0
// This test stimulates a connection leak as seen in
// https://github.com/getlantern/lantern/issues/2174.
func TestHTTPRedirect(t *testing.T) {
	startProxy(t, false)

	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				return Dial(addr, &Config{
					DialProxy: func(addr string) (net.Conn, error) {
						return net.Dial("tcp", proxyAddr)
					},
					NewRequest: newRequest,
				})
			},
			DisableKeepAlives: true,
		},
	}

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

	resp, err := client.Head("http://www.facebook.com")
	if assert.NoError(t, err, "Head request to facebook should have succeeded") {
		resp.Body.Close()
	}

	assert.NoError(t, counter.AssertDelta(2), "All file descriptors except the connection from proxy to destination site should have been closed")
}
Esempio n. 7
0
func TestAuth(t *testing.T) {
	log.Debugf("TestGET")
	reqTemplate := "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n"
	resp := "HTTP/1.1 404 Not Found\r\n"
	content := "holla!\n"
	defer stopMockServers()
	site, _ := newMockServer(content)
	u, _ := url.Parse(site)
	log.Debugf("Started target site at %s", u)

	addr, s := startServer(t)
	s.Checker = func(req *http.Request) error {
		return errors.New("dsafda")
	}
	log.Debugf("Started proxy server at %s", addr)

	con, err := net.Dial("tcp", addr.String())
	if !assert.NoError(t, err, "should dial proxy server") {
		return
	}
	defer func() {
		assert.NoError(t, con.Close(), "should close connection")
	}()

	req := fmt.Sprintf(reqTemplate, u, u.Host)
	_, err = con.Write([]byte(req))
	if !assert.NoError(t, err, "should write request") {
		return
	}

	var buf [400]byte
	_, err = con.Read(buf[:])
	assert.Contains(t, string(buf[:]), resp, "should get 404 Not Found")
}
Esempio n. 8
0
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")
}
Esempio n. 9
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()
}
Esempio n. 10
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()))
}
Esempio n. 11
0
func TestEnsureRegistered(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	u := getUtil()
	// Test with no existing record
	name, ip := "cfl-test-entry", "127.0.0.1"
	rec, proxying, err := u.EnsureRegistered(name, ip, nil)
	if assert.NoError(t, err, "Should be able to register with no record") {
		assert.NotNil(t, rec, "A new record should have been returned")
		assert.True(t, proxying, "Proxying (orange cloud) should be on")
	}

	// Test with existing record, but not passing it in
	rec, proxying, err = u.EnsureRegistered(name, ip, nil)
	if assert.NoError(t, err, "Should be able to register with unspecified existing record") {
		assert.NotNil(t, rec, "Existing record should have been returned")
		assert.True(t, proxying, "Proxying (orange cloud) should be on")

		// Test with existing record, passing it in
		rec, proxying, err = u.EnsureRegistered(name, ip, rec)
		if assert.NoError(t, err, "Should be able to register with specified existing record") {
			assert.NotNil(t, rec, "Existing record should have been returned")
			assert.True(t, proxying, "Proxying (orange cloud) should be on")
		}
	}

	if rec != nil {
		err := u.DestroyRecord(rec)
		assert.NoError(t, err, "Should be able to destroy record")
	}

	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Esempio n. 12
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")
}
Esempio n. 13
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")
}
Esempio n. 14
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")
}
Esempio n. 15
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")
}
Esempio n. 16
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")
	}
}
Esempio n. 17
0
func TestList(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	dists, err := ListDistributions(cfr)
	if assert.NoError(t, err, "Should be able to get all distributions") {
		for _, d := range dists {
			log.Tracef("%v : %v (%v)", d.InstanceId, d.Domain, d.Status)
		}
		assert.True(t, len(dists) > 0, "There should be some distributions")
	}
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Esempio n. 18
0
func TestAll(t *testing.T) {
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	u := getUtil()
	recs, err := u.GetAllRecords()
	if assert.NoError(t, err, "Should be able to get all records") {
		for _, r := range recs {
			log.Tracef("%v : %v", r.Name, r.Content)
		}
		assert.True(t, len(recs) > 0, "There should be some records")
	}

	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}
Esempio n. 19
0
func TestIdleClientConnections(t *testing.T) {
	limitedServer, err := setupNewHTTPServer(0, 100*time.Millisecond)
	if err != nil {
		assert.Fail(t, "Error starting proxy server")
	}

	okFn := func(conn net.Conn, proxy *server.Server, originURL *url.URL) {
		time.Sleep(time.Millisecond * 90)
		conn.Write([]byte("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n"))

		var buf [400]byte
		_, err := conn.Read(buf[:])

		assert.NoError(t, err)
	}

	idleFn := func(conn net.Conn, proxy *server.Server, originURL *url.URL) {
		time.Sleep(time.Millisecond * 110)
		conn.Write([]byte("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n"))

		var buf [400]byte
		_, err := conn.Read(buf[:])

		assert.Error(t, err)
	}

	go testRoundTrip(t, limitedServer, httpOriginServer, okFn)
	testRoundTrip(t, limitedServer, httpOriginServer, idleFn)
}
Esempio n. 20
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")
}
Esempio n. 21
0
func doTestTLS(buffered bool, t *testing.T) {
	startServers(t, false)

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

	conn, err := prepareConn(httpsAddr, buffered, false, t, nil)
	if err != nil {
		t.Fatalf("Unable to prepareConn: %s", err)
	}

	tlsConn := tls.Client(conn, &tls.Config{
		ServerName: "localhost",
		RootCAs:    cert.PoolContainingCert(),
	})
	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()
		}
	}()

	err = tlsConn.Handshake()
	if err != nil {
		t.Fatalf("Unable to handshake: %s", err)
	}

	doRequests(tlsConn, t)

	assert.True(t, destsSent[httpsAddr], "https address wasn't recorded as sent destination")
	assert.True(t, destsReceived[httpsAddr], "https address wasn't recorded as received destination")
}
Esempio n. 22
0
func TestWaitUntilNoneMatchOK(t *testing.T) {
	conn, err := net.Dial("tcp", "www.google.com:80")
	if err != nil {
		t.Fatalf("Unable to dial google: %v", err)
	}
	defer func() {
		if err := conn.Close(); err != nil {
			fmt.Println("Unable to close connection: %v", err)
		}
	}()

	wait := 250 * time.Millisecond
	start := time.Now()
	go func() {
		time.Sleep(wait)
		if err := conn.Close(); err != nil {
			t.Fatalf("Unable to close connection: %v", err)
		}
	}()

	err = WaitUntilNoneMatch("TCP", wait*2)
	elapsed := time.Now().Sub(start)
	assert.NoError(t, err, "Waiting should have succeeded")
	assert.True(t, elapsed >= wait, "Should have waited a while")
}
Esempio n. 23
0
func TestBadMethodToServer(t *testing.T) {
	l := startServer(t)
	resp, err := http.Get("http://" + l.Addr().String() + "/")
	assert.NoError(t, err, "Making a Get request to the server should not have errored")
	if err == nil {
		assert.True(t, resp.StatusCode == 405, "Response should have indicated a bad method")
	}
}
Esempio n. 24
0
func closeAndCountFDs(t *testing.T, conn *tls.Conn, err error, fdc *fdcount.Counter) {
	if err == nil {
		if err := conn.Close(); err != nil {
			t.Fatalf("Unable to close connection: %v", err)
		}
	}
	assert.NoError(t, fdc.AssertDelta(0), "Number of open TCP files should be the same after test as before")
}
Esempio n. 25
0
func TestReadFailure(t *testing.T) {
	id1 := Random()
	b := make([]byte, EncodedLength)
	err := id1.Write(b)
	assert.NoError(t, err, "Unable to write")
	_, err = Read(b[:EncodedLength-1])
	assert.Error(t, err, "Read should have failed")
}
Esempio n. 26
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)))
	}
}
Esempio n. 27
0
func TestOKWithInsecureSkipVerify(t *testing.T) {
	fdStart := countTCPFiles()
	conn, err := Dial("tcp", ADDR, false, &tls.Config{
		InsecureSkipVerify: true,
	})
	assert.NoError(t, err, "Unable to dial")
	<-receivedServerNames
	closeAndCountFDs(t, conn, err, fdStart)
}
Esempio n. 28
0
func TestReadFromMemory(t *testing.T) {
	fromMemory := func(path string) ([]byte, error) {
		switch path {
		case "en_US.json":
			return []byte(`{"HELLO": "Hello %s!"}`), nil
		case "zh_CN.json":
			return []byte(`{"ONLY_IN_ZH": "I speak Chinese!"}`), nil
		}
		return nil, nil
	}
	SetMessagesFunc(fromMemory)
	if assert.NoError(t, SetLocale("en_US"), "should load en_US from memory") {
		assertTranslation(t, "", "ONLY_IN_ZH")
	}
	if assert.NoError(t, SetLocale("zh_CN"), "should load zh_CN from memory") {
		assertTranslation(t, "I speak Chinese!", "ONLY_IN_ZH")
	}
}
Esempio n. 29
0
func TestSuccess(t *testing.T) {
	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatalf("Unable to listen: %s", err)
	}
	defer l.Close()
	err = WaitForServer("tcp", l.Addr().String(), 100*time.Millisecond)
	assert.NoError(t, err, "Server should have been found")
}
Esempio n. 30
0
func TestList(t *testing.T) {
	if true {
		t.Log("We don't currently use peerscanner, so this test is disabled")
		return
	}
	_, counter, err := fdcount.Matching("TCP")
	if err != nil {
		t.Fatalf("Unable to get starting fdcount: %v", err)
	}
	cfr := getCfr()
	dists, err := ListDistributions(cfr)
	if assert.NoError(t, err, "Should be able to get all distributions") {
		for _, d := range dists {
			log.Tracef("%v : %v (%v)\t\t%v", d.InstanceId, d.Domain, d.Status, d.Comment)
		}
		assert.True(t, len(dists) > 0, "There should be some distributions")
	}
	assert.NoError(t, counter.AssertDelta(0), "All file descriptors should have been closed")
}