test.py 35 KB

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