blob: c1ba399424d0f923bf4f96042b359ca51c95df8a [file] [log] [blame]
Russ Cox1e37e8a2009-03-06 17:51:31 -08001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package net
6
7import (
Russ Cox6e788e02009-11-17 08:39:17 -08008 "os";
Russ Cox1e37e8a2009-03-06 17:51:31 -08009 "testing";
10 "time";
Russ Cox1e37e8a2009-03-06 17:51:31 -080011)
12
Russ Cox6e788e02009-11-17 08:39:17 -080013func testTimeout(t *testing.T, network, addr string, readFrom bool) {
Russ Coxb04ac102009-08-12 13:19:17 -070014 fd, err := Dial(network, "", addr);
Russ Cox1e37e8a2009-03-06 17:51:31 -080015 defer fd.Close();
16 if err != nil {
Robert Griesemer40621d52009-11-09 12:07:39 -080017 t.Errorf("dial %s %s failed: %v", network, addr, err)
Russ Cox1e37e8a2009-03-06 17:51:31 -080018 }
19 t0 := time.Nanoseconds();
20 fd.SetReadTimeout(1e8); // 100ms
21 var b [100]byte;
Russ Cox6e788e02009-11-17 08:39:17 -080022 var n int;
23 var err1 os.Error;
24 if readFrom {
25 n, _, err1 = fd.(PacketConn).ReadFrom(&b)
26 } else {
27 n, err1 = fd.Read(&b)
28 }
Russ Cox1e37e8a2009-03-06 17:51:31 -080029 t1 := time.Nanoseconds();
Russ Cox6e788e02009-11-17 08:39:17 -080030 what := "Read";
31 if readFrom {
32 what = "ReadFrom"
33 }
Russ Coxa0bcaf42009-06-25 20:24:55 -070034 if n != 0 || !isEAGAIN(err1) {
Russ Cox6e788e02009-11-17 08:39:17 -080035 t.Errorf("fd.%s on %s %s did not return 0, EAGAIN: %v, %v", what, network, addr, n, err1)
Russ Cox1e37e8a2009-03-06 17:51:31 -080036 }
Robert Griesemer5d377052009-11-04 23:16:46 -080037 if t1-t0 < 0.5e8 || t1-t0 > 1.5e8 {
Russ Cox6e788e02009-11-17 08:39:17 -080038 t.Errorf("fd.%s on %s %s took %f seconds, expected 0.1", what, network, addr, float64(t1-t0)/1e9)
Russ Cox1e37e8a2009-03-06 17:51:31 -080039 }
40}
41
Russ Cox6e788e02009-11-17 08:39:17 -080042func TestTimeoutUDP(t *testing.T) {
43 testTimeout(t, "udp", "127.0.0.1:53", false);
44 testTimeout(t, "udp", "127.0.0.1:53", true);
45}
Russ Cox1e37e8a2009-03-06 17:51:31 -080046
47func TestTimeoutTCP(t *testing.T) {
48 // 74.125.19.99 is www.google.com.
49 // could use dns, but dns depends on
50 // timeouts and this is the timeout test.
Russ Cox6e788e02009-11-17 08:39:17 -080051 testTimeout(t, "tcp", "74.125.19.99:80", false)
Russ Cox1e37e8a2009-03-06 17:51:31 -080052}