test.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. # Utility for testing the web server. Test cases:
  17. # Assume the device supports 'n' simultaneous open sockets
  18. #
  19. # HTTP Server Tests
  20. #
  21. # 0. Firmware Settings:
  22. # - Create a dormant thread whose sole job is to call httpd_stop() when instructed
  23. # - Measure the following before httpd_start() is called:
  24. # - current free memory
  25. # - current free sockets
  26. # - Measure the same whenever httpd_stop is called
  27. # - Register maximum possible URI handlers: should be successful
  28. # - Register one more URI handler: should fail
  29. # - Deregister on URI handler: should be successful
  30. # - Register on more URI handler: should succeed
  31. # - Register separate handlers for /hello, /hello/type_html. Also
  32. # ensure that /hello/type_html is registered BEFORE /hello. (tests
  33. # that largest matching URI is picked properly)
  34. # - Create URI handler /adder. Make sure it uses a custom free_ctx
  35. # structure to free it up
  36. # 1. Using Standard Python HTTP Client
  37. # - simple GET on /hello (returns Hello World. Ensures that basic
  38. # firmware tests are complete, or returns error)
  39. # - POST on /hello (should fail)
  40. # - PUT on /hello (should fail)
  41. # - simple POST on /echo (returns whatever the POST data)
  42. # - simple PUT on /echo (returns whatever the PUT data)
  43. # - GET on /echo (should fail)
  44. # - simple GET on /hello/type_html (returns Content type as text/html)
  45. # - simple GET on /hello/status_500 (returns HTTP status 500)
  46. # - simple GET on /false_uri (returns HTTP status 404)
  47. # - largest matching URI handler is picked is already verified because
  48. # of /hello and /hello/type_html tests
  49. #
  50. #
  51. # 2. Session Tests
  52. # - Sessions + Pipelining basics:
  53. # - Create max supported sessions
  54. # - On session i,
  55. # - send 3 back-to-back POST requests with data i on /adder
  56. # - read back 3 responses. They should be i, 2i and 3i
  57. # - Tests that
  58. # - pipelining works
  59. # - per-session context is maintained for all supported
  60. # sessions
  61. # - Close all sessions
  62. #
  63. # - Cleanup leftover data: Tests that the web server properly cleans
  64. # up leftover data
  65. # - Create a session
  66. # - POST on /leftover_data with 52 bytes of data (data includes
  67. # \r\n)(the handler only
  68. # reads first 10 bytes and returns them, leaving the rest of the
  69. # bytes unread)
  70. # - GET on /hello (should return 'Hello World')
  71. # - POST on /false_uri with 52 bytes of data (data includes \r\n)
  72. # (should return HTTP 404)
  73. # - GET on /hello (should return 'Hello World')
  74. #
  75. # - Test HTTPd Asynchronous response
  76. # - Create a session
  77. # - GET on /async_data
  78. # - returns 'Hello World!' as a response
  79. # - the handler schedules an async response, which generates a second
  80. # response 'Hello Double World!'
  81. #
  82. # - Spillover test
  83. # - Create max supported sessions with the web server
  84. # - GET /hello on all the sessions (should return Hello World)
  85. # - Create one more session, this should fail
  86. # - GET /hello on all the sessions (should return Hello World)
  87. #
  88. # - Timeout test
  89. # - Create a session and only Send 'GE' on the same (simulates a
  90. # client that left the network halfway through a request)
  91. # - Wait for recv-wait-timeout
  92. # - Server should automatically close the socket
  93. ############# TODO TESTS #############
  94. # 3. Stress Tests
  95. #
  96. # - httperf
  97. # - Run the following httperf command:
  98. # httperf --server=10.31.130.126 --wsess=8,50,0.5 --rate 8 --burst-length 2
  99. #
  100. # - The above implies that the test suite will open
  101. # - 8 simultaneous connections with the server
  102. # - the rate of opening the sessions will be 8 per sec. So in our
  103. # case, a new connection will be opened every 0.2 seconds for 1 second
  104. # - The burst length 2 indicates that 2 requests will be sent
  105. # simultaneously on the same connection in a single go
  106. # - 0.5 seconds is the time between sending out 2 bursts
  107. # - 50 is the total number of requests that will be sent out
  108. #
  109. # - So in the above example, the test suite will open 8
  110. # connections, each separated by 0.2 seconds. On each connection
  111. # it will send 2 requests in a single burst. The bursts on a
  112. # single connection will be separated by 0.5 seconds. A total of
  113. # 25 bursts (25 x 2 = 50) will be sent out
  114. # 4. Leak Tests
  115. # - Simple Leak test
  116. # - Simple GET on /hello/restart (returns success, stop web server, measures leaks, restarts webserver)
  117. # - Simple GET on /hello/restart_results (returns the leak results)
  118. # - Leak test with open sockets
  119. # - Open 8 sessions
  120. # - Simple GET on /hello/restart (returns success, stop web server,
  121. # measures leaks, restarts webserver)
  122. # - All sockets should get closed
  123. # - Simple GET on /hello/restart_results (returns the leak results)
  124. from __future__ import division
  125. from __future__ import print_function
  126. from future import standard_library
  127. standard_library.install_aliases()
  128. from builtins import str
  129. from builtins import range
  130. from builtins import object
  131. import threading
  132. import socket
  133. import time
  134. import argparse
  135. import http.client
  136. import sys
  137. import string
  138. import random
  139. import Utility
  140. _verbose_ = False
  141. class Session(object):
  142. def __init__(self, addr, port, timeout = 15):
  143. self.client = socket.create_connection((addr, int(port)), timeout = timeout)
  144. self.target = addr
  145. self.status = 0
  146. self.encoding = ''
  147. self.content_type = ''
  148. self.content_len = 0
  149. def send_err_check(self, request, data=None):
  150. rval = True
  151. try:
  152. self.client.sendall(request.encode());
  153. if data:
  154. self.client.sendall(data.encode())
  155. except socket.error as err:
  156. self.client.close()
  157. Utility.console_log("Socket Error in send :", err)
  158. rval = False
  159. return rval
  160. def send_get(self, path, headers=None):
  161. request = "GET " + path + " HTTP/1.1\r\nHost: " + self.target
  162. if headers:
  163. for field, value in headers.items():
  164. request += "\r\n"+field+": "+value
  165. request += "\r\n\r\n"
  166. return self.send_err_check(request)
  167. def send_put(self, path, data, headers=None):
  168. request = "PUT " + path + " HTTP/1.1\r\nHost: " + self.target
  169. if headers:
  170. for field, value in headers.items():
  171. request += "\r\n"+field+": "+value
  172. request += "\r\nContent-Length: " + str(len(data)) +"\r\n\r\n"
  173. return self.send_err_check(request, data)
  174. def send_post(self, path, data, headers=None):
  175. request = "POST " + path + " HTTP/1.1\r\nHost: " + self.target
  176. if headers:
  177. for field, value in headers.items():
  178. request += "\r\n"+field+": "+value
  179. request += "\r\nContent-Length: " + str(len(data)) +"\r\n\r\n"
  180. return self.send_err_check(request, data)
  181. def read_resp_hdrs(self):
  182. try:
  183. state = 'nothing'
  184. resp_read = ''
  185. while True:
  186. char = self.client.recv(1).decode()
  187. if char == '\r' and state == 'nothing':
  188. state = 'first_cr'
  189. elif char == '\n' and state == 'first_cr':
  190. state = 'first_lf'
  191. elif char == '\r' and state == 'first_lf':
  192. state = 'second_cr'
  193. elif char == '\n' and state == 'second_cr':
  194. state = 'second_lf'
  195. else:
  196. state = 'nothing'
  197. resp_read += char
  198. if state == 'second_lf':
  199. break
  200. # Handle first line
  201. line_hdrs = resp_read.splitlines()
  202. line_comp = line_hdrs[0].split()
  203. self.status = line_comp[1]
  204. del line_hdrs[0]
  205. self.encoding = ''
  206. self.content_type = ''
  207. headers = dict()
  208. # Process other headers
  209. for h in range(len(line_hdrs)):
  210. line_comp = line_hdrs[h].split(':')
  211. if line_comp[0] == 'Content-Length':
  212. self.content_len = int(line_comp[1])
  213. if line_comp[0] == 'Content-Type':
  214. self.content_type = line_comp[1].lstrip()
  215. if line_comp[0] == 'Transfer-Encoding':
  216. self.encoding = line_comp[1].lstrip()
  217. if len(line_comp) == 2:
  218. headers[line_comp[0]] = line_comp[1].lstrip()
  219. return headers
  220. except socket.error as err:
  221. self.client.close()
  222. Utility.console_log("Socket Error in recv :", err)
  223. return None
  224. def read_resp_data(self):
  225. try:
  226. read_data = ''
  227. if self.encoding != 'chunked':
  228. while len(read_data) != self.content_len:
  229. read_data += self.client.recv(self.content_len).decode()
  230. else:
  231. chunk_data_buf = ''
  232. while (True):
  233. # Read one character into temp buffer
  234. read_ch = self.client.recv(1)
  235. # Check CRLF
  236. if (read_ch == '\r'):
  237. read_ch = self.client.recv(1).decode()
  238. if (read_ch == '\n'):
  239. # If CRLF decode length of chunk
  240. chunk_len = int(chunk_data_buf, 16)
  241. # Keep adding to contents
  242. self.content_len += chunk_len
  243. rem_len = chunk_len
  244. while (rem_len):
  245. new_data = self.client.recv(rem_len)
  246. read_data += new_data
  247. rem_len -= len(new_data)
  248. chunk_data_buf = ''
  249. # Fetch remaining CRLF
  250. if self.client.recv(2) != "\r\n":
  251. # Error in packet
  252. Utility.console_log("Error in chunked data")
  253. return None
  254. if not chunk_len:
  255. # If last chunk
  256. break
  257. continue
  258. chunk_data_buf += '\r'
  259. # If not CRLF continue appending
  260. # character to chunked data buffer
  261. chunk_data_buf += read_ch
  262. return read_data
  263. except socket.error as err:
  264. self.client.close()
  265. Utility.console_log("Socket Error in recv :", err)
  266. return None
  267. def close(self):
  268. self.client.close()
  269. def test_val(text, expected, received):
  270. if expected != received:
  271. Utility.console_log(" Fail!")
  272. Utility.console_log(" [reason] " + text + ":")
  273. Utility.console_log(" expected: " + str(expected))
  274. Utility.console_log(" received: " + str(received))
  275. return False
  276. return True
  277. class adder_thread (threading.Thread):
  278. def __init__(self, id, dut, port):
  279. threading.Thread.__init__(self)
  280. self.id = id
  281. self.dut = dut
  282. self.depth = 3
  283. self.session = Session(dut, port)
  284. def run(self):
  285. self.response = []
  286. # Pipeline 3 requests
  287. if (_verbose_):
  288. Utility.console_log(" Thread: Using adder start " + str(self.id))
  289. for _ in range(self.depth):
  290. self.session.send_post('/adder', str(self.id))
  291. time.sleep(2)
  292. for _ in range(self.depth):
  293. self.session.read_resp_hdrs()
  294. self.response.append(self.session.read_resp_data())
  295. def adder_result(self):
  296. if len(self.response) != self.depth:
  297. Utility.console_log("Error : missing response packets")
  298. return False
  299. for i in range(len(self.response)):
  300. if not test_val("Thread" + str(self.id) + " response[" + str(i) + "]",
  301. str(self.id * (i + 1)), str(self.response[i])):
  302. return False
  303. return True
  304. def close(self):
  305. self.session.close()
  306. def get_hello(dut, port):
  307. # GET /hello should return 'Hello World!'
  308. Utility.console_log("[test] GET /hello returns 'Hello World!' =>", end=' ')
  309. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  310. conn.request("GET", "/hello")
  311. resp = conn.getresponse()
  312. if not test_val("status_code", 200, resp.status):
  313. conn.close()
  314. return False
  315. if not test_val("data", "Hello World!", resp.read().decode()):
  316. conn.close()
  317. return False
  318. if not test_val("data", "text/html", resp.getheader('Content-Type')):
  319. conn.close()
  320. return False
  321. Utility.console_log("Success")
  322. conn.close()
  323. return True
  324. def put_hello(dut, port):
  325. # PUT /hello returns 405'
  326. Utility.console_log("[test] PUT /hello returns 405' =>", end=' ')
  327. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  328. conn.request("PUT", "/hello", "Hello")
  329. resp = conn.getresponse()
  330. if not test_val("status_code", 405, resp.status):
  331. conn.close()
  332. return False
  333. Utility.console_log("Success")
  334. conn.close()
  335. return True
  336. def post_hello(dut, port):
  337. # POST /hello returns 405'
  338. Utility.console_log("[test] POST /hello returns 404' =>", end=' ')
  339. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  340. conn.request("POST", "/hello", "Hello")
  341. resp = conn.getresponse()
  342. if not test_val("status_code", 405, resp.status):
  343. conn.close()
  344. return False
  345. Utility.console_log("Success")
  346. conn.close()
  347. return True
  348. def post_echo(dut, port):
  349. # POST /echo echoes data'
  350. Utility.console_log("[test] POST /echo echoes data' =>", end=' ')
  351. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  352. conn.request("POST", "/echo", "Hello")
  353. resp = conn.getresponse()
  354. if not test_val("status_code", 200, resp.status):
  355. conn.close()
  356. return False
  357. if not test_val("data", "Hello", resp.read().decode()):
  358. conn.close()
  359. return False
  360. Utility.console_log("Success")
  361. conn.close()
  362. return True
  363. def put_echo(dut, port):
  364. # PUT /echo echoes data'
  365. Utility.console_log("[test] PUT /echo echoes data' =>", end=' ')
  366. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  367. conn.request("PUT", "/echo", "Hello")
  368. resp = conn.getresponse()
  369. if not test_val("status_code", 200, resp.status):
  370. conn.close()
  371. return False
  372. if not test_val("data", "Hello", resp.read().decode()):
  373. conn.close()
  374. return False
  375. Utility.console_log("Success")
  376. conn.close()
  377. return True
  378. def get_echo(dut, port):
  379. # GET /echo returns 404'
  380. Utility.console_log("[test] GET /echo returns 405' =>", end=' ')
  381. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  382. conn.request("GET", "/echo")
  383. resp = conn.getresponse()
  384. if not test_val("status_code", 405, resp.status):
  385. conn.close()
  386. return False
  387. Utility.console_log("Success")
  388. conn.close()
  389. return True
  390. def get_hello_type(dut, port):
  391. # GET /hello/type_html returns text/html as Content-Type'
  392. Utility.console_log("[test] GET /hello/type_html has Content-Type of text/html =>", end=' ')
  393. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  394. conn.request("GET", "/hello/type_html")
  395. resp = conn.getresponse()
  396. if not test_val("status_code", 200, resp.status):
  397. conn.close()
  398. return False
  399. if not test_val("data", "Hello World!", resp.read().decode()):
  400. conn.close()
  401. return False
  402. if not test_val("data", "text/html", resp.getheader('Content-Type')):
  403. conn.close()
  404. return False
  405. Utility.console_log("Success")
  406. conn.close()
  407. return True
  408. def get_hello_status(dut, port):
  409. # GET /hello/status_500 returns status 500'
  410. Utility.console_log("[test] GET /hello/status_500 returns status 500 =>", end=' ')
  411. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  412. conn.request("GET", "/hello/status_500")
  413. resp = conn.getresponse()
  414. if not test_val("status_code", 500, resp.status):
  415. conn.close()
  416. return False
  417. Utility.console_log("Success")
  418. conn.close()
  419. return True
  420. def get_false_uri(dut, port):
  421. # GET /false_uri returns status 404'
  422. Utility.console_log("[test] GET /false_uri returns status 404 =>", end=' ')
  423. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  424. conn.request("GET", "/false_uri")
  425. resp = conn.getresponse()
  426. if not test_val("status_code", 404, resp.status):
  427. conn.close()
  428. return False
  429. Utility.console_log("Success")
  430. conn.close()
  431. return True
  432. def parallel_sessions_adder(dut, port, max_sessions):
  433. # POSTs on /adder in parallel sessions
  434. Utility.console_log("[test] POST {pipelined} on /adder in " + str(max_sessions) + " sessions =>", end=' ')
  435. t = []
  436. # Create all sessions
  437. for i in range(max_sessions):
  438. t.append(adder_thread(i, dut, port))
  439. for i in range(len(t)):
  440. t[i].start()
  441. for i in range(len(t)):
  442. t[i].join()
  443. res = True
  444. for i in range(len(t)):
  445. if not test_val("Thread" + str(i) + " Failed", t[i].adder_result(), True):
  446. res = False
  447. t[i].close()
  448. if (res):
  449. Utility.console_log("Success")
  450. return res
  451. def async_response_test(dut, port):
  452. # Test that an asynchronous work is executed in the HTTPD's context
  453. # This is tested by reading two responses over the same session
  454. Utility.console_log("[test] Test HTTPD Work Queue (Async response) =>", end=' ')
  455. s = Session(dut, port)
  456. s.send_get('/async_data')
  457. s.read_resp_hdrs()
  458. if not test_val("First Response", "Hello World!", s.read_resp_data()):
  459. s.close()
  460. return False
  461. s.read_resp_hdrs()
  462. if not test_val("Second Response", "Hello Double World!", s.read_resp_data()):
  463. s.close()
  464. return False
  465. s.close()
  466. Utility.console_log("Success")
  467. return True
  468. def leftover_data_test(dut, port):
  469. # Leftover data in POST is purged (valid and invalid URIs)
  470. Utility.console_log("[test] Leftover data in POST is purged (valid and invalid URIs) =>", end=' ')
  471. s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  472. s.request("POST", url='/leftover_data', body="abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
  473. resp = s.getresponse()
  474. if not test_val("Partial data", "abcdefghij", resp.read().decode()):
  475. s.close()
  476. return False
  477. s.request("GET", url='/hello')
  478. resp = s.getresponse()
  479. if not test_val("Hello World Data", "Hello World!", resp.read().decode()):
  480. s.close()
  481. return False
  482. s.request("POST", url='/false_uri', body="abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
  483. resp = s.getresponse()
  484. if not test_val("False URI Status", str(404), str(resp.status)):
  485. s.close()
  486. return False
  487. resp.read()
  488. s.request("GET", url='/hello')
  489. resp = s.getresponse()
  490. if not test_val("Hello World Data", "Hello World!", resp.read().decode()):
  491. s.close()
  492. return False
  493. s.close()
  494. Utility.console_log("Success")
  495. return True
  496. def spillover_session(dut, port, max_sess):
  497. # Session max_sess_sessions + 1 is rejected
  498. Utility.console_log("[test] Session max_sess_sessions (" + str(max_sess) + ") + 1 is rejected =>", end=' ')
  499. s = []
  500. _verbose_ = True
  501. for i in range(max_sess + 1):
  502. if (_verbose_):
  503. Utility.console_log("Executing " + str(i))
  504. try:
  505. a = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  506. a.request("GET", url='/hello')
  507. resp = a.getresponse()
  508. if not test_val("Connection " + str(i), "Hello World!", resp.read().decode()):
  509. a.close()
  510. break
  511. s.append(a)
  512. except:
  513. if (_verbose_):
  514. Utility.console_log("Connection " + str(i) + " rejected")
  515. a.close()
  516. break
  517. # Close open connections
  518. for a in s:
  519. a.close()
  520. # Check if number of connections is equal to max_sess
  521. Utility.console_log(["Fail","Success"][len(s) == max_sess])
  522. return (len(s) == max_sess)
  523. def recv_timeout_test(dut, port):
  524. Utility.console_log("[test] Timeout occurs if partial packet sent =>", end=' ')
  525. s = Session(dut, port)
  526. s.client.sendall(b"GE")
  527. s.read_resp_hdrs()
  528. resp = s.read_resp_data()
  529. if not test_val("Request Timeout", "Server closed this connection", resp):
  530. s.close()
  531. return False
  532. s.close()
  533. Utility.console_log("Success")
  534. return True
  535. def packet_size_limit_test(dut, port, test_size):
  536. Utility.console_log("[test] send size limit test =>", end=' ')
  537. retry = 5
  538. while (retry):
  539. retry -= 1
  540. Utility.console_log("data size = ", test_size)
  541. s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  542. random_data = ''.join(string.printable[random.randint(0,len(string.printable))-1] for _ in list(range(test_size)))
  543. path = "/echo"
  544. s.request("POST", url=path, body=random_data)
  545. resp = s.getresponse()
  546. if not test_val("Error", "200", str(resp.status)):
  547. if test_val("Error", "408", str(resp.status)):
  548. Utility.console_log("Data too large to be allocated")
  549. test_size = test_size//10
  550. else:
  551. Utility.console_log("Unexpected error")
  552. s.close()
  553. Utility.console_log("Retry...")
  554. continue
  555. resp = resp.read().decode()
  556. result = (resp == random_data)
  557. if not result:
  558. test_val("Data size", str(len(random_data)), str(len(resp)))
  559. s.close()
  560. Utility.console_log("Retry...")
  561. continue
  562. s.close()
  563. Utility.console_log("Success")
  564. return True
  565. Utility.console_log("Failed")
  566. return False
  567. def code_500_server_error_test(dut, port):
  568. Utility.console_log("[test] 500 Server Error test =>", end=' ')
  569. s = Session(dut, port)
  570. s.client.sendall(b"abcdefgh\0")
  571. s.read_resp_hdrs()
  572. resp = s.read_resp_data()
  573. # Presently server sends back 400 Bad Request
  574. #if not test_val("Server Error", "500", s.status):
  575. #s.close()
  576. #return False
  577. if not test_val("Server Error", "400", s.status):
  578. s.close()
  579. return False
  580. s.close()
  581. Utility.console_log("Success")
  582. return True
  583. def code_501_method_not_impl(dut, port):
  584. Utility.console_log("[test] 501 Method Not Implemented =>", end=' ')
  585. s = Session(dut, port)
  586. path = "/hello"
  587. s.client.sendall(("ABC " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  588. s.read_resp_hdrs()
  589. resp = s.read_resp_data()
  590. # Presently server sends back 400 Bad Request
  591. #if not test_val("Server Error", "501", s.status):
  592. #s.close()
  593. #return False
  594. if not test_val("Server Error", "400", s.status):
  595. s.close()
  596. return False
  597. s.close()
  598. Utility.console_log("Success")
  599. return True
  600. def code_505_version_not_supported(dut, port):
  601. Utility.console_log("[test] 505 Version Not Supported =>", end=' ')
  602. s = Session(dut, port)
  603. path = "/hello"
  604. s.client.sendall(("GET " + path + " HTTP/2.0\r\nHost: " + dut + "\r\n\r\n").encode())
  605. s.read_resp_hdrs()
  606. resp = s.read_resp_data()
  607. if not test_val("Server Error", "505", s.status):
  608. s.close()
  609. return False
  610. s.close()
  611. Utility.console_log("Success")
  612. return True
  613. def code_400_bad_request(dut, port):
  614. Utility.console_log("[test] 400 Bad Request =>", end=' ')
  615. s = Session(dut, port)
  616. path = "/hello"
  617. s.client.sendall(("XYZ " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  618. s.read_resp_hdrs()
  619. resp = s.read_resp_data()
  620. if not test_val("Client Error", "400", s.status):
  621. s.close()
  622. return False
  623. s.close()
  624. Utility.console_log("Success")
  625. return True
  626. def code_404_not_found(dut, port):
  627. Utility.console_log("[test] 404 Not Found =>", end=' ')
  628. s = Session(dut, port)
  629. path = "/dummy"
  630. s.client.sendall(("GET " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  631. s.read_resp_hdrs()
  632. resp = s.read_resp_data()
  633. if not test_val("Client Error", "404", s.status):
  634. s.close()
  635. return False
  636. s.close()
  637. Utility.console_log("Success")
  638. return True
  639. def code_405_method_not_allowed(dut, port):
  640. Utility.console_log("[test] 405 Method Not Allowed =>", end=' ')
  641. s = Session(dut, port)
  642. path = "/hello"
  643. s.client.sendall(("POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  644. s.read_resp_hdrs()
  645. resp = s.read_resp_data()
  646. if not test_val("Client Error", "405", s.status):
  647. s.close()
  648. return False
  649. s.close()
  650. Utility.console_log("Success")
  651. return True
  652. def code_408_req_timeout(dut, port):
  653. Utility.console_log("[test] 408 Request Timeout =>", end=' ')
  654. s = Session(dut, port)
  655. s.client.sendall(("POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 10\r\n\r\nABCD").encode())
  656. s.read_resp_hdrs()
  657. resp = s.read_resp_data()
  658. if not test_val("Client Error", "408", s.status):
  659. s.close()
  660. return False
  661. s.close()
  662. Utility.console_log("Success")
  663. return True
  664. def code_411_length_required(dut, port):
  665. Utility.console_log("[test] 411 Length Required =>", end=' ')
  666. s = Session(dut, port)
  667. path = "/echo"
  668. s.client.sendall(("POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n").encode())
  669. s.read_resp_hdrs()
  670. resp = s.read_resp_data()
  671. # Presently server sends back 400 Bad Request
  672. #if not test_val("Client Error", "411", s.status):
  673. #s.close()
  674. #return False
  675. if not test_val("Client Error", "400", s.status):
  676. s.close()
  677. return False
  678. s.close()
  679. Utility.console_log("Success")
  680. return True
  681. def send_getx_uri_len(dut, port, length):
  682. s = Session(dut, port)
  683. method = "GET "
  684. version = " HTTP/1.1\r\n"
  685. path = "/"+"x"*(length - len(method) - len(version) - len("/"))
  686. s.client.sendall(method.encode())
  687. time.sleep(1)
  688. s.client.sendall(path.encode())
  689. time.sleep(1)
  690. s.client.sendall((version + "Host: " + dut + "\r\n\r\n").encode())
  691. s.read_resp_hdrs()
  692. resp = s.read_resp_data()
  693. s.close()
  694. return s.status
  695. def code_414_uri_too_long(dut, port, max_uri_len):
  696. Utility.console_log("[test] 414 URI Too Long =>", end=' ')
  697. status = send_getx_uri_len(dut, port, max_uri_len)
  698. if not test_val("Client Error", "404", status):
  699. return False
  700. status = send_getx_uri_len(dut, port, max_uri_len + 1)
  701. if not test_val("Client Error", "414", status):
  702. return False
  703. Utility.console_log("Success")
  704. return True
  705. def send_postx_hdr_len(dut, port, length):
  706. s = Session(dut, port)
  707. path = "/echo"
  708. host = "Host: " + dut
  709. custom_hdr_field = "\r\nCustom: "
  710. custom_hdr_val = "x"*(length - len(host) - len(custom_hdr_field) - len("\r\n\r\n") + len("0"))
  711. request = ("POST " + path + " HTTP/1.1\r\n" + host + custom_hdr_field + custom_hdr_val + "\r\n\r\n").encode()
  712. s.client.sendall(request[:length//2])
  713. time.sleep(1)
  714. s.client.sendall(request[length//2:])
  715. hdr = s.read_resp_hdrs()
  716. resp = s.read_resp_data()
  717. s.close()
  718. if "Custom" in hdr:
  719. return (hdr["Custom"] == custom_hdr_val), resp
  720. return False, s.status
  721. def code_431_hdr_too_long(dut, port, max_hdr_len):
  722. Utility.console_log("[test] 431 Header Too Long =>", end=' ')
  723. res, status = send_postx_hdr_len(dut, port, max_hdr_len)
  724. if not res:
  725. return False
  726. res, status = send_postx_hdr_len(dut, port, max_hdr_len + 1)
  727. if not test_val("Client Error", "431", status):
  728. return False
  729. Utility.console_log("Success")
  730. return True
  731. def test_upgrade_not_supported(dut, port):
  732. Utility.console_log("[test] Upgrade Not Supported =>", end=' ')
  733. s = Session(dut, port)
  734. path = "/hello"
  735. s.client.sendall(("OPTIONS * HTTP/1.1\r\nHost:" + dut + "\r\nUpgrade: TLS/1.0\r\nConnection: Upgrade\r\n\r\n").encode())
  736. s.read_resp_hdrs()
  737. resp = s.read_resp_data()
  738. if not test_val("Client Error", "200", s.status):
  739. s.close()
  740. return False
  741. s.close()
  742. Utility.console_log("Success")
  743. return True
  744. if __name__ == '__main__':
  745. ########### Execution begins here...
  746. # Configuration
  747. # Max number of threads/sessions
  748. max_sessions = 7
  749. max_uri_len = 512
  750. max_hdr_len = 512
  751. parser = argparse.ArgumentParser(description='Run HTTPD Test')
  752. parser.add_argument('-4','--ipv4', help='IPv4 address')
  753. parser.add_argument('-6','--ipv6', help='IPv6 address')
  754. parser.add_argument('-p','--port', help='Port')
  755. args = vars(parser.parse_args())
  756. dut4 = args['ipv4']
  757. dut6 = args['ipv6']
  758. port = args['port']
  759. dut = dut4
  760. _verbose_ = True
  761. Utility.console_log("### Basic HTTP Client Tests")
  762. get_hello(dut, port)
  763. post_hello(dut, port)
  764. put_hello(dut, port)
  765. post_echo(dut, port)
  766. get_echo(dut, port)
  767. put_echo(dut, port)
  768. get_hello_type(dut, port)
  769. get_hello_status(dut, port)
  770. get_false_uri(dut, port)
  771. Utility.console_log("### Error code tests")
  772. code_500_server_error_test(dut, port)
  773. code_501_method_not_impl(dut, port)
  774. code_505_version_not_supported(dut, port)
  775. code_400_bad_request(dut, port)
  776. code_404_not_found(dut, port)
  777. code_405_method_not_allowed(dut, port)
  778. code_408_req_timeout(dut, port)
  779. code_414_uri_too_long(dut, port, max_uri_len)
  780. code_431_hdr_too_long(dut, port, max_hdr_len)
  781. test_upgrade_not_supported(dut, port)
  782. # Not supported yet (Error on chunked request)
  783. ###code_411_length_required(dut, port)
  784. Utility.console_log("### Sessions and Context Tests")
  785. parallel_sessions_adder(dut, port, max_sessions)
  786. leftover_data_test(dut, port)
  787. async_response_test(dut, port)
  788. spillover_session(dut, port, max_sessions)
  789. recv_timeout_test(dut, port)
  790. packet_size_limit_test(dut, port, 50*1024)
  791. get_hello(dut, port)
  792. sys.exit()