test.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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 builtins import str
  127. from builtins import range
  128. from builtins import object
  129. import threading
  130. import socket
  131. import time
  132. import argparse
  133. import http.client
  134. import sys
  135. import string
  136. import random
  137. from tiny_test_fw import Utility
  138. _verbose_ = False
  139. class Session(object):
  140. def __init__(self, addr, port, timeout=15):
  141. self.client = socket.create_connection((addr, int(port)), timeout=timeout)
  142. self.target = addr
  143. self.status = 0
  144. self.encoding = ''
  145. self.content_type = ''
  146. self.content_len = 0
  147. def send_err_check(self, request, data=None):
  148. rval = True
  149. try:
  150. self.client.sendall(request.encode())
  151. if data:
  152. self.client.sendall(data.encode())
  153. except socket.error as err:
  154. self.client.close()
  155. Utility.console_log("Socket Error in send :", err)
  156. rval = False
  157. return rval
  158. def send_get(self, path, headers=None):
  159. request = "GET " + path + " HTTP/1.1\r\nHost: " + self.target
  160. if headers:
  161. for field, value in headers.items():
  162. request += "\r\n" + field + ": " + value
  163. request += "\r\n\r\n"
  164. return self.send_err_check(request)
  165. def send_put(self, path, data, headers=None):
  166. request = "PUT " + path + " HTTP/1.1\r\nHost: " + self.target
  167. if headers:
  168. for field, value in headers.items():
  169. request += "\r\n" + field + ": " + value
  170. request += "\r\nContent-Length: " + str(len(data)) + "\r\n\r\n"
  171. return self.send_err_check(request, data)
  172. def send_post(self, path, data, headers=None):
  173. request = "POST " + path + " HTTP/1.1\r\nHost: " + self.target
  174. if headers:
  175. for field, value in headers.items():
  176. request += "\r\n" + field + ": " + value
  177. request += "\r\nContent-Length: " + str(len(data)) + "\r\n\r\n"
  178. return self.send_err_check(request, data)
  179. def read_resp_hdrs(self):
  180. try:
  181. state = 'nothing'
  182. resp_read = ''
  183. while True:
  184. char = self.client.recv(1).decode()
  185. if char == '\r' and state == 'nothing':
  186. state = 'first_cr'
  187. elif char == '\n' and state == 'first_cr':
  188. state = 'first_lf'
  189. elif char == '\r' and state == 'first_lf':
  190. state = 'second_cr'
  191. elif char == '\n' and state == 'second_cr':
  192. state = 'second_lf'
  193. else:
  194. state = 'nothing'
  195. resp_read += char
  196. if state == 'second_lf':
  197. break
  198. # Handle first line
  199. line_hdrs = resp_read.splitlines()
  200. line_comp = line_hdrs[0].split()
  201. self.status = line_comp[1]
  202. del line_hdrs[0]
  203. self.encoding = ''
  204. self.content_type = ''
  205. headers = dict()
  206. # Process other headers
  207. for h in range(len(line_hdrs)):
  208. line_comp = line_hdrs[h].split(':')
  209. if line_comp[0] == 'Content-Length':
  210. self.content_len = int(line_comp[1])
  211. if line_comp[0] == 'Content-Type':
  212. self.content_type = line_comp[1].lstrip()
  213. if line_comp[0] == 'Transfer-Encoding':
  214. self.encoding = line_comp[1].lstrip()
  215. if len(line_comp) == 2:
  216. headers[line_comp[0]] = line_comp[1].lstrip()
  217. return headers
  218. except socket.error as err:
  219. self.client.close()
  220. Utility.console_log("Socket Error in recv :", err)
  221. return None
  222. def read_resp_data(self):
  223. try:
  224. read_data = ''
  225. if self.encoding != 'chunked':
  226. while len(read_data) != self.content_len:
  227. read_data += self.client.recv(self.content_len).decode()
  228. else:
  229. chunk_data_buf = ''
  230. while (True):
  231. # Read one character into temp buffer
  232. read_ch = self.client.recv(1)
  233. # Check CRLF
  234. if (read_ch == '\r'):
  235. read_ch = self.client.recv(1).decode()
  236. if (read_ch == '\n'):
  237. # If CRLF decode length of chunk
  238. chunk_len = int(chunk_data_buf, 16)
  239. # Keep adding to contents
  240. self.content_len += chunk_len
  241. rem_len = chunk_len
  242. while (rem_len):
  243. new_data = self.client.recv(rem_len)
  244. read_data += new_data
  245. rem_len -= len(new_data)
  246. chunk_data_buf = ''
  247. # Fetch remaining CRLF
  248. if self.client.recv(2) != "\r\n":
  249. # Error in packet
  250. Utility.console_log("Error in chunked data")
  251. return None
  252. if not chunk_len:
  253. # If last chunk
  254. break
  255. continue
  256. chunk_data_buf += '\r'
  257. # If not CRLF continue appending
  258. # character to chunked data buffer
  259. chunk_data_buf += read_ch
  260. return read_data
  261. except socket.error as err:
  262. self.client.close()
  263. Utility.console_log("Socket Error in recv :", err)
  264. return None
  265. def close(self):
  266. self.client.close()
  267. def test_val(text, expected, received):
  268. if expected != received:
  269. Utility.console_log(" Fail!")
  270. Utility.console_log(" [reason] " + text + ":")
  271. Utility.console_log(" expected: " + str(expected))
  272. Utility.console_log(" received: " + str(received))
  273. return False
  274. return True
  275. class adder_thread (threading.Thread):
  276. def __init__(self, id, dut, port):
  277. threading.Thread.__init__(self)
  278. self.id = id
  279. self.dut = dut
  280. self.depth = 3
  281. self.session = Session(dut, port)
  282. def run(self):
  283. self.response = []
  284. # Pipeline 3 requests
  285. if (_verbose_):
  286. Utility.console_log(" Thread: Using adder start " + str(self.id))
  287. for _ in range(self.depth):
  288. self.session.send_post('/adder', str(self.id))
  289. time.sleep(2)
  290. for _ in range(self.depth):
  291. self.session.read_resp_hdrs()
  292. self.response.append(self.session.read_resp_data())
  293. def adder_result(self):
  294. if len(self.response) != self.depth:
  295. Utility.console_log("Error : missing response packets")
  296. return False
  297. for i in range(len(self.response)):
  298. if not test_val("Thread" + str(self.id) + " response[" + str(i) + "]",
  299. str(self.id * (i + 1)), str(self.response[i])):
  300. return False
  301. return True
  302. def close(self):
  303. self.session.close()
  304. def get_hello(dut, port):
  305. # GET /hello should return 'Hello World!'
  306. Utility.console_log("[test] GET /hello returns 'Hello World!' =>", end=' ')
  307. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  308. conn.request("GET", "/hello")
  309. resp = conn.getresponse()
  310. if not test_val("status_code", 200, resp.status):
  311. conn.close()
  312. return False
  313. if not test_val("data", "Hello World!", resp.read().decode()):
  314. conn.close()
  315. return False
  316. if not test_val("data", "text/html", resp.getheader('Content-Type')):
  317. conn.close()
  318. return False
  319. Utility.console_log("Success")
  320. conn.close()
  321. return True
  322. def put_hello(dut, port):
  323. # PUT /hello returns 405'
  324. Utility.console_log("[test] PUT /hello returns 405 =>", end=' ')
  325. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  326. conn.request("PUT", "/hello", "Hello")
  327. resp = conn.getresponse()
  328. if not test_val("status_code", 405, resp.status):
  329. conn.close()
  330. return False
  331. Utility.console_log("Success")
  332. conn.close()
  333. return True
  334. def post_hello(dut, port):
  335. # POST /hello returns 405'
  336. Utility.console_log("[test] POST /hello returns 405 =>", end=' ')
  337. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  338. conn.request("POST", "/hello", "Hello")
  339. resp = conn.getresponse()
  340. if not test_val("status_code", 405, resp.status):
  341. conn.close()
  342. return False
  343. Utility.console_log("Success")
  344. conn.close()
  345. return True
  346. def post_echo(dut, port):
  347. # POST /echo echoes data'
  348. Utility.console_log("[test] POST /echo echoes data =>", end=' ')
  349. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  350. conn.request("POST", "/echo", "Hello")
  351. resp = conn.getresponse()
  352. if not test_val("status_code", 200, resp.status):
  353. conn.close()
  354. return False
  355. if not test_val("data", "Hello", resp.read().decode()):
  356. conn.close()
  357. return False
  358. Utility.console_log("Success")
  359. conn.close()
  360. return True
  361. def put_echo(dut, port):
  362. # PUT /echo echoes data'
  363. Utility.console_log("[test] PUT /echo echoes data =>", end=' ')
  364. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  365. conn.request("PUT", "/echo", "Hello")
  366. resp = conn.getresponse()
  367. if not test_val("status_code", 200, resp.status):
  368. conn.close()
  369. return False
  370. if not test_val("data", "Hello", resp.read().decode()):
  371. conn.close()
  372. return False
  373. Utility.console_log("Success")
  374. conn.close()
  375. return True
  376. def get_echo(dut, port):
  377. # GET /echo returns 404'
  378. Utility.console_log("[test] GET /echo returns 405 =>", end=' ')
  379. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  380. conn.request("GET", "/echo")
  381. resp = conn.getresponse()
  382. if not test_val("status_code", 405, resp.status):
  383. conn.close()
  384. return False
  385. Utility.console_log("Success")
  386. conn.close()
  387. return True
  388. def get_test_headers(dut, port):
  389. # GET /test_header returns data of Header2'
  390. Utility.console_log("[test] GET /test_header =>", end=' ')
  391. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  392. custom_header = {"Header1": "Value1", "Header3": "Value3"}
  393. header2_values = ["", " ", "Value2", " Value2", "Value2 ", " Value2 "]
  394. for val in header2_values:
  395. custom_header["Header2"] = val
  396. conn.request("GET", "/test_header", headers=custom_header)
  397. resp = conn.getresponse()
  398. if not test_val("status_code", 200, resp.status):
  399. conn.close()
  400. return False
  401. hdr_val_start_idx = val.find("Value2")
  402. if hdr_val_start_idx == -1:
  403. if not test_val("header: Header2", "", resp.read().decode()):
  404. conn.close()
  405. return False
  406. else:
  407. if not test_val("header: Header2", val[hdr_val_start_idx:], resp.read().decode()):
  408. conn.close()
  409. return False
  410. resp.read()
  411. Utility.console_log("Success")
  412. conn.close()
  413. return True
  414. def get_hello_type(dut, port):
  415. # GET /hello/type_html returns text/html as Content-Type'
  416. Utility.console_log("[test] GET /hello/type_html has Content-Type of text/html =>", end=' ')
  417. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  418. conn.request("GET", "/hello/type_html")
  419. resp = conn.getresponse()
  420. if not test_val("status_code", 200, resp.status):
  421. conn.close()
  422. return False
  423. if not test_val("data", "Hello World!", resp.read().decode()):
  424. conn.close()
  425. return False
  426. if not test_val("data", "text/html", resp.getheader('Content-Type')):
  427. conn.close()
  428. return False
  429. Utility.console_log("Success")
  430. conn.close()
  431. return True
  432. def get_hello_status(dut, port):
  433. # GET /hello/status_500 returns status 500'
  434. Utility.console_log("[test] GET /hello/status_500 returns status 500 =>", end=' ')
  435. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  436. conn.request("GET", "/hello/status_500")
  437. resp = conn.getresponse()
  438. if not test_val("status_code", 500, resp.status):
  439. conn.close()
  440. return False
  441. Utility.console_log("Success")
  442. conn.close()
  443. return True
  444. def get_false_uri(dut, port):
  445. # GET /false_uri returns status 404'
  446. Utility.console_log("[test] GET /false_uri returns status 404 =>", end=' ')
  447. conn = http.client.HTTPConnection(dut, int(port), timeout=15)
  448. conn.request("GET", "/false_uri")
  449. resp = conn.getresponse()
  450. if not test_val("status_code", 404, resp.status):
  451. conn.close()
  452. return False
  453. Utility.console_log("Success")
  454. conn.close()
  455. return True
  456. def parallel_sessions_adder(dut, port, max_sessions):
  457. # POSTs on /adder in parallel sessions
  458. Utility.console_log("[test] POST {pipelined} on /adder in " + str(max_sessions) + " sessions =>", end=' ')
  459. t = []
  460. # Create all sessions
  461. for i in range(max_sessions):
  462. t.append(adder_thread(i, dut, port))
  463. for i in range(len(t)):
  464. t[i].start()
  465. for i in range(len(t)):
  466. t[i].join()
  467. res = True
  468. for i in range(len(t)):
  469. if not test_val("Thread" + str(i) + " Failed", t[i].adder_result(), True):
  470. res = False
  471. t[i].close()
  472. if (res):
  473. Utility.console_log("Success")
  474. return res
  475. def async_response_test(dut, port):
  476. # Test that an asynchronous work is executed in the HTTPD's context
  477. # This is tested by reading two responses over the same session
  478. Utility.console_log("[test] Test HTTPD Work Queue (Async response) =>", end=' ')
  479. s = Session(dut, port)
  480. s.send_get('/async_data')
  481. s.read_resp_hdrs()
  482. if not test_val("First Response", "Hello World!", s.read_resp_data()):
  483. s.close()
  484. return False
  485. s.read_resp_hdrs()
  486. if not test_val("Second Response", "Hello Double World!", s.read_resp_data()):
  487. s.close()
  488. return False
  489. s.close()
  490. Utility.console_log("Success")
  491. return True
  492. def leftover_data_test(dut, port):
  493. # Leftover data in POST is purged (valid and invalid URIs)
  494. Utility.console_log("[test] Leftover data in POST is purged (valid and invalid URIs) =>", end=' ')
  495. s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  496. s.request("POST", url='/leftover_data', body="abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
  497. resp = s.getresponse()
  498. if not test_val("Partial data", "abcdefghij", resp.read().decode()):
  499. s.close()
  500. return False
  501. s.request("GET", url='/hello')
  502. resp = s.getresponse()
  503. if not test_val("Hello World Data", "Hello World!", resp.read().decode()):
  504. s.close()
  505. return False
  506. s.request("POST", url='/false_uri', body="abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
  507. resp = s.getresponse()
  508. if not test_val("False URI Status", str(404), str(resp.status)):
  509. s.close()
  510. return False
  511. # socket would have been closed by server due to error
  512. s.close()
  513. s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  514. s.request("GET", url='/hello')
  515. resp = s.getresponse()
  516. if not test_val("Hello World Data", "Hello World!", resp.read().decode()):
  517. s.close()
  518. return False
  519. s.close()
  520. Utility.console_log("Success")
  521. return True
  522. def spillover_session(dut, port, max_sess):
  523. # Session max_sess_sessions + 1 is rejected
  524. Utility.console_log("[test] Session max_sess_sessions (" + str(max_sess) + ") + 1 is rejected =>", end=' ')
  525. s = []
  526. _verbose_ = True
  527. for i in range(max_sess + 1):
  528. if (_verbose_):
  529. Utility.console_log("Executing " + str(i))
  530. try:
  531. a = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  532. a.request("GET", url='/hello')
  533. resp = a.getresponse()
  534. if not test_val("Connection " + str(i), "Hello World!", resp.read().decode()):
  535. a.close()
  536. break
  537. s.append(a)
  538. except Exception:
  539. if (_verbose_):
  540. Utility.console_log("Connection " + str(i) + " rejected")
  541. a.close()
  542. break
  543. # Close open connections
  544. for a in s:
  545. a.close()
  546. # Check if number of connections is equal to max_sess
  547. Utility.console_log(["Fail","Success"][len(s) == max_sess])
  548. return (len(s) == max_sess)
  549. def recv_timeout_test(dut, port):
  550. Utility.console_log("[test] Timeout occurs if partial packet sent =>", end=' ')
  551. s = Session(dut, port)
  552. s.client.sendall(b"GE")
  553. s.read_resp_hdrs()
  554. resp = s.read_resp_data()
  555. if not test_val("Request Timeout", "Server closed this connection", resp):
  556. s.close()
  557. return False
  558. s.close()
  559. Utility.console_log("Success")
  560. return True
  561. def packet_size_limit_test(dut, port, test_size):
  562. Utility.console_log("[test] send size limit test =>", end=' ')
  563. retry = 5
  564. while (retry):
  565. retry -= 1
  566. Utility.console_log("data size = ", test_size)
  567. s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
  568. random_data = ''.join(string.printable[random.randint(0,len(string.printable)) - 1] for _ in list(range(test_size)))
  569. path = "/echo"
  570. s.request("POST", url=path, body=random_data)
  571. resp = s.getresponse()
  572. if not test_val("Error", "200", str(resp.status)):
  573. if test_val("Error", "500", str(resp.status)):
  574. Utility.console_log("Data too large to be allocated")
  575. test_size = test_size // 10
  576. else:
  577. Utility.console_log("Unexpected error")
  578. s.close()
  579. Utility.console_log("Retry...")
  580. continue
  581. resp = resp.read().decode()
  582. result = (resp == random_data)
  583. if not result:
  584. test_val("Data size", str(len(random_data)), str(len(resp)))
  585. s.close()
  586. Utility.console_log("Retry...")
  587. continue
  588. s.close()
  589. Utility.console_log("Success")
  590. return True
  591. Utility.console_log("Failed")
  592. return False
  593. def arbitrary_termination_test(dut, port):
  594. Utility.console_log("[test] Arbitrary termination test =>", end=' ')
  595. cases = [
  596. {
  597. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: SomeValue\r\n\r\n",
  598. "code": "200",
  599. "header": "SomeValue"
  600. },
  601. {
  602. "request": "POST /echo HTTP/1.1\nHost: " + dut + "\r\nCustom: SomeValue\r\n\r\n",
  603. "code": "200",
  604. "header": "SomeValue"
  605. },
  606. {
  607. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\nCustom: SomeValue\r\n\r\n",
  608. "code": "200",
  609. "header": "SomeValue"
  610. },
  611. {
  612. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: SomeValue\n\r\n",
  613. "code": "200",
  614. "header": "SomeValue"
  615. },
  616. {
  617. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: SomeValue\r\n\n",
  618. "code": "200",
  619. "header": "SomeValue"
  620. },
  621. {
  622. "request": "POST /echo HTTP/1.1\nHost: " + dut + "\nCustom: SomeValue\n\n",
  623. "code": "200",
  624. "header": "SomeValue"
  625. },
  626. {
  627. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\n\r\nABCDE",
  628. "code": "200",
  629. "body": "ABCDE"
  630. },
  631. {
  632. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\r\n\nABCDE",
  633. "code": "200",
  634. "body": "ABCDE"
  635. },
  636. {
  637. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\n\nABCDE",
  638. "code": "200",
  639. "body": "ABCDE"
  640. },
  641. {
  642. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\n\n\rABCD",
  643. "code": "200",
  644. "body": "\rABCD"
  645. },
  646. {
  647. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\r\nCustom: SomeValue\r\r\n\r\r\n",
  648. "code": "400"
  649. },
  650. {
  651. "request": "POST /echo HTTP/1.1\r\r\nHost: " + dut + "\r\n\r\n",
  652. "code": "400"
  653. },
  654. {
  655. "request": "POST /echo HTTP/1.1\r\n\rHost: " + dut + "\r\n\r\n",
  656. "code": "400"
  657. },
  658. {
  659. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\rCustom: SomeValue\r\n",
  660. "code": "400"
  661. },
  662. {
  663. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: Some\rValue\r\n",
  664. "code": "400"
  665. },
  666. {
  667. "request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom- SomeValue\r\n\r\n",
  668. "code": "400"
  669. }
  670. ]
  671. for case in cases:
  672. s = Session(dut, port)
  673. s.client.sendall((case['request']).encode())
  674. resp_hdrs = s.read_resp_hdrs()
  675. resp_body = s.read_resp_data()
  676. s.close()
  677. if not test_val("Response Code", case["code"], s.status):
  678. return False
  679. if "header" in case.keys():
  680. resp_hdr_val = None
  681. if "Custom" in resp_hdrs.keys():
  682. resp_hdr_val = resp_hdrs["Custom"]
  683. if not test_val("Response Header", case["header"], resp_hdr_val):
  684. return False
  685. if "body" in case.keys():
  686. if not test_val("Response Body", case["body"], resp_body):
  687. return False
  688. Utility.console_log("Success")
  689. return True
  690. def code_500_server_error_test(dut, port):
  691. Utility.console_log("[test] 500 Server Error test =>", end=' ')
  692. s = Session(dut, port)
  693. # Sending a very large content length will cause malloc to fail
  694. content_len = 2**30
  695. s.client.sendall(("POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: " + str(content_len) + "\r\n\r\nABCD").encode())
  696. s.read_resp_hdrs()
  697. s.read_resp_data()
  698. if not test_val("Server Error", "500", s.status):
  699. s.close()
  700. return False
  701. s.close()
  702. Utility.console_log("Success")
  703. return True
  704. def code_501_method_not_impl(dut, port):
  705. Utility.console_log("[test] 501 Method Not Implemented =>", end=' ')
  706. s = Session(dut, port)
  707. path = "/hello"
  708. s.client.sendall(("ABC " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  709. s.read_resp_hdrs()
  710. s.read_resp_data()
  711. # Presently server sends back 400 Bad Request
  712. # if not test_val("Server Error", "501", s.status):
  713. # s.close()
  714. # return False
  715. if not test_val("Server Error", "400", s.status):
  716. s.close()
  717. return False
  718. s.close()
  719. Utility.console_log("Success")
  720. return True
  721. def code_505_version_not_supported(dut, port):
  722. Utility.console_log("[test] 505 Version Not Supported =>", end=' ')
  723. s = Session(dut, port)
  724. path = "/hello"
  725. s.client.sendall(("GET " + path + " HTTP/2.0\r\nHost: " + dut + "\r\n\r\n").encode())
  726. s.read_resp_hdrs()
  727. s.read_resp_data()
  728. if not test_val("Server Error", "505", s.status):
  729. s.close()
  730. return False
  731. s.close()
  732. Utility.console_log("Success")
  733. return True
  734. def code_400_bad_request(dut, port):
  735. Utility.console_log("[test] 400 Bad Request =>", end=' ')
  736. s = Session(dut, port)
  737. path = "/hello"
  738. s.client.sendall(("XYZ " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  739. s.read_resp_hdrs()
  740. s.read_resp_data()
  741. if not test_val("Client Error", "400", s.status):
  742. s.close()
  743. return False
  744. s.close()
  745. Utility.console_log("Success")
  746. return True
  747. def code_404_not_found(dut, port):
  748. Utility.console_log("[test] 404 Not Found =>", end=' ')
  749. s = Session(dut, port)
  750. path = "/dummy"
  751. s.client.sendall(("GET " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  752. s.read_resp_hdrs()
  753. s.read_resp_data()
  754. if not test_val("Client Error", "404", s.status):
  755. s.close()
  756. return False
  757. s.close()
  758. Utility.console_log("Success")
  759. return True
  760. def code_405_method_not_allowed(dut, port):
  761. Utility.console_log("[test] 405 Method Not Allowed =>", end=' ')
  762. s = Session(dut, port)
  763. path = "/hello"
  764. s.client.sendall(("POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
  765. s.read_resp_hdrs()
  766. s.read_resp_data()
  767. if not test_val("Client Error", "405", s.status):
  768. s.close()
  769. return False
  770. s.close()
  771. Utility.console_log("Success")
  772. return True
  773. def code_408_req_timeout(dut, port):
  774. Utility.console_log("[test] 408 Request Timeout =>", end=' ')
  775. s = Session(dut, port)
  776. s.client.sendall(("POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 10\r\n\r\nABCD").encode())
  777. s.read_resp_hdrs()
  778. s.read_resp_data()
  779. if not test_val("Client Error", "408", s.status):
  780. s.close()
  781. return False
  782. s.close()
  783. Utility.console_log("Success")
  784. return True
  785. def code_411_length_required(dut, port):
  786. Utility.console_log("[test] 411 Length Required =>", end=' ')
  787. s = Session(dut, port)
  788. path = "/echo"
  789. 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())
  790. s.read_resp_hdrs()
  791. s.read_resp_data()
  792. # Presently server sends back 400 Bad Request
  793. # if not test_val("Client Error", "411", s.status):
  794. # s.close()
  795. # return False
  796. if not test_val("Client Error", "400", s.status):
  797. s.close()
  798. return False
  799. s.close()
  800. Utility.console_log("Success")
  801. return True
  802. def send_getx_uri_len(dut, port, length):
  803. s = Session(dut, port)
  804. method = "GET "
  805. version = " HTTP/1.1\r\n"
  806. path = "/" + "x" * (length - len(method) - len(version) - len("/"))
  807. s.client.sendall(method.encode())
  808. time.sleep(1)
  809. s.client.sendall(path.encode())
  810. time.sleep(1)
  811. s.client.sendall((version + "Host: " + dut + "\r\n\r\n").encode())
  812. s.read_resp_hdrs()
  813. s.read_resp_data()
  814. s.close()
  815. return s.status
  816. def code_414_uri_too_long(dut, port, max_uri_len):
  817. Utility.console_log("[test] 414 URI Too Long =>", end=' ')
  818. status = send_getx_uri_len(dut, port, max_uri_len)
  819. if not test_val("Client Error", "404", status):
  820. return False
  821. status = send_getx_uri_len(dut, port, max_uri_len + 1)
  822. if not test_val("Client Error", "414", status):
  823. return False
  824. Utility.console_log("Success")
  825. return True
  826. def send_postx_hdr_len(dut, port, length):
  827. s = Session(dut, port)
  828. path = "/echo"
  829. host = "Host: " + dut
  830. custom_hdr_field = "\r\nCustom: "
  831. custom_hdr_val = "x" * (length - len(host) - len(custom_hdr_field) - len("\r\n\r\n") + len("0"))
  832. request = ("POST " + path + " HTTP/1.1\r\n" + host + custom_hdr_field + custom_hdr_val + "\r\n\r\n").encode()
  833. s.client.sendall(request[:length // 2])
  834. time.sleep(1)
  835. s.client.sendall(request[length // 2:])
  836. hdr = s.read_resp_hdrs()
  837. resp = s.read_resp_data()
  838. s.close()
  839. if hdr and ("Custom" in hdr):
  840. return (hdr["Custom"] == custom_hdr_val), resp
  841. return False, s.status
  842. def code_431_hdr_too_long(dut, port, max_hdr_len):
  843. Utility.console_log("[test] 431 Header Too Long =>", end=' ')
  844. res, status = send_postx_hdr_len(dut, port, max_hdr_len)
  845. if not res:
  846. return False
  847. res, status = send_postx_hdr_len(dut, port, max_hdr_len + 1)
  848. if not test_val("Client Error", "431", status):
  849. return False
  850. Utility.console_log("Success")
  851. return True
  852. def test_upgrade_not_supported(dut, port):
  853. Utility.console_log("[test] Upgrade Not Supported =>", end=' ')
  854. s = Session(dut, port)
  855. # path = "/hello"
  856. s.client.sendall(("OPTIONS * HTTP/1.1\r\nHost:" + dut + "\r\nUpgrade: TLS/1.0\r\nConnection: Upgrade\r\n\r\n").encode())
  857. s.read_resp_hdrs()
  858. s.read_resp_data()
  859. if not test_val("Client Error", "400", s.status):
  860. s.close()
  861. return False
  862. s.close()
  863. Utility.console_log("Success")
  864. return True
  865. if __name__ == '__main__':
  866. # Execution begins here...
  867. # Configuration
  868. # Max number of threads/sessions
  869. max_sessions = 7
  870. max_uri_len = 512
  871. max_hdr_len = 512
  872. parser = argparse.ArgumentParser(description='Run HTTPD Test')
  873. parser.add_argument('-4','--ipv4', help='IPv4 address')
  874. parser.add_argument('-6','--ipv6', help='IPv6 address')
  875. parser.add_argument('-p','--port', help='Port')
  876. args = vars(parser.parse_args())
  877. dut4 = args['ipv4']
  878. dut6 = args['ipv6']
  879. port = args['port']
  880. dut = dut4
  881. _verbose_ = True
  882. Utility.console_log("### Basic HTTP Client Tests")
  883. get_hello(dut, port)
  884. post_hello(dut, port)
  885. put_hello(dut, port)
  886. post_echo(dut, port)
  887. get_echo(dut, port)
  888. put_echo(dut, port)
  889. get_hello_type(dut, port)
  890. get_hello_status(dut, port)
  891. get_false_uri(dut, port)
  892. get_test_headers(dut, port)
  893. Utility.console_log("### Error code tests")
  894. code_500_server_error_test(dut, port)
  895. code_501_method_not_impl(dut, port)
  896. code_505_version_not_supported(dut, port)
  897. code_400_bad_request(dut, port)
  898. code_404_not_found(dut, port)
  899. code_405_method_not_allowed(dut, port)
  900. code_408_req_timeout(dut, port)
  901. code_414_uri_too_long(dut, port, max_uri_len)
  902. code_431_hdr_too_long(dut, port, max_hdr_len)
  903. test_upgrade_not_supported(dut, port)
  904. # Not supported yet (Error on chunked request)
  905. # code_411_length_required(dut, port)
  906. Utility.console_log("### Sessions and Context Tests")
  907. parallel_sessions_adder(dut, port, max_sessions)
  908. leftover_data_test(dut, port)
  909. async_response_test(dut, port)
  910. spillover_session(dut, port, max_sessions)
  911. recv_timeout_test(dut, port)
  912. packet_size_limit_test(dut, port, 50 * 1024)
  913. arbitrary_termination_test(dut, port)
  914. get_hello(dut, port)
  915. sys.exit()