esp-idf/tools/ci/python_packages/idf_http_server_test/adder.py

94 lines
2.8 KiB
Python
Raw Normal View History

#!/usr/bin/env python
#
# SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
from __future__ import print_function, unicode_literals
import argparse
import http.client
import logging
from builtins import range, str
2018-12-04 02:32:48 -05:00
def start_session(ip, port):
2018-09-10 09:13:47 -04:00
return http.client.HTTPConnection(ip, int(port), timeout=15)
2018-12-04 02:32:48 -05:00
def end_session(conn):
conn.close()
2018-12-04 02:32:48 -05:00
def getreq(conn, path, verbose=False):
conn.request('GET', path)
resp = conn.getresponse()
data = resp.read()
if verbose:
logging.info('GET : {}'.format(path))
logging.info('Status : {}'.format(resp.status))
logging.info('Reason : {}'.format(resp.reason))
logging.info('Data length : {}'.format(len(data)))
logging.info('Data content : {}'.format(data))
return data
2018-12-04 02:32:48 -05:00
def postreq(conn, path, data, verbose=False):
conn.request('POST', path, data)
resp = conn.getresponse()
data = resp.read()
if verbose:
logging.info('POST : {}'.format(data))
logging.info('Status : {}'.format(resp.status))
logging.info('Reason : {}'.format(resp.reason))
logging.info('Data length : {}'.format(len(data)))
logging.info('Data content : {}'.format(data))
return data
2018-12-04 02:32:48 -05:00
def putreq(conn, path, body, verbose=False):
conn.request('PUT', path, body)
resp = conn.getresponse()
data = resp.read()
if verbose:
logging.info('PUT : {} {}'.format(path, body))
logging.info('Status : {}'.format(resp.status))
logging.info('Reason : {}'.format(resp.reason))
logging.info('Data length : {}'.format(len(data)))
logging.info('Data content : {}'.format(data))
return data
2018-12-04 02:32:48 -05:00
if __name__ == '__main__':
# Configure argument parser
parser = argparse.ArgumentParser(description='Run HTTPd Test')
2018-12-04 02:32:48 -05:00
parser.add_argument('IP', metavar='IP', type=str, help='Server IP')
parser.add_argument('port', metavar='port', type=str, help='Server port')
2018-12-04 02:32:48 -05:00
parser.add_argument('N', metavar='integer', type=int, help='Integer to sum upto')
args = vars(parser.parse_args())
# Get arguments
ip = args['IP']
port = args['port']
N = args['N']
# Establish HTTP connection
logging.info('Connecting to => ' + ip + ':' + port)
2018-12-04 02:32:48 -05:00
conn = start_session(ip, port)
# Reset adder context to specified value(0)
# -- Not needed as new connection will always
# -- have zero value of the accumulator
logging.info('Reset the accumulator to 0')
putreq(conn, '/adder', str(0))
# Sum numbers from 1 to specified value(N)
logging.info('Summing numbers from 1 to {}'.format(N))
2018-12-04 02:32:48 -05:00
for i in range(1, N + 1):
postreq(conn, '/adder', str(i))
# Fetch the result
logging.info('Result :{}'.format(getreq(conn, '/adder')))
# Close HTTP connection
2018-12-04 02:32:48 -05:00
end_session(conn)