summary refs log tree commit diff stats
path: root/tests/stdlib/thttpclient_standalone.nim
blob: 5fa1ea41a5a689ba3fba39e05c721a26b9a00401 (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
discard """
  cmd: "nim c --threads:on $file"
"""

import asynchttpserver, httpclient, asyncdispatch, strutils

block: # bug #16436
  proc startServer() {.async.} =
    proc cb(req: Request) {.async.} =
      let headers = { "Content-length": "15"} # Provide invalid content-length
      await req.respond(Http200, "Hello World", headers.newHttpHeaders())

    var server = newAsyncHttpServer()
    await server.serve(Port(5555), cb)

  proc runClient() {.async.} =
    let c = newAsyncHttpClient(headers = {"Connection": "close"}.newHttpHeaders)
    let r = await c.getContent("http://127.0.0.1:5555")
    doAssert false, "should fail earlier"

  asyncCheck startServer()
  doAssertRaises(ProtocolError):
    waitFor runClient()

block: # bug #14794 (And test for presence of content-length header when using postContent)
  proc startServer() {.async.} =
    var killServer = false
    proc cb(req: Request) {.async.} =
      doAssert(req.body.endsWith(httpNewLine), "Multipart body does not end with a newline.")
      # this next line is probably not required because asynchttpserver does not call
      # the callback when there is no content-length header.  It instead errors with 
      # Error: unhandled exception: 411 Length Required
      # Added for good measure in case the server becomes more permissive.
      doAssert(req.headers.hasKey("content-length"), "Content-Length header is not present.")
      killServer = true
      asyncCheck req.respond(Http200, "OK")

    var server = newAsyncHttpServer()
    server.listen(Port(5556))
    while not killServer:
      if server.shouldAcceptRequest():
        await server.acceptRequest(cb)
      else:
        poll()

  proc runClient() {.async.} =
    let c = newAsyncHttpClient()
    var data = newMultipartData()
    data.add("file.txt", "This is intended to be an example text file.\r\nThis would be the second line.\r\n")
    let r = await c.postContent("http://127.0.0.1:5556", multipart = data)
    c.close()

  asyncCheck startServer()
  waitFor runClient()