test.py 35 KB

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