summary refs log tree commit diff stats
path: root/tests/async/tasynceverror.nim
blob: 22b4fe9a703e502d70fa2c0000944b60da3e5c34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
discard """
  file: "tasynceverror.nim"
  exitcode: 1
  outputsub: "Error: unhandled exception: Connection reset by peer"
"""

import
    asyncdispatch,
    asyncnet,
    nativesockets,
    os


const
    testHost = "127.0.0.1"
    testPort = Port(17357)


when defined(windows) or defined(nimdoc):
    # TODO: just make it work on Windows for now.
    quit("Error: unhandled exception: Connection reset by peer")
else:
    proc createListenSocket(host: string, port: Port): TAsyncFD =
        result = newAsyncNativeSocket()

        SocketHandle(result).setSockOptInt(SOL_SOCKET, SO_REUSEADDR, 1)

        var aiList = getAddrInfo(host, port, AF_INET)
        if SocketHandle(result).bindAddr(aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32:
          dealloc(aiList)
          raiseOSError(osLastError())
        dealloc(aiList)

        if SocketHandle(result).listen(1) < 0'i32:
            raiseOSError(osLastError())


    proc testAsyncSend() {.async.} =
        var
            ls = createListenSocket(testHost, testPort)
            s = newAsyncSocket()

        await s.connect(testHost, testPort)

        var ps = await ls.accept()
        SocketHandle(ls).close()

        await ps.send("test 1", flags={})
        s.close()
        # This send should raise EPIPE
        await ps.send("test 2", flags={})
        SocketHandle(ps).close()


    # The bug was, when the poll function handled EvError for us,
    # our callbacks may never get executed, thus making the event
    # loop block indefinitely. This is a timer to keep everything
    # rolling. 400 ms is an arbitrary value, should be enough though.
    proc timer() {.async.} =
        await sleepAsync(400)
        echo("Timer expired.")
        quit(2)


    asyncCheck(testAsyncSend())
    waitFor(timer())