Exemple #1
0
func TestDo(t *testing.T) {
	ncall = 0
	once.Do(call)
	if ncall != 1 {
		t.Fatalf("once.Do(call) didn't call(): ncall=%d", ncall)
	}
	once.Do(call)
	if ncall != 1 {
		t.Fatalf("second once.Do(call) did call(): ncall=%d", ncall)
	}
	once.Do(call)
	if ncall != 1 {
		t.Fatalf("third once.Do(call) did call(): ncall=%d", ncall)
	}
}
Exemple #2
0
func TestStatShouldHaveStat(t *testing.T) {
	var ch = make(chan Result)

	once.Do(startServer)
	wsClients := &WSBench{Connections: 3, Ch: ch}
	wsClients.Run()
	fmt.Printf("B: %v ", wsClients.results)
	fmt.Printf("C: %v ", wsClients.Stats)
	if wsClients.Stats["sum"] <= 0 {
		t.Errorf("Stats should have sum", wsClients.Stats["sum"], 0)
	}

	if wsClients.Stats["count"] <= 0 {
		t.Errorf("Stats should have count", wsClients.Stats["count"], 0)
	}

	if wsClients.Stats["avg"] <= 0 {
		t.Errorf("Stats should have avg", wsClients.Stats["avg"], 0)
	}

	if wsClients.Stats["max"] <= 0 {
		t.Errorf("Stats should have max", wsClients.Stats["max"], 0)
	}

	if wsClients.Stats["min"] <= 0 {
		t.Errorf("Stats should have min", wsClients.Stats["min"], 0)
	}

}
Exemple #3
0
func newFD(fd, family, proto int, net string, laddr, raddr Addr) (f *netFD, err os.Error) {
	once.Do(startServer)
	if e := syscall.SetNonblock(fd, true); e != 0 {
		return nil, &OpError{"setnonblock", net, laddr, os.Errno(e)}
	}
	f = &netFD{
		sysfd:  fd,
		family: family,
		proto:  proto,
		net:    net,
		laddr:  laddr,
		raddr:  raddr,
	}
	var ls, rs string
	if laddr != nil {
		ls = laddr.String()
	}
	if raddr != nil {
		rs = raddr.String()
	}
	f.sysfile = os.NewFile(fd, net+":"+ls+"->"+rs)
	f.cr = make(chan bool, 1)
	f.cw = make(chan bool, 1)
	return f, nil
}
func TestEchoDraft75(t *testing.T) {
	once.Do(startServer)

	// websocket.Dial()
	client, err := net.Dial("tcp", "", serverAddr)
	if err != nil {
		t.Fatal("dialing", err)
	}
	ws, err := newClient("/echoDraft75", "localhost", "http://localhost",
		"ws://localhost/echoDraft75", "", client, draft75handshake)
	if err != nil {
		t.Errorf("WebSocket handshake: %v", err)
		return
	}

	msg := []byte("hello, world\n")
	if _, err := ws.Write(msg); err != nil {
		t.Errorf("Write: error %v", err)
	}
	var actual_msg = make([]byte, 512)
	n, err := ws.Read(actual_msg)
	if err != nil {
		t.Errorf("Read: error %v", err)
	}
	actual_msg = actual_msg[0:n]
	if !bytes.Equal(msg, actual_msg) {
		t.Errorf("Echo: expected %q got %q", msg, actual_msg)
	}
	ws.Close()
}
func Prime(number int64) bool {
	once.Do(inits)
	if number == 2 {
		return true
	}
	l := int64(len(primes))
	i := int64(0)
	for ; i < l && primes[i] < number; i++ {
		if number%primes[i] == 0 {
			return false
		}
	}
	i = primes[i-1] + 1
	if i%2 == 0 {
		i--
	}
	for ; i < number; i += 2 {
		if number%i == 0 {
			return false
		}
	}
	l = int64(len(primes))
	if number > primes[l-1] && l < 10000 {
		primes = primes[0 : l+1]
		primes[l] = number
	}
	return true
}
Exemple #6
0
// LookupHost looks for name using the local hosts file and DNS resolver.
// It returns the canonical name for the host and an array of that
// host's addresses.
func LookupHost(name string) (cname string, addrs []string, err os.Error) {
	if !isDomainName(name) {
		return name, nil, &DNSError{"invalid domain name", name, ""}
	}
	once.Do(loadConfig)
	if dnserr != nil || cfg == nil {
		err = dnserr
		return
	}
	// Use entries from /etc/hosts if they match.
	addrs = lookupStaticHost(name)
	if len(addrs) > 0 {
		cname = name
		return
	}
	// If name is rooted (trailing dot) or has enough dots,
	// try it by itself first.
	rooted := len(name) > 0 && name[len(name)-1] == '.'
	if rooted || count(name, '.') >= cfg.ndots {
		rname := name
		if !rooted {
			rname += "."
		}
		// Can try as ordinary name.
		addrs, err = tryOneName(cfg, rname)
		if err == nil {
			cname = rname
			return
		}
	}
	if rooted {
		return
	}

	// Otherwise, try suffixes.
	for i := 0; i < len(cfg.search); i++ {
		rname := name + "." + cfg.search[i]
		if rname[len(rname)-1] != '.' {
			rname += "."
		}
		addrs, err = tryOneName(cfg, rname)
		if err == nil {
			cname = rname
			return
		}
	}

	// Last ditch effort: try unsuffixed.
	rname := name
	if !rooted {
		rname += "."
	}
	addrs, err = tryOneName(cfg, rname)
	if err == nil {
		cname = rname
		return
	}
	return
}
Exemple #7
0
// Setenv sets the value of the environment variable named by the key.
// It returns an Error, if any.
func Setenv(key, value string) Error {
	once.Do(copyenv)

	if len(key) == 0 {
		return EINVAL
	}
	env[key] = value
	return nil
}
Exemple #8
0
func createTempDir() string {
	once.Do(seedRand)
	result := fmt.Sprintf("/tmp/files_test.%d", rand.Uint32())
	err := os.Mkdir(result, 0700)
	if err != nil {
		panic(fmt.Sprintf("Can't create dir [%s]: %s", result, err))
	}

	return result
}
Exemple #9
0
// NewTicker returns a new Ticker containing a channel that will
// send the time, in nanoseconds, every ns nanoseconds.  It adjusts the
// intervals to make up for pauses in delivery of the ticks.
func NewTicker(ns int64) *Ticker {
	if ns <= 0 {
		return nil
	}
	c := make(chan int64, 1) //  See comment on send in tickerLoop
	t := &Ticker{c, c, ns, false, Nanoseconds() + ns, nil}
	once.Do(startTickerLoop)
	// must be run in background so global Tickers can be created
	go func() { newTicker <- t }()
	return t
}
Exemple #10
0
func TestRunCreatesMultipleConnections(t *testing.T) {
	var ch = make(chan Result)

	once.Do(startServer)
	wsClients := &WSBench{Connections: 2, Ch: ch}
	wsClients.Run()
	fmt.Printf("A: %v ", wsClients.results)
	if len(wsClients.results) != 2 {
		t.Errorf("Running WSBench w 2 connections should return 2 results ", wsClients.results, 2)
	}
}
Exemple #11
0
func TestSetClientConnections(t *testing.T) {
	once.Do(startServer)
	wsClients := &WSBench{Connections: 2, target: "ws://0.0.0.0:5555/echo"}
	if wsClients.Connections != 2 {
		t.Errorf("Setting connections ", wsClients.Connections, 2)
	}
	if wsClients.target != "ws://0.0.0.0:5555/echo" {
		t.Errorf("Setting target ", wsClients.target, "ws://0.0.0.0:5555/echo")
	}

}
Exemple #12
0
// Getenverror retrieves the value of the environment variable named by the key.
// It returns the value and an error, if any.
func Getenverror(key string) (value string, err Error) {
	once.Do(copyenv)

	if len(key) == 0 {
		return "", EINVAL
	}
	v, ok := env[key]
	if !ok {
		return "", ENOENV
	}
	return v, nil
}
Exemple #13
0
func TestMoreThan30Connections(t *testing.T) {
	var ch = make(chan Result)
	num := 1000000

	once.Do(startServer)
	wsClients := &WSBench{Connections: num, Ch: ch}
	wsClients.Run()
	// fmt.Printf("A: %v ", wsClients.results)
	if len(wsClients.results) < num {
		t.Errorf("Running WSBench w 2 connections should return 30 results ", len(wsClients.results), num)
	}
}
func TestHTTPDraft75(t *testing.T) {
	once.Do(startServer)

	r, _, err := http.Get(fmt.Sprintf("http://%s/echoDraft75", serverAddr))
	if err != nil {
		t.Errorf("Get: error %#v", err)
		return
	}
	if r.StatusCode != http.StatusBadRequest {
		t.Errorf("Get: got status %d", r.StatusCode)
	}
}
Exemple #15
0
func TestRPC(t *testing.T) {
	once.Do(startServer)

	client, err := Dial("tcp", serverAddr)
	if err != nil {
		t.Fatal("dialing", err)
	}

	// Synchronous calls
	args := &Args{7, 8}
	reply := new(Reply)
	err = client.Call("Arith.Add", args, reply)
	if reply.C != args.A+args.B {
		t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
	}

	args = &Args{7, 8}
	reply = new(Reply)
	err = client.Call("Arith.Mul", args, reply)
	if reply.C != args.A*args.B {
		t.Errorf("Mul: expected %d got %d", reply.C, args.A*args.B)
	}

	// Out of order.
	args = &Args{7, 8}
	mulReply := new(Reply)
	mulCall := client.Go("Arith.Mul", args, mulReply, nil)
	addReply := new(Reply)
	addCall := client.Go("Arith.Add", args, addReply, nil)

	<-addCall.Done
	if addReply.C != args.A+args.B {
		t.Errorf("Add: expected %d got %d", addReply.C, args.A+args.B)
	}

	<-mulCall.Done
	if mulReply.C != args.A*args.B {
		t.Errorf("Mul: expected %d got %d", mulReply.C, args.A*args.B)
	}

	// Error test
	args = &Args{7, 0}
	reply = new(Reply)
	err = client.Call("Arith.Div", args, reply)
	// expect an error: zero divide
	if err == nil {
		t.Error("Div: expected error")
	} else if err.String() != "divide by zero" {
		t.Error("Div: expected divide by zero error; got", err)
	}
}
// LookupMX looks for name using the local hosts file and DNS resolver.
// It returns the canonical name for the host and an array of that
// host's addresses.
func LookupMX(name string) (addrs []string, prefs []uint16, err os.Error) {
	if !isDomainName(name) {
		return nil, nil, &DNSError{Error: "invalid domain name", Name: name}
	}
	once.Do(loadConfig)
	if dnserr != nil || cfg == nil {
		err = dnserr
		return
	}

	// If name is rooted (trailing dot) or has enough dots,
	// try it by itself first.
	rooted := len(name) > 0 && name[len(name)-1] == '.'
	if rooted || count(name, '.') >= cfg.ndots {
		rname := name
		if !rooted {
			rname += "."
		}
		// Can try as ordinary name.
		addrs, prefs, err = tryOneName(cfg, rname)
		if err == nil {
			return
		}
	}
	if rooted {
		return
	}

	// Otherwise, try suffixes.
	for i := 0; i < len(cfg.search); i++ {
		rname := name + "." + cfg.search[i]
		if rname[len(rname)-1] != '.' {
			rname += "."
		}
		addrs, prefs, err = tryOneName(cfg, rname)
		if err == nil {
			return
		}
	}

	// Last ditch effort: try unsuffixed.
	rname := name
	if !rooted {
		rname += "."
	}
	addrs, prefs, err = tryOneName(cfg, rname)
	if err == nil {
		return
	}
	return
}
Exemple #17
0
// Environ returns an array of strings representing the environment,
// in the form "key=value".
func Environ() []string {
	once.Do(copyenv)
	a := make([]string, len(env))
	i := 0
	for k, v := range env {
		// check i < len(a) for safety,
		// in case env is changing underfoot.
		if i < len(a) {
			a[i] = k + "=" + v
			i++
		}
	}
	return a[0:i]
}
func TestWithQuery(t *testing.T) {
	once.Do(startServer)

	client, err := net.Dial("tcp", "", serverAddr)
	if err != nil {
		t.Fatal("dialing", err)
	}

	ws, err := newClient("/echo?q=v", "localhost", "http://localhost",
		"ws://localhost/echo?q=v", "", client, handshake)
	if err != nil {
		t.Errorf("WebSocket handshake: %v", err)
		return
	}
	ws.Close()
}
Exemple #19
0
func TestHTTPRPC(t *testing.T) {
	once.Do(startServer)

	client, err := DialHTTP("tcp", httpServerAddr)
	if err != nil {
		t.Fatal("dialing", err)
	}

	// Synchronous calls
	args := &Args{7, 8}
	reply := new(Reply)
	err = client.Call("Arith.Add", args, reply)
	if reply.C != args.A+args.B {
		t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
	}
}
Exemple #20
0
// LookupPort looks up the port for the given network and service.
func LookupPort(network, service string) (port int, err os.Error) {
	once.Do(readServices)

	switch network {
	case "tcp4", "tcp6":
		network = "tcp"
	case "udp4", "udp6":
		network = "udp"
	}

	if m, ok := services[network]; ok {
		if port, ok = m[service]; ok {
			return
		}
	}
	return 0, &AddrError{"unknown port", network + "/" + service}
}
Exemple #21
0
func TestCheckBadType(t *testing.T) {
	once.Do(startServer)

	conn, err := net.Dial("tcp", "", serverAddr)
	if err != nil {
		t.Fatal("dialing:", err)
	}

	client := NewClient(conn)

	reply := new(Reply)
	err = client.Call("Arith.Add", reply, reply) // args, reply would be the correct thing to use
	if err == nil {
		t.Error("expected error calling Arith.Add with wrong arg type")
	} else if strings.Index(err.String(), "type") < 0 {
		t.Error("expected error about type; got", err)
	}
}
Exemple #22
0
func TestCheckUnknownMethod(t *testing.T) {
	once.Do(startServer)

	conn, err := net.Dial("tcp", "", serverAddr)
	if err != nil {
		t.Fatal("dialing:", err)
	}

	client := NewClient(conn)

	args := &Args{7, 8}
	reply := new(Reply)
	err = client.Call("Arith.Unknown", args, reply)
	if err == nil {
		t.Error("expected error calling unknown service")
	} else if strings.Index(err.String(), "method") < 0 {
		t.Error("expected error about method; got", err)
	}
}
Exemple #23
0
// Look up the correct time zone (daylight savings or not) for the given unix time, in the current location.
func lookupTimezone(sec int64) (zone string, offset int) {
	once.Do(setupZone)
	if len(zones) == 0 {
		return "UTC", 0
	}

	// Binary search for entry with largest time <= sec
	tz := zones
	for len(tz) > 1 {
		m := len(tz) / 2
		if sec < int64(tz[m].time) {
			tz = tz[0:m]
		} else {
			tz = tz[m:]
		}
	}
	z := tz[0].zone
	return z.name, z.utcoff
}
func TestHTTP(t *testing.T) {
	once.Do(startServer)

	// If the client did not send a handshake that matches the protocol
	// specification, the server should abort the WebSocket connection.
	_, _, err := http.Get(fmt.Sprintf("http://%s/echo", serverAddr))
	if err == nil {
		t.Errorf("Get: unexpected success")
		return
	}
	urlerr, ok := err.(*http.URLError)
	if !ok {
		t.Errorf("Get: not URLError %#v", err)
		return
	}
	if urlerr.Error != io.ErrUnexpectedEOF {
		t.Errorf("Get: error %#v", err)
		return
	}
}
Exemple #25
0
func TestEcho(t *testing.T) {
	once.Do(startServer)
	msg := []byte("hello, world!")
	ws, err := websocket.Dial("ws://0.0.0.0:5555/echo", "", "http://0.0.0.0/")
	if err != nil {
		t.Errorf("WebSocket handshake: %v", err)
	}
	if _, err := ws.Write([]byte(msg)); err != nil {
		t.Errorf("Write: error %v", err)
	}
	var response = make([]byte, 512)
	fmt.Println(bytes.Equal(response, response))
	n, err := ws.Read(response)

	if err != nil {
		t.Errorf("Read: error %v", err)
	}

	if !bytes.Equal(msg, response[0:n]) {
		t.Errorf("Echo: expected %q got %q", msg, response)
	}
	ws.Close()
}
Exemple #26
0
// TypeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, TypeByExtension returns "".
func TypeByExtension(ext string) string {
	once.Do(initMime)
	return mimeTypes[ext]
}
Exemple #27
0
func defaultConfig() *Config {
	once.Do(initDefaultConfig)
	return varDefaultConfig
}
Exemple #28
0
// Clearenv deletes all environment variables.
func Clearenv() {
	once.Do(copyenv) // prevent copyenv in Getenv/Setenv
	env = make(map[string]string)
}
Exemple #29
0
// Parse parses a formatted string and returns the time value it represents.
// The layout defines the format by showing the representation of a standard
// time, which is then used to describe the string to be parsed.  Predefined
// layouts ANSIC, UnixDate, ISO8601 and others describe standard
// representations.
//
// Only those elements present in the value will be set in the returned time
// structure.  Also, if the input string represents an inconsistent time
// (such as having the wrong day of the week), the returned value will also
// be inconsistent.  In any case, the elements of the returned time will be
// sane: hours in 0..23, minutes in 0..59, day of month in 0..31, etc.
func Parse(alayout, avalue string) (*Time, os.Error) {
	var t Time
	const formatErr = ": different format from "
	rangeErrString := "" // set if a value is out of range
	pmSet := false       // do we need to add 12 to the hour?
	// Each iteration steps along one piece
	layout, value := alayout, avalue
	sign := "" // pending + or - from previous iteration
	for len(layout) > 0 && len(value) > 0 {
		c := layout[0]
		pieceType := charType(c)
		var i int
		for i = 0; i < len(layout) && charType(layout[i]) == pieceType; i++ {
		}
		reference := layout[0:i]
		prevLayout := layout
		layout = layout[i:]
		// Ugly time zone handling.
		if reference == "Z" {
			// Special case for ISO8601 time zone: "Z" or "-0800"
			if value[0] == 'Z' {
				i = 1
			} else if len(value) >= 5 {
				i = 5
			} else {
				return nil, &ParseError{Layout: alayout, Value: avalue, Message: formatErr + alayout}
			}
		} else {
			c = value[0]
			if charType(c) != pieceType {
				// Ugly management of signs.  Reference and data might differ.
				// 1. Could be a minus sign introducing a negative year.
				if c == '-' && pieceType != minus {
					value = value[1:]
					layout = prevLayout // don't consume reference item
					sign = "-"
					continue
				}
				// 2. Could be a plus sign for a +0100 time zone, represented by -0700 in the standard.
				if c == '+' && pieceType == minus {
					value = value[1:]
					layout = prevLayout[1:] // absorb sign in both value and layout
					sign = "+"
					continue
				}
				return nil, &ParseError{Layout: alayout, Value: avalue, Message: formatErr + alayout}
			}
			for i = 0; i < len(value) && charType(value[i]) == pieceType; i++ {
			}
		}
		p := value[0:i]
		value = value[i:]
		switch pieceType {
		case separator:
			// Separators must match but initial run of spaces is treated as a single space.
			if collapseSpaces(p) != collapseSpaces(reference) {
				return nil, &ParseError{Layout: alayout, Value: avalue, Message: formatErr + alayout}
			}
			continue
		case plus, minus:
			if len(p) == 1 { // ++ or -- don't count as signs.
				sign = p
				continue
			}
		}
		var err os.Error
		switch reference {
		case stdYear:
			t.Year, err = strconv.Atoi64(p)
			if t.Year >= 69 { // Unix time starts Dec 31 1969 in some time zones
				t.Year += 1900
			} else {
				t.Year += 2000
			}
		case stdLongYear:
			t.Year, err = strconv.Atoi64(p)
			if sign == "-" {
				t.Year = -t.Year
			}
		case stdMonth:
			t.Month, err = lookup(shortMonthNames, p)
		case stdLongMonth:
			t.Month, err = lookup(longMonthNames, p)
		case stdNumMonth, stdZeroMonth:
			t.Month, err = strconv.Atoi(p)
			if t.Month <= 0 || 12 < t.Month {
				rangeErrString = "month"
			}
		case stdWeekDay:
			t.Weekday, err = lookup(shortDayNames, p)
		case stdLongWeekDay:
			t.Weekday, err = lookup(longDayNames, p)
		case stdDay, stdUnderDay, stdZeroDay:
			t.Day, err = strconv.Atoi(p)
			if t.Day < 0 || 31 < t.Day {
				// TODO: be more thorough in date check?
				rangeErrString = "day"
			}
		case stdHour:
			t.Hour, err = strconv.Atoi(p)
			if t.Hour < 0 || 24 <= t.Hour {
				rangeErrString = "hour"
			}
		case stdHour12, stdZeroHour12:
			t.Hour, err = strconv.Atoi(p)
			if t.Hour < 0 || 12 < t.Hour {
				rangeErrString = "hour"
			}
		case stdMinute, stdZeroMinute:
			t.Minute, err = strconv.Atoi(p)
			if t.Minute < 0 || 60 <= t.Minute {
				rangeErrString = "minute"
			}
		case stdSecond, stdZeroSecond:
			t.Second, err = strconv.Atoi(p)
			if t.Second < 0 || 60 <= t.Second {
				rangeErrString = "second"
			}
		case stdZulu:
			if len(p) != 4 {
				err = os.ErrorString("HHMM value must be 4 digits")
				break
			}
			t.Hour, err = strconv.Atoi(p[0:2])
			if err != nil {
				t.Minute, err = strconv.Atoi(p[2:4])
			}
		case stdISO8601TZ, stdNumTZ:
			if reference == stdISO8601TZ {
				if p == "Z" {
					t.Zone = "UTC"
					break
				}
				// len(p) known to be 5: "-0800"
				sign = p[0:1]
				p = p[1:]
			} else {
				// len(p) known to be 4: "0800" and sign is set
			}
			var hr, min int
			hr, err = strconv.Atoi(p[0:2])
			if err != nil {
				min, err = strconv.Atoi(p[2:4])
			}
			t.ZoneOffset = (hr*60 + min) * 60 // offset is in seconds
			switch sign[0] {
			case '+':
			case '-':
				t.ZoneOffset = -t.ZoneOffset
			default:
				err = errBad
			}
		case stdPM:
			if p == "PM" {
				pmSet = true
			} else if p != "AM" {
				err = errBad
			}
		case stdpm:
			if p == "pm" {
				pmSet = true
			} else if p != "am" {
				err = errBad
			}
		case stdTZ:
			// Does it look like a time zone?
			if p == "UTC" {
				t.Zone = p
				break
			}
			// All other time zones look like XXT or XXXT.
			if len(p) != 3 && len(p) != 4 || p[len(p)-1] != 'T' {
				err = errBad
			}
			for i := 0; i < len(p); i++ {
				if p[i] < 'A' || 'Z' < p[i] {
					err = errBad
				}
			}
			if err != nil {
				break
			}
			// It's a valid format.
			t.Zone = p
			// Can we find it in the table?
			once.Do(setupZone)
			for _, z := range zones {
				if p == z.zone.name {
					t.ZoneOffset = z.zone.utcoff
					break
				}
			}
		}
		if rangeErrString != "" {
			return nil, &ParseError{alayout, avalue, reference, p, ": " + rangeErrString + " out of range"}
		}
		if err != nil {
			return nil, &ParseError{alayout, avalue, reference, p, ""}
		}
		sign = ""
	}
	if pmSet && t.Hour < 12 {
		t.Hour += 12
	}
	return &t, nil
}
Exemple #30
0
// TypeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, TypeByExtension returns "".
func TypeByExtension(ext string) string {
	once.Do(initMime)
	typ, _ := mimeTypes[ext]
	return typ
}