1+ app [main!] { pf: platform " ../platform/main.roc" }
2+
3+ import pf.Stdout
4+ import pf.Tcp
5+ import pf.Arg exposing [Arg ]
6+
7+ main ! : List Arg => Result {} _
8+ main ! = |_args |
9+ Stdout . line !("Testing Tcp module functions..." )?
10+ Stdout.line!(" Note : These tests require a TCP server running on localhost:8085 " )?
11+ Stdout.line!(" You can start one with: ncat - e `which cat` - l 8085 " )?
12+ Stdout.line!(" " )?
13+
14+ Stdout.line!(" Testing Tcp . connect !:")?
15+ when Tcp . connect !("127.0.0.1", 8085 ) is
16+ Ok (stream) ->
17+ Stdout . line !("✓ Successfully connected to localhost:8085 " )?
18+ test_tcp_functions!(stream)?
19+ Stdout.line!(" \n✓ All tests executed! ✓" )
20+
21+ Err(connect_err) ->
22+ err_str = Tcp.connect_err_to_str(connect_err)
23+ Err(Exit(1, " ✗ Failed to connect: ${err_str}" ))
24+
25+
26+ test_tcp_functions! : Tcp.Stream => Result {} _
27+ test_tcp_functions! = |stream|
28+
29+ Stdout.line!(" \nTesting Tcp . write !:")?
30+ hello_bytes = [72 , 101 , 108 , 108 , 111 , 10 ] # "Hello\n" in bytes
31+ Tcp . write !(stream , hello_bytes)?
32+
33+ reply_msg = Tcp . read_line !(stream )?
34+ Stdout . line !("Echo server reply: ${reply_msg}" )?
35+
36+
37+ Stdout.line!(" Testing Tcp . write_utf8 !:")?
38+ test_message = " Test message from Roc!\n "
39+ Tcp . write_utf8 !(stream , test_message)?
40+
41+ reply_msg_utf8 = Tcp . read_line !(stream )?
42+ Stdout . line !("Echo server reply: ${reply_msg_utf8}" )?
43+
44+
45+ Stdout.line!(" Testing Tcp . read_up_to !:")?
46+
47+ do_not_read_bytes = [100 , 111 , 32 , 110 , 111 , 116 , 32 , 114 , 101 , 97 , 100 , 32 , 112 , 97 , 115 , 116 , 32 , 109 , 101 , 65 ] # "do not read past meA" in bytes
48+ Tcp . write !(stream , do_not_read_bytes)?
49+
50+ nineteen_bytes = Tcp . read_up_to !(stream , 19 ) ? |err| FailedReadUpTo (err)
51+ nineteen_bytes_as_str = Str . from_utf8 (nineteen_bytes ) ? |err| ReadUpToFromUtf8 (err)
52+
53+ Stdout . line !("Tcp . read_up_to yielded : ' ${nineteen_bytes_as_str}' " )?
54+
55+
56+ Stdout.line!(" \nTesting Tcp . read_exactly !:")?
57+ Tcp . write_utf8 !(stream , " BC" )?
58+
59+ three_bytes = Tcp . read_exactly !(stream , 3 ) ? |err| FailedReadExactly (err)
60+ three_bytes_as_str = Str . from_utf8 (three_bytes ) ? |err| ReadExactlyFromUtf8 (err)
61+
62+ Stdout . line !("Tcp . read_exactly yielded : ' ${three_bytes_as_str}' " )?
63+
64+
65+ Stdout.line!(" \nTesting Tcp . read_until !:")?
66+ Tcp . write_utf8 !(stream , " Line1\n Line2\n " )?
67+
68+ bytes_until = Tcp . read_until !(stream , ' \n ' ) ? |err| FailedReadUntil (err)
69+ bytes_until_as_str = Str . from_utf8 (bytes_until ) ? |err| ReadUntilFromUtf8 (err)
70+
71+ Stdout . line !("Tcp . read_until yielded : ' ${bytes_until_as_str}' " )?
72+
73+ Ok({})
0 commit comments