|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "net" |
| 7 | + "strconv" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +// Test golang network package integration for tinygo. |
| 12 | +// This test is not exhaustive and only tests the basic functionality of the package. |
| 13 | + |
| 14 | +const ( |
| 15 | + TEST_PORT = 9000 |
| 16 | +) |
| 17 | + |
| 18 | +var ( |
| 19 | + testsPassed uint |
| 20 | + err error |
| 21 | + sendBuf = &bytes.Buffer{} |
| 22 | + recvBuf = &bytes.Buffer{} |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + testDialListenData = []byte("Hello tinygo :)") |
| 27 | +) |
| 28 | + |
| 29 | +func TestDialListen() { |
| 30 | + // listen thread |
| 31 | + go func() { |
| 32 | + ln, err := net.Listen("tcp", ":"+strconv.FormatInt(TEST_PORT, 10)) |
| 33 | + if err != nil { |
| 34 | + fmt.Printf("error listening: %v\n", err) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + conn, err := ln.Accept() |
| 39 | + if err != nil { |
| 40 | + fmt.Printf("error accepting: %v\n", err) |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + recvBuf.Reset() |
| 45 | + _, err = conn.Read(recvBuf.Bytes()) |
| 46 | + if err != nil { |
| 47 | + fmt.Printf("error reading: %v\n", err) |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + // TODO: this is racy |
| 52 | + if recvBuf.String() != string(testDialListenData) { |
| 53 | + fmt.Printf("error: received data does not match sent data: '%s' != '%s'\n", recvBuf.String(), string(testDialListenData)) |
| 54 | + return |
| 55 | + } |
| 56 | + conn.Close() |
| 57 | + |
| 58 | + return |
| 59 | + }() |
| 60 | + |
| 61 | + // hacky way to wait for the listener to start |
| 62 | + time.Sleep(1 * time.Second) |
| 63 | + |
| 64 | + sendBuf.Reset() |
| 65 | + fmt.Fprint(sendBuf, testDialListenData) |
| 66 | + conn, err := net.Dial("tcp4", "127.0.0.1:"+strconv.FormatInt(TEST_PORT, 10)) |
| 67 | + if err != nil { |
| 68 | + fmt.Printf("error dialing: %v\n", err) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + if _, err = conn.Write(sendBuf.Bytes()); err != nil { |
| 73 | + fmt.Printf("error writing: %v\n", err) |
| 74 | + return |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +func main() { |
| 79 | + fmt.Printf("test: net start\n") |
| 80 | + TestDialListen() |
| 81 | + fmt.Printf("test: net end\n") |
| 82 | +} |
0 commit comments