style: format python files with isort and double-quote-string-fixer
This commit is contained in:
@@ -1,21 +1,21 @@
|
||||
import re
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from threading import Thread
|
||||
import time
|
||||
from threading import Thread
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
global g_client_response
|
||||
global g_msg_to_client
|
||||
|
||||
g_client_response = b""
|
||||
g_msg_to_client = b" 3XYZ"
|
||||
g_client_response = b''
|
||||
g_msg_to_client = b' 3XYZ'
|
||||
|
||||
|
||||
def get_my_ip():
|
||||
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s1.connect(("8.8.8.8", 80))
|
||||
s1.connect(('8.8.8.8', 80))
|
||||
my_ip = s1.getsockname()[0]
|
||||
s1.close()
|
||||
return my_ip
|
||||
@@ -23,14 +23,14 @@ def get_my_ip():
|
||||
|
||||
def chat_server_sketch(my_ip):
|
||||
global g_client_response
|
||||
print("Starting the server on {}".format(my_ip))
|
||||
print('Starting the server on {}'.format(my_ip))
|
||||
port = 2222
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(600)
|
||||
s.bind((my_ip, port))
|
||||
s.listen(1)
|
||||
q,addr = s.accept()
|
||||
print("connection accepted")
|
||||
print('connection accepted')
|
||||
q.settimeout(30)
|
||||
q.send(g_msg_to_client)
|
||||
data = q.recv(1024)
|
||||
@@ -39,12 +39,12 @@ def chat_server_sketch(my_ip):
|
||||
g_client_response = data
|
||||
else:
|
||||
g_client_response = q.recv(1024)
|
||||
print("received from client {}".format(g_client_response))
|
||||
print('received from client {}'.format(g_client_response))
|
||||
s.close()
|
||||
print("server closed")
|
||||
print('server closed')
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_asio_chat_client(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -57,19 +57,19 @@ def test_examples_protocol_asio_chat_client(env, extra_data):
|
||||
"""
|
||||
global g_client_response
|
||||
global g_msg_to_client
|
||||
test_msg = "ABC"
|
||||
dut1 = env.get_dut("chat_client", "examples/protocols/asio/chat_client", dut_class=ttfw_idf.ESP32DUT)
|
||||
test_msg = 'ABC'
|
||||
dut1 = env.get_dut('chat_client', 'examples/protocols/asio/chat_client', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_chat_client.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'asio_chat_client.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("asio_chat_client_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('asio_chat_client_size', '{}KB'.format(bin_size // 1024))
|
||||
# 1. start a tcp server on the host
|
||||
host_ip = get_my_ip()
|
||||
thread1 = Thread(target=chat_server_sketch, args=(host_ip,))
|
||||
thread1.start()
|
||||
# 2. start the dut test and wait till client gets IP address
|
||||
dut1.start_app()
|
||||
dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)
|
||||
dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)
|
||||
# 3. send host's IP to the client i.e. the `dut1`
|
||||
dut1.write(host_ip)
|
||||
# 4. client `dut1` should receive a message
|
||||
@@ -82,10 +82,10 @@ def test_examples_protocol_asio_chat_client(env, extra_data):
|
||||
print(g_client_response)
|
||||
# 6. evaluate host_server received this message
|
||||
if (g_client_response[4:7] == test_msg):
|
||||
print("PASS: Received correct message")
|
||||
print('PASS: Received correct message')
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
print('Failure!')
|
||||
raise ValueError('Wrong data received from asi tcp server: {} (expected:{})'.format(g_client_response[4:7], test_msg))
|
||||
thread1.join()
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import re
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_asio_chat_server(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -14,16 +14,16 @@ def test_examples_protocol_asio_chat_server(env, extra_data):
|
||||
3. Test connects to server and sends a test message
|
||||
4. Test evaluates received test message from server
|
||||
"""
|
||||
test_msg = b" 4ABC\n"
|
||||
dut1 = env.get_dut("chat_server", "examples/protocols/asio/chat_server", dut_class=ttfw_idf.ESP32DUT)
|
||||
test_msg = b' 4ABC\n'
|
||||
dut1 = env.get_dut('chat_server', 'examples/protocols/asio/chat_server', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_chat_server.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'asio_chat_server.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("asio_chat_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('asio_chat_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# 1. start test
|
||||
dut1.start_app()
|
||||
# 2. get the server IP address
|
||||
data = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)
|
||||
data = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)
|
||||
# 3. create tcp client and connect to server
|
||||
cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
cli.settimeout(30)
|
||||
@@ -32,10 +32,10 @@ def test_examples_protocol_asio_chat_server(env, extra_data):
|
||||
data = cli.recv(1024)
|
||||
# 4. check the message received back from the server
|
||||
if (data == test_msg):
|
||||
print("PASS: Received correct message {}".format(data))
|
||||
print('PASS: Received correct message {}'.format(data))
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
print('Failure!')
|
||||
raise ValueError('Wrong data received from asi tcp server: {} (expoected:{})'.format(data, test_msg))
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import re
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_asio_tcp_server(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -15,16 +15,16 @@ def test_examples_protocol_asio_tcp_server(env, extra_data):
|
||||
4. Test evaluates received test message from server
|
||||
5. Test evaluates received test message on server stdout
|
||||
"""
|
||||
test_msg = b"echo message from client to server"
|
||||
dut1 = env.get_dut("tcp_echo_server", "examples/protocols/asio/tcp_echo_server", dut_class=ttfw_idf.ESP32DUT)
|
||||
test_msg = b'echo message from client to server'
|
||||
dut1 = env.get_dut('tcp_echo_server', 'examples/protocols/asio/tcp_echo_server', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_tcp_echo_server.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'asio_tcp_echo_server.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("asio_tcp_echo_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('asio_tcp_echo_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# 1. start test
|
||||
dut1.start_app()
|
||||
# 2. get the server IP address
|
||||
data = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)
|
||||
data = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)
|
||||
# 3. create tcp client and connect to server
|
||||
cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
cli.settimeout(30)
|
||||
@@ -33,10 +33,10 @@ def test_examples_protocol_asio_tcp_server(env, extra_data):
|
||||
data = cli.recv(1024)
|
||||
# 4. check the message received back from the server
|
||||
if (data == test_msg):
|
||||
print("PASS: Received correct message")
|
||||
print('PASS: Received correct message')
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
print('Failure!')
|
||||
raise ValueError('Wrong data received from asi tcp server: {} (expected:{})'.format(data, test_msg))
|
||||
# 5. check the client message appears also on server terminal
|
||||
dut1.expect(test_msg.decode())
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import re
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_asio_udp_server(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -15,16 +15,16 @@ def test_examples_protocol_asio_udp_server(env, extra_data):
|
||||
4. Test evaluates received test message from server
|
||||
5. Test evaluates received test message on server stdout
|
||||
"""
|
||||
test_msg = b"echo message from client to server"
|
||||
dut1 = env.get_dut("udp_echo_server", "examples/protocols/asio/udp_echo_server", dut_class=ttfw_idf.ESP32DUT)
|
||||
test_msg = b'echo message from client to server'
|
||||
dut1 = env.get_dut('udp_echo_server', 'examples/protocols/asio/udp_echo_server', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_udp_echo_server.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'asio_udp_echo_server.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("asio_udp_echo_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('asio_udp_echo_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# 1. start test
|
||||
dut1.start_app()
|
||||
# 2. get the server IP address
|
||||
data = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)
|
||||
data = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)
|
||||
# 3. create tcp client and connect to server
|
||||
cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
cli.settimeout(30)
|
||||
@@ -33,10 +33,10 @@ def test_examples_protocol_asio_udp_server(env, extra_data):
|
||||
data = cli.recv(1024)
|
||||
# 4. check the message received back from the server
|
||||
if (data == test_msg):
|
||||
print("PASS: Received correct message")
|
||||
print('PASS: Received correct message')
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
print('Failure!')
|
||||
raise ValueError('Wrong data received from asio udp server: {} (expected:{})'.format(data, test_msg))
|
||||
# 5. check the client message appears also on server terminal
|
||||
dut1.expect(test_msg.decode())
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import re
|
||||
import textwrap
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
|
||||
@@ -1,64 +1,64 @@
|
||||
import re
|
||||
import os
|
||||
import re
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_EthKitV1")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_EthKitV1')
|
||||
def test_examples_protocol_esp_http_client(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
1. join AP
|
||||
2. Send HTTP request to httpbin.org
|
||||
"""
|
||||
dut1 = env.get_dut("esp_http_client", "examples/protocols/esp_http_client", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('esp_http_client', 'examples/protocols/esp_http_client', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "esp-http-client-example.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'esp-http-client-example.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("esp_http_client_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('esp_http_client_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# start test
|
||||
dut1.start_app()
|
||||
dut1.expect("Connected to AP, begin http example", timeout=30)
|
||||
dut1.expect(re.compile(r"HTTP GET Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP POST Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP PUT Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP PATCH Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP DELETE Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP HEAD Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Basic Auth Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Basic Auth redirect Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Digest Auth Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTPS Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP chunk encoding Status = 200, content_length = (-?\d)"))
|
||||
dut1.expect('Connected to AP, begin http example', timeout=30)
|
||||
dut1.expect(re.compile(r'HTTP GET Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP POST Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP PUT Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP PATCH Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP DELETE Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP HEAD Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP Basic Auth Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP Basic Auth redirect Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP Digest Auth Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTPS Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP chunk encoding Status = 200, content_length = (-?\d)'))
|
||||
# content-len for chunked encoding is typically -1, could be a positive length in some cases
|
||||
dut1.expect(re.compile(r"HTTP Stream reader Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"Last esp error code: 0x8001"))
|
||||
dut1.expect("Finish http example")
|
||||
dut1.expect(re.compile(r'HTTP Stream reader Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'Last esp error code: 0x8001'))
|
||||
dut1.expect('Finish http example')
|
||||
|
||||
# test mbedtls dynamic resource
|
||||
dut1 = env.get_dut("esp_http_client", "examples/protocols/esp_http_client", dut_class=ttfw_idf.ESP32DUT, app_config_name='ssldyn')
|
||||
dut1 = env.get_dut('esp_http_client', 'examples/protocols/esp_http_client', dut_class=ttfw_idf.ESP32DUT, app_config_name='ssldyn')
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "esp-http-client-example.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'esp-http-client-example.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("esp_http_client_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('esp_http_client_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# start test
|
||||
dut1.start_app()
|
||||
dut1.expect("Connected to AP, begin http example", timeout=30)
|
||||
dut1.expect(re.compile(r"HTTP GET Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP POST Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP PUT Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP PATCH Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP DELETE Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP HEAD Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Basic Auth Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Basic Auth redirect Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Digest Auth Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTPS Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP chunk encoding Status = 200, content_length = (-?\d)"))
|
||||
dut1.expect('Connected to AP, begin http example', timeout=30)
|
||||
dut1.expect(re.compile(r'HTTP GET Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP POST Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP PUT Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP PATCH Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP DELETE Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP HEAD Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP Basic Auth Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP Basic Auth redirect Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP Digest Auth Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTPS Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'HTTP chunk encoding Status = 200, content_length = (-?\d)'))
|
||||
# content-len for chunked encoding is typically -1, could be a positive length in some cases
|
||||
dut1.expect(re.compile(r"HTTP Stream reader Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"Last esp error code: 0x8001"))
|
||||
dut1.expect("Finish http example")
|
||||
dut1.expect(re.compile(r'HTTP Stream reader Status = 200, content_length = (\d)'))
|
||||
dut1.expect(re.compile(r'Last esp error code: 0x8001'))
|
||||
dut1.expect('Finish http example')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
|
||||
@@ -16,22 +16,22 @@
|
||||
#
|
||||
|
||||
from __future__ import print_function
|
||||
from future.utils import tobytes
|
||||
from builtins import input
|
||||
import os
|
||||
import sys
|
||||
import struct
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import ssl
|
||||
import struct
|
||||
import sys
|
||||
from builtins import input
|
||||
|
||||
import proto
|
||||
from future.utils import tobytes
|
||||
|
||||
# The tools directory is already in the PATH in environment prepared by install.sh which would allow to import
|
||||
# esp_prov as file but not as complete module.
|
||||
sys.path.insert(0, os.path.join(os.environ['IDF_PATH'], 'tools/esp_prov'))
|
||||
import esp_prov # noqa: E402
|
||||
|
||||
|
||||
# Set this to true to allow exceptions to be thrown
|
||||
config_throw_except = False
|
||||
|
||||
@@ -48,26 +48,26 @@ PROP_FLAG_READONLY = (1 << 0)
|
||||
|
||||
|
||||
def prop_typestr(prop):
|
||||
if prop["type"] == PROP_TYPE_TIMESTAMP:
|
||||
return "TIME(us)"
|
||||
elif prop["type"] == PROP_TYPE_INT32:
|
||||
return "INT32"
|
||||
elif prop["type"] == PROP_TYPE_BOOLEAN:
|
||||
return "BOOLEAN"
|
||||
elif prop["type"] == PROP_TYPE_STRING:
|
||||
return "STRING"
|
||||
return "UNKNOWN"
|
||||
if prop['type'] == PROP_TYPE_TIMESTAMP:
|
||||
return 'TIME(us)'
|
||||
elif prop['type'] == PROP_TYPE_INT32:
|
||||
return 'INT32'
|
||||
elif prop['type'] == PROP_TYPE_BOOLEAN:
|
||||
return 'BOOLEAN'
|
||||
elif prop['type'] == PROP_TYPE_STRING:
|
||||
return 'STRING'
|
||||
return 'UNKNOWN'
|
||||
|
||||
|
||||
def encode_prop_value(prop, value):
|
||||
try:
|
||||
if prop["type"] == PROP_TYPE_TIMESTAMP:
|
||||
if prop['type'] == PROP_TYPE_TIMESTAMP:
|
||||
return struct.pack('q', value)
|
||||
elif prop["type"] == PROP_TYPE_INT32:
|
||||
elif prop['type'] == PROP_TYPE_INT32:
|
||||
return struct.pack('i', value)
|
||||
elif prop["type"] == PROP_TYPE_BOOLEAN:
|
||||
elif prop['type'] == PROP_TYPE_BOOLEAN:
|
||||
return struct.pack('?', value)
|
||||
elif prop["type"] == PROP_TYPE_STRING:
|
||||
elif prop['type'] == PROP_TYPE_STRING:
|
||||
return tobytes(value)
|
||||
return value
|
||||
except struct.error as e:
|
||||
@@ -77,13 +77,13 @@ def encode_prop_value(prop, value):
|
||||
|
||||
def decode_prop_value(prop, value):
|
||||
try:
|
||||
if prop["type"] == PROP_TYPE_TIMESTAMP:
|
||||
if prop['type'] == PROP_TYPE_TIMESTAMP:
|
||||
return struct.unpack('q', value)[0]
|
||||
elif prop["type"] == PROP_TYPE_INT32:
|
||||
elif prop['type'] == PROP_TYPE_INT32:
|
||||
return struct.unpack('i', value)[0]
|
||||
elif prop["type"] == PROP_TYPE_BOOLEAN:
|
||||
elif prop['type'] == PROP_TYPE_BOOLEAN:
|
||||
return struct.unpack('?', value)[0]
|
||||
elif prop["type"] == PROP_TYPE_STRING:
|
||||
elif prop['type'] == PROP_TYPE_STRING:
|
||||
return value.decode('latin-1')
|
||||
return value
|
||||
except struct.error as e:
|
||||
@@ -93,13 +93,13 @@ def decode_prop_value(prop, value):
|
||||
|
||||
def str_to_prop_value(prop, strval):
|
||||
try:
|
||||
if prop["type"] == PROP_TYPE_TIMESTAMP:
|
||||
if prop['type'] == PROP_TYPE_TIMESTAMP:
|
||||
return int(strval)
|
||||
elif prop["type"] == PROP_TYPE_INT32:
|
||||
elif prop['type'] == PROP_TYPE_INT32:
|
||||
return int(strval)
|
||||
elif prop["type"] == PROP_TYPE_BOOLEAN:
|
||||
elif prop['type'] == PROP_TYPE_BOOLEAN:
|
||||
return bool(strval)
|
||||
elif prop["type"] == PROP_TYPE_STRING:
|
||||
elif prop['type'] == PROP_TYPE_STRING:
|
||||
return strval
|
||||
return strval
|
||||
except ValueError as e:
|
||||
@@ -108,7 +108,7 @@ def str_to_prop_value(prop, strval):
|
||||
|
||||
|
||||
def prop_is_readonly(prop):
|
||||
return (prop["flags"] & PROP_FLAG_READONLY) != 0
|
||||
return (prop['flags'] & PROP_FLAG_READONLY) != 0
|
||||
|
||||
|
||||
def on_except(err):
|
||||
@@ -122,8 +122,8 @@ def get_transport(sel_transport, service_name, check_hostname):
|
||||
try:
|
||||
tp = None
|
||||
if (sel_transport == 'http'):
|
||||
example_path = os.environ['IDF_PATH'] + "/examples/protocols/esp_local_ctrl"
|
||||
cert_path = example_path + "/main/certs/rootCA.pem"
|
||||
example_path = os.environ['IDF_PATH'] + '/examples/protocols/esp_local_ctrl'
|
||||
cert_path = example_path + '/main/certs/rootCA.pem'
|
||||
ssl_ctx = ssl.create_default_context(cafile=cert_path)
|
||||
ssl_ctx.check_hostname = check_hostname
|
||||
tp = esp_prov.transport.Transport_HTTP(service_name, ssl_ctx)
|
||||
@@ -156,15 +156,15 @@ def get_all_property_values(tp):
|
||||
response = tp.send_data('esp_local_ctrl/control', message)
|
||||
count = proto.get_prop_count_response(response)
|
||||
if count == 0:
|
||||
raise RuntimeError("No properties found!")
|
||||
raise RuntimeError('No properties found!')
|
||||
indices = [i for i in range(count)]
|
||||
message = proto.get_prop_vals_request(indices)
|
||||
response = tp.send_data('esp_local_ctrl/control', message)
|
||||
props = proto.get_prop_vals_response(response)
|
||||
if len(props) != count:
|
||||
raise RuntimeError("Incorrect count of properties!")
|
||||
raise RuntimeError('Incorrect count of properties!')
|
||||
for p in props:
|
||||
p["value"] = decode_prop_value(p, p["value"])
|
||||
p['value'] = decode_prop_value(p, p['value'])
|
||||
return props
|
||||
except RuntimeError as e:
|
||||
on_except(e)
|
||||
@@ -176,7 +176,7 @@ def set_property_values(tp, props, indices, values, check_readonly=False):
|
||||
if check_readonly:
|
||||
for index in indices:
|
||||
if prop_is_readonly(props[index]):
|
||||
raise RuntimeError("Cannot set value of Read-Only property")
|
||||
raise RuntimeError('Cannot set value of Read-Only property')
|
||||
message = proto.set_prop_vals_request(indices, values)
|
||||
response = tp.send_data('esp_local_ctrl/control', message)
|
||||
return proto.set_prop_vals_response(response)
|
||||
@@ -188,27 +188,27 @@ def set_property_values(tp, props, indices, values, check_readonly=False):
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
|
||||
parser = argparse.ArgumentParser(description="Control an ESP32 running esp_local_ctrl service")
|
||||
parser = argparse.ArgumentParser(description='Control an ESP32 running esp_local_ctrl service')
|
||||
|
||||
parser.add_argument("--version", dest='version', type=str,
|
||||
help="Protocol version", default='')
|
||||
parser.add_argument('--version', dest='version', type=str,
|
||||
help='Protocol version', default='')
|
||||
|
||||
parser.add_argument("--transport", dest='transport', type=str,
|
||||
help="transport i.e http or ble", default='http')
|
||||
parser.add_argument('--transport', dest='transport', type=str,
|
||||
help='transport i.e http or ble', default='http')
|
||||
|
||||
parser.add_argument("--name", dest='service_name', type=str,
|
||||
help="BLE Device Name / HTTP Server hostname or IP", default='')
|
||||
parser.add_argument('--name', dest='service_name', type=str,
|
||||
help='BLE Device Name / HTTP Server hostname or IP', default='')
|
||||
|
||||
parser.add_argument("--dont-check-hostname", action="store_true",
|
||||
parser.add_argument('--dont-check-hostname', action='store_true',
|
||||
# If enabled, the certificate won't be rejected for hostname mismatch.
|
||||
# This option is hidden because it should be used only for testing purposes.
|
||||
help=argparse.SUPPRESS)
|
||||
|
||||
parser.add_argument("-v", "--verbose", dest='verbose', help="increase output verbosity", action="store_true")
|
||||
parser.add_argument('-v', '--verbose', dest='verbose', help='increase output verbosity', action='store_true')
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.version != '':
|
||||
print("==== Esp_Ctrl Version: " + args.version + " ====")
|
||||
print('==== Esp_Ctrl Version: ' + args.version + ' ====')
|
||||
|
||||
if args.service_name == '':
|
||||
args.service_name = 'my_esp_ctrl_device'
|
||||
@@ -217,45 +217,45 @@ if __name__ == '__main__':
|
||||
|
||||
obj_transport = get_transport(args.transport, args.service_name, not args.dont_check_hostname)
|
||||
if obj_transport is None:
|
||||
print("---- Invalid transport ----")
|
||||
print('---- Invalid transport ----')
|
||||
exit(1)
|
||||
|
||||
if args.version != '':
|
||||
print("\n==== Verifying protocol version ====")
|
||||
print('\n==== Verifying protocol version ====')
|
||||
if not version_match(obj_transport, args.version, args.verbose):
|
||||
print("---- Error in protocol version matching ----")
|
||||
print('---- Error in protocol version matching ----')
|
||||
exit(2)
|
||||
print("==== Verified protocol version successfully ====")
|
||||
print('==== Verified protocol version successfully ====')
|
||||
|
||||
while True:
|
||||
properties = get_all_property_values(obj_transport)
|
||||
if len(properties) == 0:
|
||||
print("---- Error in reading property values ----")
|
||||
print('---- Error in reading property values ----')
|
||||
exit(4)
|
||||
|
||||
print("\n==== Available Properties ====")
|
||||
print("{0: >4} {1: <16} {2: <10} {3: <16} {4: <16}".format(
|
||||
"S.N.", "Name", "Type", "Flags", "Value"))
|
||||
print('\n==== Available Properties ====')
|
||||
print('{0: >4} {1: <16} {2: <10} {3: <16} {4: <16}'.format(
|
||||
'S.N.', 'Name', 'Type', 'Flags', 'Value'))
|
||||
for i in range(len(properties)):
|
||||
print("[{0: >2}] {1: <16} {2: <10} {3: <16} {4: <16}".format(
|
||||
i + 1, properties[i]["name"], prop_typestr(properties[i]),
|
||||
["","Read-Only"][prop_is_readonly(properties[i])],
|
||||
str(properties[i]["value"])))
|
||||
print('[{0: >2}] {1: <16} {2: <10} {3: <16} {4: <16}'.format(
|
||||
i + 1, properties[i]['name'], prop_typestr(properties[i]),
|
||||
['','Read-Only'][prop_is_readonly(properties[i])],
|
||||
str(properties[i]['value'])))
|
||||
|
||||
select = 0
|
||||
while True:
|
||||
try:
|
||||
inval = input("\nSelect properties to set (0 to re-read, 'q' to quit) : ")
|
||||
if inval.lower() == 'q':
|
||||
print("Quitting...")
|
||||
print('Quitting...')
|
||||
exit(5)
|
||||
invals = inval.split(',')
|
||||
selections = [int(val) for val in invals]
|
||||
if min(selections) < 0 or max(selections) > len(properties):
|
||||
raise ValueError("Invalid input")
|
||||
raise ValueError('Invalid input')
|
||||
break
|
||||
except ValueError as e:
|
||||
print(str(e) + "! Retry...")
|
||||
print(str(e) + '! Retry...')
|
||||
|
||||
if len(selections) == 1 and selections[0] == 0:
|
||||
continue
|
||||
@@ -264,15 +264,15 @@ if __name__ == '__main__':
|
||||
set_indices = []
|
||||
for select in selections:
|
||||
while True:
|
||||
inval = input("Enter value to set for property (" + properties[select - 1]["name"] + ") : ")
|
||||
inval = input('Enter value to set for property (' + properties[select - 1]['name'] + ') : ')
|
||||
value = encode_prop_value(properties[select - 1],
|
||||
str_to_prop_value(properties[select - 1], inval))
|
||||
if value is None:
|
||||
print("Invalid input! Retry...")
|
||||
print('Invalid input! Retry...')
|
||||
continue
|
||||
break
|
||||
set_values += [value]
|
||||
set_indices += [select - 1]
|
||||
|
||||
if not set_property_values(obj_transport, properties, set_indices, set_values):
|
||||
print("Failed to set values!")
|
||||
print('Failed to set values!')
|
||||
|
||||
@@ -15,9 +15,11 @@
|
||||
|
||||
|
||||
from __future__ import print_function
|
||||
from future.utils import tobytes
|
||||
|
||||
import os
|
||||
|
||||
from future.utils import tobytes
|
||||
|
||||
|
||||
def _load_source(name, path):
|
||||
try:
|
||||
@@ -30,8 +32,8 @@ def _load_source(name, path):
|
||||
|
||||
|
||||
idf_path = os.environ['IDF_PATH']
|
||||
constants_pb2 = _load_source("constants_pb2", idf_path + "/components/protocomm/python/constants_pb2.py")
|
||||
local_ctrl_pb2 = _load_source("esp_local_ctrl_pb2", idf_path + "/components/esp_local_ctrl/python/esp_local_ctrl_pb2.py")
|
||||
constants_pb2 = _load_source('constants_pb2', idf_path + '/components/protocomm/python/constants_pb2.py')
|
||||
local_ctrl_pb2 = _load_source('esp_local_ctrl_pb2', idf_path + '/components/esp_local_ctrl/python/esp_local_ctrl_pb2.py')
|
||||
|
||||
|
||||
def get_prop_count_request():
|
||||
@@ -67,10 +69,10 @@ def get_prop_vals_response(response_data):
|
||||
if (resp.resp_get_prop_vals.status == 0):
|
||||
for prop in resp.resp_get_prop_vals.props:
|
||||
results += [{
|
||||
"name": prop.name,
|
||||
"type": prop.type,
|
||||
"flags": prop.flags,
|
||||
"value": tobytes(prop.value)
|
||||
'name': prop.name,
|
||||
'type': prop.type,
|
||||
'flags': prop.flags,
|
||||
'value': tobytes(prop.value)
|
||||
}]
|
||||
return results
|
||||
|
||||
|
||||
@@ -14,15 +14,14 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
import re
|
||||
import os
|
||||
from __future__ import division, print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from tiny_test_fw import Utility
|
||||
import ttfw_idf
|
||||
from idf_http_server_test import test as client
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
# When running on local machine execute the following before running this script
|
||||
# > make app bootloader
|
||||
@@ -36,23 +35,23 @@ from idf_http_server_test import test as client
|
||||
# features to this component.
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_http_server_advanced(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/advanced_tests", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('http_server', 'examples/protocols/http_server/advanced_tests', dut_class=ttfw_idf.ESP32DUT)
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "tests.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'tests.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("http_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('http_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# Upload binary and start testing
|
||||
Utility.console_log("Starting http_server advanced test app")
|
||||
Utility.console_log('Starting http_server advanced test app')
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
Utility.console_log("Waiting to connect with AP")
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
Utility.console_log('Waiting to connect with AP')
|
||||
got_ip = dut1.expect(re.compile(r'(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=30)[0]
|
||||
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Started HTTP server on port: '(\d+)'"), timeout=15)[0]
|
||||
result = dut1.expect(re.compile(r"(?:[\s\S]*)Max URI handlers: '(\d+)'(?:[\s\S]*)Max Open Sessions: " # noqa: W605
|
||||
@@ -64,18 +63,18 @@ def test_examples_protocol_http_server_advanced(env, extra_data):
|
||||
max_uri_len = int(result[3])
|
||||
max_stack_size = int(result[4])
|
||||
|
||||
Utility.console_log("Got IP : " + got_ip)
|
||||
Utility.console_log("Got Port : " + got_port)
|
||||
Utility.console_log('Got IP : ' + got_ip)
|
||||
Utility.console_log('Got Port : ' + got_port)
|
||||
|
||||
# Run test script
|
||||
# If failed raise appropriate exception
|
||||
failed = False
|
||||
|
||||
Utility.console_log("Sessions and Context Tests...")
|
||||
Utility.console_log('Sessions and Context Tests...')
|
||||
if not client.spillover_session(got_ip, got_port, max_sessions):
|
||||
Utility.console_log("Ignoring failure")
|
||||
Utility.console_log('Ignoring failure')
|
||||
if not client.parallel_sessions_adder(got_ip, got_port, max_sessions):
|
||||
Utility.console_log("Ignoring failure")
|
||||
Utility.console_log('Ignoring failure')
|
||||
if not client.leftover_data_test(got_ip, got_port):
|
||||
failed = True
|
||||
if not client.async_response_test(got_ip, got_port):
|
||||
@@ -90,17 +89,17 @@ def test_examples_protocol_http_server_advanced(env, extra_data):
|
||||
# if not client.packet_size_limit_test(got_ip, got_port, test_size):
|
||||
# Utility.console_log("Ignoring failure")
|
||||
|
||||
Utility.console_log("Getting initial stack usage...")
|
||||
Utility.console_log('Getting initial stack usage...')
|
||||
if not client.get_hello(got_ip, got_port):
|
||||
failed = True
|
||||
|
||||
inital_stack = int(dut1.expect(re.compile(r"(?:[\s\S]*)Free Stack for server task: '(\d+)'"), timeout=15)[0])
|
||||
|
||||
if inital_stack < 0.1 * max_stack_size:
|
||||
Utility.console_log("More than 90% of stack being used on server start")
|
||||
Utility.console_log('More than 90% of stack being used on server start')
|
||||
failed = True
|
||||
|
||||
Utility.console_log("Basic HTTP Client Tests...")
|
||||
Utility.console_log('Basic HTTP Client Tests...')
|
||||
if not client.get_hello(got_ip, got_port):
|
||||
failed = True
|
||||
if not client.post_hello(got_ip, got_port):
|
||||
@@ -122,7 +121,7 @@ def test_examples_protocol_http_server_advanced(env, extra_data):
|
||||
if not client.get_test_headers(got_ip, got_port):
|
||||
failed = True
|
||||
|
||||
Utility.console_log("Error code tests...")
|
||||
Utility.console_log('Error code tests...')
|
||||
if not client.code_500_server_error_test(got_ip, got_port):
|
||||
failed = True
|
||||
if not client.code_501_method_not_impl(got_ip, got_port):
|
||||
@@ -138,20 +137,20 @@ def test_examples_protocol_http_server_advanced(env, extra_data):
|
||||
if not client.code_408_req_timeout(got_ip, got_port):
|
||||
failed = True
|
||||
if not client.code_414_uri_too_long(got_ip, got_port, max_uri_len):
|
||||
Utility.console_log("Ignoring failure")
|
||||
Utility.console_log('Ignoring failure')
|
||||
if not client.code_431_hdr_too_long(got_ip, got_port, max_hdr_len):
|
||||
Utility.console_log("Ignoring failure")
|
||||
Utility.console_log('Ignoring failure')
|
||||
if not client.test_upgrade_not_supported(got_ip, got_port):
|
||||
failed = True
|
||||
|
||||
Utility.console_log("Getting final stack usage...")
|
||||
Utility.console_log('Getting final stack usage...')
|
||||
if not client.get_hello(got_ip, got_port):
|
||||
failed = True
|
||||
|
||||
final_stack = int(dut1.expect(re.compile(r"(?:[\s\S]*)Free Stack for server task: '(\d+)'"), timeout=15)[0])
|
||||
|
||||
if final_stack < 0.05 * max_stack_size:
|
||||
Utility.console_log("More than 95% of stack got used during tests")
|
||||
Utility.console_log('More than 95% of stack got used during tests')
|
||||
failed = True
|
||||
|
||||
if failed:
|
||||
|
||||
@@ -129,20 +129,17 @@
|
||||
# - Simple GET on /hello/restart_results (returns the leak results)
|
||||
|
||||
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
from builtins import str
|
||||
from builtins import range
|
||||
from builtins import object
|
||||
import threading
|
||||
import socket
|
||||
import time
|
||||
from __future__ import division, print_function
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import sys
|
||||
import string
|
||||
import random
|
||||
|
||||
import socket
|
||||
import string
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from builtins import object, range, str
|
||||
|
||||
try:
|
||||
import Utility
|
||||
@@ -151,7 +148,7 @@ except ImportError:
|
||||
|
||||
# This environment variable is expected on the host machine
|
||||
# > export TEST_FW_PATH=~/esp/esp-idf/tools/tiny-test-fw
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
test_fw_path = os.getenv('TEST_FW_PATH')
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
@@ -177,32 +174,32 @@ class Session(object):
|
||||
self.client.sendall(data.encode())
|
||||
except socket.error as err:
|
||||
self.client.close()
|
||||
Utility.console_log("Socket Error in send :", err)
|
||||
Utility.console_log('Socket Error in send :', err)
|
||||
rval = False
|
||||
return rval
|
||||
|
||||
def send_get(self, path, headers=None):
|
||||
request = "GET " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
request = 'GET ' + path + ' HTTP/1.1\r\nHost: ' + self.target
|
||||
if headers:
|
||||
for field, value in headers.items():
|
||||
request += "\r\n" + field + ": " + value
|
||||
request += "\r\n\r\n"
|
||||
request += '\r\n' + field + ': ' + value
|
||||
request += '\r\n\r\n'
|
||||
return self.send_err_check(request)
|
||||
|
||||
def send_put(self, path, data, headers=None):
|
||||
request = "PUT " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
request = 'PUT ' + path + ' HTTP/1.1\r\nHost: ' + self.target
|
||||
if headers:
|
||||
for field, value in headers.items():
|
||||
request += "\r\n" + field + ": " + value
|
||||
request += "\r\nContent-Length: " + str(len(data)) + "\r\n\r\n"
|
||||
request += '\r\n' + field + ': ' + value
|
||||
request += '\r\nContent-Length: ' + str(len(data)) + '\r\n\r\n'
|
||||
return self.send_err_check(request, data)
|
||||
|
||||
def send_post(self, path, data, headers=None):
|
||||
request = "POST " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
request = 'POST ' + path + ' HTTP/1.1\r\nHost: ' + self.target
|
||||
if headers:
|
||||
for field, value in headers.items():
|
||||
request += "\r\n" + field + ": " + value
|
||||
request += "\r\nContent-Length: " + str(len(data)) + "\r\n\r\n"
|
||||
request += '\r\n' + field + ': ' + value
|
||||
request += '\r\nContent-Length: ' + str(len(data)) + '\r\n\r\n'
|
||||
return self.send_err_check(request, data)
|
||||
|
||||
def read_resp_hdrs(self):
|
||||
@@ -246,7 +243,7 @@ class Session(object):
|
||||
return headers
|
||||
except socket.error as err:
|
||||
self.client.close()
|
||||
Utility.console_log("Socket Error in recv :", err)
|
||||
Utility.console_log('Socket Error in recv :', err)
|
||||
return None
|
||||
|
||||
def read_resp_data(self):
|
||||
@@ -275,9 +272,9 @@ class Session(object):
|
||||
rem_len -= len(new_data)
|
||||
chunk_data_buf = ''
|
||||
# Fetch remaining CRLF
|
||||
if self.client.recv(2) != "\r\n":
|
||||
if self.client.recv(2) != '\r\n':
|
||||
# Error in packet
|
||||
Utility.console_log("Error in chunked data")
|
||||
Utility.console_log('Error in chunked data')
|
||||
return None
|
||||
if not chunk_len:
|
||||
# If last chunk
|
||||
@@ -290,7 +287,7 @@ class Session(object):
|
||||
return read_data
|
||||
except socket.error as err:
|
||||
self.client.close()
|
||||
Utility.console_log("Socket Error in recv :", err)
|
||||
Utility.console_log('Socket Error in recv :', err)
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
@@ -299,10 +296,10 @@ class Session(object):
|
||||
|
||||
def test_val(text, expected, received):
|
||||
if expected != received:
|
||||
Utility.console_log(" Fail!")
|
||||
Utility.console_log(" [reason] " + text + ":")
|
||||
Utility.console_log(" expected: " + str(expected))
|
||||
Utility.console_log(" received: " + str(received))
|
||||
Utility.console_log(' Fail!')
|
||||
Utility.console_log(' [reason] ' + text + ':')
|
||||
Utility.console_log(' expected: ' + str(expected))
|
||||
Utility.console_log(' received: ' + str(received))
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -320,7 +317,7 @@ class adder_thread (threading.Thread):
|
||||
|
||||
# Pipeline 3 requests
|
||||
if (_verbose_):
|
||||
Utility.console_log(" Thread: Using adder start " + str(self.id))
|
||||
Utility.console_log(' Thread: Using adder start ' + str(self.id))
|
||||
|
||||
for _ in range(self.depth):
|
||||
self.session.send_post('/adder', str(self.id))
|
||||
@@ -332,10 +329,10 @@ class adder_thread (threading.Thread):
|
||||
|
||||
def adder_result(self):
|
||||
if len(self.response) != self.depth:
|
||||
Utility.console_log("Error : missing response packets")
|
||||
Utility.console_log('Error : missing response packets')
|
||||
return False
|
||||
for i in range(len(self.response)):
|
||||
if not test_val("Thread" + str(self.id) + " response[" + str(i) + "]",
|
||||
if not test_val('Thread' + str(self.id) + ' response[' + str(i) + ']',
|
||||
str(self.id * (i + 1)), str(self.response[i])):
|
||||
return False
|
||||
return True
|
||||
@@ -348,177 +345,177 @@ def get_hello(dut, port):
|
||||
# GET /hello should return 'Hello World!'
|
||||
Utility.console_log("[test] GET /hello returns 'Hello World!' =>", end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("GET", "/hello")
|
||||
conn.request('GET', '/hello')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 200, resp.status):
|
||||
if not test_val('status_code', 200, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
if not test_val("data", "Hello World!", resp.read().decode()):
|
||||
if not test_val('data', 'Hello World!', resp.read().decode()):
|
||||
conn.close()
|
||||
return False
|
||||
if not test_val("data", "text/html", resp.getheader('Content-Type')):
|
||||
if not test_val('data', 'text/html', resp.getheader('Content-Type')):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def put_hello(dut, port):
|
||||
# PUT /hello returns 405'
|
||||
Utility.console_log("[test] PUT /hello returns 405 =>", end=' ')
|
||||
Utility.console_log('[test] PUT /hello returns 405 =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("PUT", "/hello", "Hello")
|
||||
conn.request('PUT', '/hello', 'Hello')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 405, resp.status):
|
||||
if not test_val('status_code', 405, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def post_hello(dut, port):
|
||||
# POST /hello returns 405'
|
||||
Utility.console_log("[test] POST /hello returns 405 =>", end=' ')
|
||||
Utility.console_log('[test] POST /hello returns 405 =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("POST", "/hello", "Hello")
|
||||
conn.request('POST', '/hello', 'Hello')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 405, resp.status):
|
||||
if not test_val('status_code', 405, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def post_echo(dut, port):
|
||||
# POST /echo echoes data'
|
||||
Utility.console_log("[test] POST /echo echoes data =>", end=' ')
|
||||
Utility.console_log('[test] POST /echo echoes data =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("POST", "/echo", "Hello")
|
||||
conn.request('POST', '/echo', 'Hello')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 200, resp.status):
|
||||
if not test_val('status_code', 200, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
if not test_val("data", "Hello", resp.read().decode()):
|
||||
if not test_val('data', 'Hello', resp.read().decode()):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def put_echo(dut, port):
|
||||
# PUT /echo echoes data'
|
||||
Utility.console_log("[test] PUT /echo echoes data =>", end=' ')
|
||||
Utility.console_log('[test] PUT /echo echoes data =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("PUT", "/echo", "Hello")
|
||||
conn.request('PUT', '/echo', 'Hello')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 200, resp.status):
|
||||
if not test_val('status_code', 200, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
if not test_val("data", "Hello", resp.read().decode()):
|
||||
if not test_val('data', 'Hello', resp.read().decode()):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def get_echo(dut, port):
|
||||
# GET /echo returns 404'
|
||||
Utility.console_log("[test] GET /echo returns 405 =>", end=' ')
|
||||
Utility.console_log('[test] GET /echo returns 405 =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("GET", "/echo")
|
||||
conn.request('GET', '/echo')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 405, resp.status):
|
||||
if not test_val('status_code', 405, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def get_test_headers(dut, port):
|
||||
# GET /test_header returns data of Header2'
|
||||
Utility.console_log("[test] GET /test_header =>", end=' ')
|
||||
Utility.console_log('[test] GET /test_header =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
custom_header = {"Header1": "Value1", "Header3": "Value3"}
|
||||
header2_values = ["", " ", "Value2", " Value2", "Value2 ", " Value2 "]
|
||||
custom_header = {'Header1': 'Value1', 'Header3': 'Value3'}
|
||||
header2_values = ['', ' ', 'Value2', ' Value2', 'Value2 ', ' Value2 ']
|
||||
for val in header2_values:
|
||||
custom_header["Header2"] = val
|
||||
conn.request("GET", "/test_header", headers=custom_header)
|
||||
custom_header['Header2'] = val
|
||||
conn.request('GET', '/test_header', headers=custom_header)
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 200, resp.status):
|
||||
if not test_val('status_code', 200, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
hdr_val_start_idx = val.find("Value2")
|
||||
hdr_val_start_idx = val.find('Value2')
|
||||
if hdr_val_start_idx == -1:
|
||||
if not test_val("header: Header2", "", resp.read().decode()):
|
||||
if not test_val('header: Header2', '', resp.read().decode()):
|
||||
conn.close()
|
||||
return False
|
||||
else:
|
||||
if not test_val("header: Header2", val[hdr_val_start_idx:], resp.read().decode()):
|
||||
if not test_val('header: Header2', val[hdr_val_start_idx:], resp.read().decode()):
|
||||
conn.close()
|
||||
return False
|
||||
resp.read()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def get_hello_type(dut, port):
|
||||
# GET /hello/type_html returns text/html as Content-Type'
|
||||
Utility.console_log("[test] GET /hello/type_html has Content-Type of text/html =>", end=' ')
|
||||
Utility.console_log('[test] GET /hello/type_html has Content-Type of text/html =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("GET", "/hello/type_html")
|
||||
conn.request('GET', '/hello/type_html')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 200, resp.status):
|
||||
if not test_val('status_code', 200, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
if not test_val("data", "Hello World!", resp.read().decode()):
|
||||
if not test_val('data', 'Hello World!', resp.read().decode()):
|
||||
conn.close()
|
||||
return False
|
||||
if not test_val("data", "text/html", resp.getheader('Content-Type')):
|
||||
if not test_val('data', 'text/html', resp.getheader('Content-Type')):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def get_hello_status(dut, port):
|
||||
# GET /hello/status_500 returns status 500'
|
||||
Utility.console_log("[test] GET /hello/status_500 returns status 500 =>", end=' ')
|
||||
Utility.console_log('[test] GET /hello/status_500 returns status 500 =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("GET", "/hello/status_500")
|
||||
conn.request('GET', '/hello/status_500')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 500, resp.status):
|
||||
if not test_val('status_code', 500, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def get_false_uri(dut, port):
|
||||
# GET /false_uri returns status 404'
|
||||
Utility.console_log("[test] GET /false_uri returns status 404 =>", end=' ')
|
||||
Utility.console_log('[test] GET /false_uri returns status 404 =>', end=' ')
|
||||
conn = http.client.HTTPConnection(dut, int(port), timeout=15)
|
||||
conn.request("GET", "/false_uri")
|
||||
conn.request('GET', '/false_uri')
|
||||
resp = conn.getresponse()
|
||||
if not test_val("status_code", 404, resp.status):
|
||||
if not test_val('status_code', 404, resp.status):
|
||||
conn.close()
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def parallel_sessions_adder(dut, port, max_sessions):
|
||||
# POSTs on /adder in parallel sessions
|
||||
Utility.console_log("[test] POST {pipelined} on /adder in " + str(max_sessions) + " sessions =>", end=' ')
|
||||
Utility.console_log('[test] POST {pipelined} on /adder in ' + str(max_sessions) + ' sessions =>', end=' ')
|
||||
t = []
|
||||
# Create all sessions
|
||||
for i in range(max_sessions):
|
||||
@@ -532,90 +529,90 @@ def parallel_sessions_adder(dut, port, max_sessions):
|
||||
|
||||
res = True
|
||||
for i in range(len(t)):
|
||||
if not test_val("Thread" + str(i) + " Failed", t[i].adder_result(), True):
|
||||
if not test_val('Thread' + str(i) + ' Failed', t[i].adder_result(), True):
|
||||
res = False
|
||||
t[i].close()
|
||||
if (res):
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return res
|
||||
|
||||
|
||||
def async_response_test(dut, port):
|
||||
# Test that an asynchronous work is executed in the HTTPD's context
|
||||
# This is tested by reading two responses over the same session
|
||||
Utility.console_log("[test] Test HTTPD Work Queue (Async response) =>", end=' ')
|
||||
Utility.console_log('[test] Test HTTPD Work Queue (Async response) =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
|
||||
s.send_get('/async_data')
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("First Response", "Hello World!", s.read_resp_data()):
|
||||
if not test_val('First Response', 'Hello World!', s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("Second Response", "Hello Double World!", s.read_resp_data()):
|
||||
if not test_val('Second Response', 'Hello Double World!', s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def leftover_data_test(dut, port):
|
||||
# Leftover data in POST is purged (valid and invalid URIs)
|
||||
Utility.console_log("[test] Leftover data in POST is purged (valid and invalid URIs) =>", end=' ')
|
||||
s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
|
||||
Utility.console_log('[test] Leftover data in POST is purged (valid and invalid URIs) =>', end=' ')
|
||||
s = http.client.HTTPConnection(dut + ':' + port, timeout=15)
|
||||
|
||||
s.request("POST", url='/leftover_data', body="abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
|
||||
s.request('POST', url='/leftover_data', body='abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz')
|
||||
resp = s.getresponse()
|
||||
if not test_val("Partial data", "abcdefghij", resp.read().decode()):
|
||||
if not test_val('Partial data', 'abcdefghij', resp.read().decode()):
|
||||
s.close()
|
||||
return False
|
||||
|
||||
s.request("GET", url='/hello')
|
||||
s.request('GET', url='/hello')
|
||||
resp = s.getresponse()
|
||||
if not test_val("Hello World Data", "Hello World!", resp.read().decode()):
|
||||
if not test_val('Hello World Data', 'Hello World!', resp.read().decode()):
|
||||
s.close()
|
||||
return False
|
||||
|
||||
s.request("POST", url='/false_uri', body="abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
|
||||
s.request('POST', url='/false_uri', body='abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz')
|
||||
resp = s.getresponse()
|
||||
if not test_val("False URI Status", str(404), str(resp.status)):
|
||||
if not test_val('False URI Status', str(404), str(resp.status)):
|
||||
s.close()
|
||||
return False
|
||||
# socket would have been closed by server due to error
|
||||
s.close()
|
||||
|
||||
s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
|
||||
s.request("GET", url='/hello')
|
||||
s = http.client.HTTPConnection(dut + ':' + port, timeout=15)
|
||||
s.request('GET', url='/hello')
|
||||
resp = s.getresponse()
|
||||
if not test_val("Hello World Data", "Hello World!", resp.read().decode()):
|
||||
if not test_val('Hello World Data', 'Hello World!', resp.read().decode()):
|
||||
s.close()
|
||||
return False
|
||||
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def spillover_session(dut, port, max_sess):
|
||||
# Session max_sess_sessions + 1 is rejected
|
||||
Utility.console_log("[test] Session max_sess_sessions (" + str(max_sess) + ") + 1 is rejected =>", end=' ')
|
||||
Utility.console_log('[test] Session max_sess_sessions (' + str(max_sess) + ') + 1 is rejected =>', end=' ')
|
||||
s = []
|
||||
_verbose_ = True
|
||||
for i in range(max_sess + 1):
|
||||
if (_verbose_):
|
||||
Utility.console_log("Executing " + str(i))
|
||||
Utility.console_log('Executing ' + str(i))
|
||||
try:
|
||||
a = http.client.HTTPConnection(dut + ":" + port, timeout=15)
|
||||
a.request("GET", url='/hello')
|
||||
a = http.client.HTTPConnection(dut + ':' + port, timeout=15)
|
||||
a.request('GET', url='/hello')
|
||||
resp = a.getresponse()
|
||||
if not test_val("Connection " + str(i), "Hello World!", resp.read().decode()):
|
||||
if not test_val('Connection ' + str(i), 'Hello World!', resp.read().decode()):
|
||||
a.close()
|
||||
break
|
||||
s.append(a)
|
||||
except Exception:
|
||||
if (_verbose_):
|
||||
Utility.console_log("Connection " + str(i) + " rejected")
|
||||
Utility.console_log('Connection ' + str(i) + ' rejected')
|
||||
a.close()
|
||||
break
|
||||
|
||||
@@ -624,134 +621,134 @@ def spillover_session(dut, port, max_sess):
|
||||
a.close()
|
||||
|
||||
# Check if number of connections is equal to max_sess
|
||||
Utility.console_log(["Fail","Success"][len(s) == max_sess])
|
||||
Utility.console_log(['Fail','Success'][len(s) == max_sess])
|
||||
return (len(s) == max_sess)
|
||||
|
||||
|
||||
def recv_timeout_test(dut, port):
|
||||
Utility.console_log("[test] Timeout occurs if partial packet sent =>", end=' ')
|
||||
Utility.console_log('[test] Timeout occurs if partial packet sent =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
s.client.sendall(b"GE")
|
||||
s.client.sendall(b'GE')
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
if not test_val("Request Timeout", "Server closed this connection", resp):
|
||||
if not test_val('Request Timeout', 'Server closed this connection', resp):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def packet_size_limit_test(dut, port, test_size):
|
||||
Utility.console_log("[test] send size limit test =>", end=' ')
|
||||
Utility.console_log('[test] send size limit test =>', end=' ')
|
||||
retry = 5
|
||||
while (retry):
|
||||
retry -= 1
|
||||
Utility.console_log("data size = ", test_size)
|
||||
s = http.client.HTTPConnection(dut + ":" + port, timeout=15)
|
||||
Utility.console_log('data size = ', test_size)
|
||||
s = http.client.HTTPConnection(dut + ':' + port, timeout=15)
|
||||
random_data = ''.join(string.printable[random.randint(0,len(string.printable)) - 1] for _ in list(range(test_size)))
|
||||
path = "/echo"
|
||||
s.request("POST", url=path, body=random_data)
|
||||
path = '/echo'
|
||||
s.request('POST', url=path, body=random_data)
|
||||
resp = s.getresponse()
|
||||
if not test_val("Error", "200", str(resp.status)):
|
||||
if test_val("Error", "500", str(resp.status)):
|
||||
Utility.console_log("Data too large to be allocated")
|
||||
if not test_val('Error', '200', str(resp.status)):
|
||||
if test_val('Error', '500', str(resp.status)):
|
||||
Utility.console_log('Data too large to be allocated')
|
||||
test_size = test_size // 10
|
||||
else:
|
||||
Utility.console_log("Unexpected error")
|
||||
Utility.console_log('Unexpected error')
|
||||
s.close()
|
||||
Utility.console_log("Retry...")
|
||||
Utility.console_log('Retry...')
|
||||
continue
|
||||
resp = resp.read().decode()
|
||||
result = (resp == random_data)
|
||||
if not result:
|
||||
test_val("Data size", str(len(random_data)), str(len(resp)))
|
||||
test_val('Data size', str(len(random_data)), str(len(resp)))
|
||||
s.close()
|
||||
Utility.console_log("Retry...")
|
||||
Utility.console_log('Retry...')
|
||||
continue
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
Utility.console_log("Failed")
|
||||
Utility.console_log('Failed')
|
||||
return False
|
||||
|
||||
|
||||
def arbitrary_termination_test(dut, port):
|
||||
Utility.console_log("[test] Arbitrary termination test =>", end=' ')
|
||||
Utility.console_log('[test] Arbitrary termination test =>', end=' ')
|
||||
cases = [
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: SomeValue\r\n\r\n",
|
||||
"code": "200",
|
||||
"header": "SomeValue"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nCustom: SomeValue\r\n\r\n',
|
||||
'code': '200',
|
||||
'header': 'SomeValue'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\nHost: " + dut + "\r\nCustom: SomeValue\r\n\r\n",
|
||||
"code": "200",
|
||||
"header": "SomeValue"
|
||||
'request': 'POST /echo HTTP/1.1\nHost: ' + dut + '\r\nCustom: SomeValue\r\n\r\n',
|
||||
'code': '200',
|
||||
'header': 'SomeValue'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\nCustom: SomeValue\r\n\r\n",
|
||||
"code": "200",
|
||||
"header": "SomeValue"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\nCustom: SomeValue\r\n\r\n',
|
||||
'code': '200',
|
||||
'header': 'SomeValue'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: SomeValue\n\r\n",
|
||||
"code": "200",
|
||||
"header": "SomeValue"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nCustom: SomeValue\n\r\n',
|
||||
'code': '200',
|
||||
'header': 'SomeValue'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: SomeValue\r\n\n",
|
||||
"code": "200",
|
||||
"header": "SomeValue"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nCustom: SomeValue\r\n\n',
|
||||
'code': '200',
|
||||
'header': 'SomeValue'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\nHost: " + dut + "\nCustom: SomeValue\n\n",
|
||||
"code": "200",
|
||||
"header": "SomeValue"
|
||||
'request': 'POST /echo HTTP/1.1\nHost: ' + dut + '\nCustom: SomeValue\n\n',
|
||||
'code': '200',
|
||||
'header': 'SomeValue'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\n\r\nABCDE",
|
||||
"code": "200",
|
||||
"body": "ABCDE"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nContent-Length: 5\n\r\nABCDE',
|
||||
'code': '200',
|
||||
'body': 'ABCDE'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\r\n\nABCDE",
|
||||
"code": "200",
|
||||
"body": "ABCDE"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nContent-Length: 5\r\n\nABCDE',
|
||||
'code': '200',
|
||||
'body': 'ABCDE'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\n\nABCDE",
|
||||
"code": "200",
|
||||
"body": "ABCDE"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nContent-Length: 5\n\nABCDE',
|
||||
'code': '200',
|
||||
'body': 'ABCDE'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 5\n\n\rABCD",
|
||||
"code": "200",
|
||||
"body": "\rABCD"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nContent-Length: 5\n\n\rABCD',
|
||||
'code': '200',
|
||||
'body': '\rABCD'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\r\nCustom: SomeValue\r\r\n\r\r\n",
|
||||
"code": "400"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\r\nCustom: SomeValue\r\r\n\r\r\n',
|
||||
'code': '400'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\r\nHost: " + dut + "\r\n\r\n",
|
||||
"code": "400"
|
||||
'request': 'POST /echo HTTP/1.1\r\r\nHost: ' + dut + '\r\n\r\n',
|
||||
'code': '400'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\n\rHost: " + dut + "\r\n\r\n",
|
||||
"code": "400"
|
||||
'request': 'POST /echo HTTP/1.1\r\n\rHost: ' + dut + '\r\n\r\n',
|
||||
'code': '400'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\rCustom: SomeValue\r\n",
|
||||
"code": "400"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\rCustom: SomeValue\r\n',
|
||||
'code': '400'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom: Some\rValue\r\n",
|
||||
"code": "400"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nCustom: Some\rValue\r\n',
|
||||
'code': '400'
|
||||
},
|
||||
{
|
||||
"request": "POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nCustom- SomeValue\r\n\r\n",
|
||||
"code": "400"
|
||||
'request': 'POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nCustom- SomeValue\r\n\r\n',
|
||||
'code': '400'
|
||||
}
|
||||
]
|
||||
for case in cases:
|
||||
@@ -760,159 +757,159 @@ def arbitrary_termination_test(dut, port):
|
||||
resp_hdrs = s.read_resp_hdrs()
|
||||
resp_body = s.read_resp_data()
|
||||
s.close()
|
||||
if not test_val("Response Code", case["code"], s.status):
|
||||
if not test_val('Response Code', case['code'], s.status):
|
||||
return False
|
||||
if "header" in case.keys():
|
||||
if 'header' in case.keys():
|
||||
resp_hdr_val = None
|
||||
if "Custom" in resp_hdrs.keys():
|
||||
resp_hdr_val = resp_hdrs["Custom"]
|
||||
if not test_val("Response Header", case["header"], resp_hdr_val):
|
||||
if 'Custom' in resp_hdrs.keys():
|
||||
resp_hdr_val = resp_hdrs['Custom']
|
||||
if not test_val('Response Header', case['header'], resp_hdr_val):
|
||||
return False
|
||||
if "body" in case.keys():
|
||||
if not test_val("Response Body", case["body"], resp_body):
|
||||
if 'body' in case.keys():
|
||||
if not test_val('Response Body', case['body'], resp_body):
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_500_server_error_test(dut, port):
|
||||
Utility.console_log("[test] 500 Server Error test =>", end=' ')
|
||||
Utility.console_log('[test] 500 Server Error test =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
# Sending a very large content length will cause malloc to fail
|
||||
content_len = 2**30
|
||||
s.client.sendall(("POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: " + str(content_len) + "\r\n\r\nABCD").encode())
|
||||
s.client.sendall(('POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nContent-Length: ' + str(content_len) + '\r\n\r\nABCD').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Server Error", "500", s.status):
|
||||
if not test_val('Server Error', '500', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_501_method_not_impl(dut, port):
|
||||
Utility.console_log("[test] 501 Method Not Implemented =>", end=' ')
|
||||
Utility.console_log('[test] 501 Method Not Implemented =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.sendall(("ABC " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
|
||||
path = '/hello'
|
||||
s.client.sendall(('ABC ' + path + ' HTTP/1.1\r\nHost: ' + dut + '\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
# Presently server sends back 400 Bad Request
|
||||
# if not test_val("Server Error", "501", s.status):
|
||||
# s.close()
|
||||
# return False
|
||||
if not test_val("Server Error", "400", s.status):
|
||||
if not test_val('Server Error', '400', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_505_version_not_supported(dut, port):
|
||||
Utility.console_log("[test] 505 Version Not Supported =>", end=' ')
|
||||
Utility.console_log('[test] 505 Version Not Supported =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.sendall(("GET " + path + " HTTP/2.0\r\nHost: " + dut + "\r\n\r\n").encode())
|
||||
path = '/hello'
|
||||
s.client.sendall(('GET ' + path + ' HTTP/2.0\r\nHost: ' + dut + '\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Server Error", "505", s.status):
|
||||
if not test_val('Server Error', '505', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_400_bad_request(dut, port):
|
||||
Utility.console_log("[test] 400 Bad Request =>", end=' ')
|
||||
Utility.console_log('[test] 400 Bad Request =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.sendall(("XYZ " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
|
||||
path = '/hello'
|
||||
s.client.sendall(('XYZ ' + path + ' HTTP/1.1\r\nHost: ' + dut + '\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Client Error", "400", s.status):
|
||||
if not test_val('Client Error', '400', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_404_not_found(dut, port):
|
||||
Utility.console_log("[test] 404 Not Found =>", end=' ')
|
||||
Utility.console_log('[test] 404 Not Found =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
path = "/dummy"
|
||||
s.client.sendall(("GET " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
|
||||
path = '/dummy'
|
||||
s.client.sendall(('GET ' + path + ' HTTP/1.1\r\nHost: ' + dut + '\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Client Error", "404", s.status):
|
||||
if not test_val('Client Error', '404', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_405_method_not_allowed(dut, port):
|
||||
Utility.console_log("[test] 405 Method Not Allowed =>", end=' ')
|
||||
Utility.console_log('[test] 405 Method Not Allowed =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.sendall(("POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n").encode())
|
||||
path = '/hello'
|
||||
s.client.sendall(('POST ' + path + ' HTTP/1.1\r\nHost: ' + dut + '\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Client Error", "405", s.status):
|
||||
if not test_val('Client Error', '405', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_408_req_timeout(dut, port):
|
||||
Utility.console_log("[test] 408 Request Timeout =>", end=' ')
|
||||
Utility.console_log('[test] 408 Request Timeout =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
s.client.sendall(("POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 10\r\n\r\nABCD").encode())
|
||||
s.client.sendall(('POST /echo HTTP/1.1\r\nHost: ' + dut + '\r\nContent-Length: 10\r\n\r\nABCD').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Client Error", "408", s.status):
|
||||
if not test_val('Client Error', '408', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def code_411_length_required(dut, port):
|
||||
Utility.console_log("[test] 411 Length Required =>", end=' ')
|
||||
Utility.console_log('[test] 411 Length Required =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
path = "/echo"
|
||||
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())
|
||||
path = '/echo'
|
||||
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())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
# Presently server sends back 400 Bad Request
|
||||
# if not test_val("Client Error", "411", s.status):
|
||||
# s.close()
|
||||
# return False
|
||||
if not test_val("Client Error", "400", s.status):
|
||||
if not test_val('Client Error', '400', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def send_getx_uri_len(dut, port, length):
|
||||
s = Session(dut, port)
|
||||
method = "GET "
|
||||
version = " HTTP/1.1\r\n"
|
||||
path = "/" + "x" * (length - len(method) - len(version) - len("/"))
|
||||
method = 'GET '
|
||||
version = ' HTTP/1.1\r\n'
|
||||
path = '/' + 'x' * (length - len(method) - len(version) - len('/'))
|
||||
s.client.sendall(method.encode())
|
||||
time.sleep(1)
|
||||
s.client.sendall(path.encode())
|
||||
time.sleep(1)
|
||||
s.client.sendall((version + "Host: " + dut + "\r\n\r\n").encode())
|
||||
s.client.sendall((version + 'Host: ' + dut + '\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
s.close()
|
||||
@@ -920,59 +917,59 @@ def send_getx_uri_len(dut, port, length):
|
||||
|
||||
|
||||
def code_414_uri_too_long(dut, port, max_uri_len):
|
||||
Utility.console_log("[test] 414 URI Too Long =>", end=' ')
|
||||
Utility.console_log('[test] 414 URI Too Long =>', end=' ')
|
||||
status = send_getx_uri_len(dut, port, max_uri_len)
|
||||
if not test_val("Client Error", "404", status):
|
||||
if not test_val('Client Error', '404', status):
|
||||
return False
|
||||
status = send_getx_uri_len(dut, port, max_uri_len + 1)
|
||||
if not test_val("Client Error", "414", status):
|
||||
if not test_val('Client Error', '414', status):
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def send_postx_hdr_len(dut, port, length):
|
||||
s = Session(dut, port)
|
||||
path = "/echo"
|
||||
host = "Host: " + dut
|
||||
custom_hdr_field = "\r\nCustom: "
|
||||
custom_hdr_val = "x" * (length - len(host) - len(custom_hdr_field) - len("\r\n\r\n") + len("0"))
|
||||
request = ("POST " + path + " HTTP/1.1\r\n" + host + custom_hdr_field + custom_hdr_val + "\r\n\r\n").encode()
|
||||
path = '/echo'
|
||||
host = 'Host: ' + dut
|
||||
custom_hdr_field = '\r\nCustom: '
|
||||
custom_hdr_val = 'x' * (length - len(host) - len(custom_hdr_field) - len('\r\n\r\n') + len('0'))
|
||||
request = ('POST ' + path + ' HTTP/1.1\r\n' + host + custom_hdr_field + custom_hdr_val + '\r\n\r\n').encode()
|
||||
s.client.sendall(request[:length // 2])
|
||||
time.sleep(1)
|
||||
s.client.sendall(request[length // 2:])
|
||||
hdr = s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
s.close()
|
||||
if hdr and ("Custom" in hdr):
|
||||
return (hdr["Custom"] == custom_hdr_val), resp
|
||||
if hdr and ('Custom' in hdr):
|
||||
return (hdr['Custom'] == custom_hdr_val), resp
|
||||
return False, s.status
|
||||
|
||||
|
||||
def code_431_hdr_too_long(dut, port, max_hdr_len):
|
||||
Utility.console_log("[test] 431 Header Too Long =>", end=' ')
|
||||
Utility.console_log('[test] 431 Header Too Long =>', end=' ')
|
||||
res, status = send_postx_hdr_len(dut, port, max_hdr_len)
|
||||
if not res:
|
||||
return False
|
||||
res, status = send_postx_hdr_len(dut, port, max_hdr_len + 1)
|
||||
if not test_val("Client Error", "431", status):
|
||||
if not test_val('Client Error', '431', status):
|
||||
return False
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
def test_upgrade_not_supported(dut, port):
|
||||
Utility.console_log("[test] Upgrade Not Supported =>", end=' ')
|
||||
Utility.console_log('[test] Upgrade Not Supported =>', end=' ')
|
||||
s = Session(dut, port)
|
||||
# path = "/hello"
|
||||
s.client.sendall(("OPTIONS * HTTP/1.1\r\nHost:" + dut + "\r\nUpgrade: TLS/1.0\r\nConnection: Upgrade\r\n\r\n").encode())
|
||||
s.client.sendall(('OPTIONS * HTTP/1.1\r\nHost:' + dut + '\r\nUpgrade: TLS/1.0\r\nConnection: Upgrade\r\n\r\n').encode())
|
||||
s.read_resp_hdrs()
|
||||
s.read_resp_data()
|
||||
if not test_val("Client Error", "400", s.status):
|
||||
if not test_val('Client Error', '400', s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
Utility.console_log("Success")
|
||||
Utility.console_log('Success')
|
||||
return True
|
||||
|
||||
|
||||
@@ -997,7 +994,7 @@ if __name__ == '__main__':
|
||||
|
||||
_verbose_ = True
|
||||
|
||||
Utility.console_log("### Basic HTTP Client Tests")
|
||||
Utility.console_log('### Basic HTTP Client Tests')
|
||||
get_hello(dut, port)
|
||||
post_hello(dut, port)
|
||||
put_hello(dut, port)
|
||||
@@ -1009,7 +1006,7 @@ if __name__ == '__main__':
|
||||
get_false_uri(dut, port)
|
||||
get_test_headers(dut, port)
|
||||
|
||||
Utility.console_log("### Error code tests")
|
||||
Utility.console_log('### Error code tests')
|
||||
code_500_server_error_test(dut, port)
|
||||
code_501_method_not_impl(dut, port)
|
||||
code_505_version_not_supported(dut, port)
|
||||
@@ -1024,7 +1021,7 @@ if __name__ == '__main__':
|
||||
# Not supported yet (Error on chunked request)
|
||||
# code_411_length_required(dut, port)
|
||||
|
||||
Utility.console_log("### Sessions and Context Tests")
|
||||
Utility.console_log('### Sessions and Context Tests')
|
||||
parallel_sessions_adder(dut, port, max_sessions)
|
||||
leftover_data_test(dut, port)
|
||||
async_response_test(dut, port)
|
||||
|
||||
@@ -14,49 +14,47 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
from builtins import range
|
||||
import re
|
||||
from __future__ import division, print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from builtins import range, str
|
||||
|
||||
from tiny_test_fw import Utility
|
||||
import ttfw_idf
|
||||
from idf_http_server_test import adder as client
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
# When running on local machine execute the following before running this script
|
||||
# > make app bootloader
|
||||
# > make print_flash_cmd | tail -n 1 > build/download.config
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_http_server_persistence(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/persistent_sockets",
|
||||
dut1 = env.get_dut('http_server', 'examples/protocols/http_server/persistent_sockets',
|
||||
dut_class=ttfw_idf.ESP32DUT)
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "persistent_sockets.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'persistent_sockets.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("http_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('http_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# Upload binary and start testing
|
||||
Utility.console_log("Starting http_server persistance test app")
|
||||
Utility.console_log('Starting http_server persistance test app')
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
Utility.console_log("Waiting to connect with AP")
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
Utility.console_log('Waiting to connect with AP')
|
||||
got_ip = dut1.expect(re.compile(r'(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=30)[0]
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: '(\d+)'"), timeout=30)[0]
|
||||
|
||||
Utility.console_log("Got IP : " + got_ip)
|
||||
Utility.console_log("Got Port : " + got_port)
|
||||
Utility.console_log('Got IP : ' + got_ip)
|
||||
Utility.console_log('Got Port : ' + got_port)
|
||||
|
||||
# Expected Logs
|
||||
dut1.expect("Registering URI handlers", timeout=30)
|
||||
dut1.expect('Registering URI handlers', timeout=30)
|
||||
|
||||
# Run test script
|
||||
conn = client.start_session(got_ip, got_port)
|
||||
@@ -65,23 +63,23 @@ def test_examples_protocol_http_server_persistence(env, extra_data):
|
||||
|
||||
# Test PUT request and initialize session context
|
||||
num = random.randint(0,100)
|
||||
client.putreq(conn, "/adder", str(num))
|
||||
client.putreq(conn, '/adder', str(num))
|
||||
visitor += 1
|
||||
dut1.expect("/adder visitor count = " + str(visitor), timeout=30)
|
||||
dut1.expect("/adder PUT handler read " + str(num), timeout=30)
|
||||
dut1.expect("PUT allocating new session", timeout=30)
|
||||
dut1.expect('/adder visitor count = ' + str(visitor), timeout=30)
|
||||
dut1.expect('/adder PUT handler read ' + str(num), timeout=30)
|
||||
dut1.expect('PUT allocating new session', timeout=30)
|
||||
|
||||
# Retest PUT request and change session context value
|
||||
num = random.randint(0,100)
|
||||
Utility.console_log("Adding: " + str(num))
|
||||
client.putreq(conn, "/adder", str(num))
|
||||
Utility.console_log('Adding: ' + str(num))
|
||||
client.putreq(conn, '/adder', str(num))
|
||||
visitor += 1
|
||||
adder += num
|
||||
dut1.expect("/adder visitor count = " + str(visitor), timeout=30)
|
||||
dut1.expect("/adder PUT handler read " + str(num), timeout=30)
|
||||
dut1.expect('/adder visitor count = ' + str(visitor), timeout=30)
|
||||
dut1.expect('/adder PUT handler read ' + str(num), timeout=30)
|
||||
try:
|
||||
# Re allocation shouldn't happen
|
||||
dut1.expect("PUT allocating new session", timeout=30)
|
||||
dut1.expect('PUT allocating new session', timeout=30)
|
||||
# Not expected
|
||||
raise RuntimeError
|
||||
except Exception:
|
||||
@@ -91,37 +89,37 @@ def test_examples_protocol_http_server_persistence(env, extra_data):
|
||||
# Test POST request and session persistence
|
||||
random_nums = [random.randint(0,100) for _ in range(100)]
|
||||
for num in random_nums:
|
||||
Utility.console_log("Adding: " + str(num))
|
||||
client.postreq(conn, "/adder", str(num))
|
||||
Utility.console_log('Adding: ' + str(num))
|
||||
client.postreq(conn, '/adder', str(num))
|
||||
visitor += 1
|
||||
adder += num
|
||||
dut1.expect("/adder visitor count = " + str(visitor), timeout=30)
|
||||
dut1.expect("/adder handler read " + str(num), timeout=30)
|
||||
dut1.expect('/adder visitor count = ' + str(visitor), timeout=30)
|
||||
dut1.expect('/adder handler read ' + str(num), timeout=30)
|
||||
|
||||
# Test GET request and session persistence
|
||||
Utility.console_log("Matching final sum: " + str(adder))
|
||||
if client.getreq(conn, "/adder").decode() != str(adder):
|
||||
Utility.console_log('Matching final sum: ' + str(adder))
|
||||
if client.getreq(conn, '/adder').decode() != str(adder):
|
||||
raise RuntimeError
|
||||
visitor += 1
|
||||
dut1.expect("/adder visitor count = " + str(visitor), timeout=30)
|
||||
dut1.expect("/adder GET handler send " + str(adder), timeout=30)
|
||||
dut1.expect('/adder visitor count = ' + str(visitor), timeout=30)
|
||||
dut1.expect('/adder GET handler send ' + str(adder), timeout=30)
|
||||
|
||||
Utility.console_log("Ending session")
|
||||
Utility.console_log('Ending session')
|
||||
# Close connection and check for invocation of context "Free" function
|
||||
client.end_session(conn)
|
||||
dut1.expect("/adder Free Context function called", timeout=30)
|
||||
dut1.expect('/adder Free Context function called', timeout=30)
|
||||
|
||||
Utility.console_log("Validating user context data")
|
||||
Utility.console_log('Validating user context data')
|
||||
# Start another session to check user context data
|
||||
client.start_session(got_ip, got_port)
|
||||
num = random.randint(0,100)
|
||||
client.putreq(conn, "/adder", str(num))
|
||||
client.putreq(conn, '/adder', str(num))
|
||||
visitor += 1
|
||||
dut1.expect("/adder visitor count = " + str(visitor), timeout=30)
|
||||
dut1.expect("/adder PUT handler read " + str(num), timeout=30)
|
||||
dut1.expect("PUT allocating new session", timeout=30)
|
||||
dut1.expect('/adder visitor count = ' + str(visitor), timeout=30)
|
||||
dut1.expect('/adder PUT handler read ' + str(num), timeout=30)
|
||||
dut1.expect('PUT allocating new session', timeout=30)
|
||||
client.end_session(conn)
|
||||
dut1.expect("/adder Free Context function called", timeout=30)
|
||||
dut1.expect('/adder Free Context function called', timeout=30)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -14,22 +14,20 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import range
|
||||
import re
|
||||
import os
|
||||
import string
|
||||
import random
|
||||
from __future__ import division, print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import socket
|
||||
import string
|
||||
import threading
|
||||
import time
|
||||
import socket
|
||||
from builtins import range
|
||||
|
||||
from tiny_test_fw import Utility
|
||||
import ttfw_idf
|
||||
from idf_http_server_test import client
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
|
||||
class http_client_thread(threading.Thread):
|
||||
@@ -64,97 +62,97 @@ class http_client_thread(threading.Thread):
|
||||
# > make print_flash_cmd | tail -n 1 > build/download.config
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_http_server_simple(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/simple", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('http_server', 'examples/protocols/http_server/simple', dut_class=ttfw_idf.ESP32DUT)
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "simple.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'simple.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("http_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('http_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# Upload binary and start testing
|
||||
Utility.console_log("Starting http_server simple test app")
|
||||
Utility.console_log('Starting http_server simple test app')
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
Utility.console_log("Waiting to connect with AP")
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
Utility.console_log('Waiting to connect with AP')
|
||||
got_ip = dut1.expect(re.compile(r'(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=30)[0]
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: '(\d+)'"), timeout=30)[0]
|
||||
|
||||
Utility.console_log("Got IP : " + got_ip)
|
||||
Utility.console_log("Got Port : " + got_port)
|
||||
Utility.console_log('Got IP : ' + got_ip)
|
||||
Utility.console_log('Got Port : ' + got_port)
|
||||
|
||||
# Expected Logs
|
||||
dut1.expect("Registering URI handlers", timeout=30)
|
||||
dut1.expect('Registering URI handlers', timeout=30)
|
||||
|
||||
# Run test script
|
||||
# If failed raise appropriate exception
|
||||
Utility.console_log("Test /hello GET handler")
|
||||
Utility.console_log('Test /hello GET handler')
|
||||
if not client.test_get_handler(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
# Acquire host IP. Need a way to check it
|
||||
dut1.expect(re.compile(r"(?:[\s\S]*)Found header => Host: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
dut1.expect(re.compile(r'(?:[\s\S]*)Found header => Host: (\d+.\d+.\d+.\d+)'), timeout=30)[0]
|
||||
|
||||
# Match additional headers sent in the request
|
||||
dut1.expect("Found header => Test-Header-2: Test-Value-2", timeout=30)
|
||||
dut1.expect("Found header => Test-Header-1: Test-Value-1", timeout=30)
|
||||
dut1.expect("Found URL query parameter => query1=value1", timeout=30)
|
||||
dut1.expect("Found URL query parameter => query3=value3", timeout=30)
|
||||
dut1.expect("Found URL query parameter => query2=value2", timeout=30)
|
||||
dut1.expect("Request headers lost", timeout=30)
|
||||
dut1.expect('Found header => Test-Header-2: Test-Value-2', timeout=30)
|
||||
dut1.expect('Found header => Test-Header-1: Test-Value-1', timeout=30)
|
||||
dut1.expect('Found URL query parameter => query1=value1', timeout=30)
|
||||
dut1.expect('Found URL query parameter => query3=value3', timeout=30)
|
||||
dut1.expect('Found URL query parameter => query2=value2', timeout=30)
|
||||
dut1.expect('Request headers lost', timeout=30)
|
||||
|
||||
Utility.console_log("Test /ctrl PUT handler and realtime handler de/registration")
|
||||
Utility.console_log('Test /ctrl PUT handler and realtime handler de/registration')
|
||||
if not client.test_put_handler(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
dut1.expect("Unregistering /hello and /echo URIs", timeout=30)
|
||||
dut1.expect("Registering /hello and /echo URIs", timeout=30)
|
||||
dut1.expect('Unregistering /hello and /echo URIs', timeout=30)
|
||||
dut1.expect('Registering /hello and /echo URIs', timeout=30)
|
||||
|
||||
# Generate random data of 10KB
|
||||
random_data = ''.join(string.printable[random.randint(0,len(string.printable)) - 1] for _ in range(10 * 1024))
|
||||
Utility.console_log("Test /echo POST handler with random data")
|
||||
Utility.console_log('Test /echo POST handler with random data')
|
||||
if not client.test_post_handler(got_ip, got_port, random_data):
|
||||
raise RuntimeError
|
||||
|
||||
query = "http://foobar"
|
||||
Utility.console_log("Test /hello with custom query : " + query)
|
||||
query = 'http://foobar'
|
||||
Utility.console_log('Test /hello with custom query : ' + query)
|
||||
if not client.test_custom_uri_query(got_ip, got_port, query):
|
||||
raise RuntimeError
|
||||
dut1.expect("Found URL query => " + query, timeout=30)
|
||||
dut1.expect('Found URL query => ' + query, timeout=30)
|
||||
|
||||
query = "abcd+1234%20xyz"
|
||||
Utility.console_log("Test /hello with custom query : " + query)
|
||||
query = 'abcd+1234%20xyz'
|
||||
Utility.console_log('Test /hello with custom query : ' + query)
|
||||
if not client.test_custom_uri_query(got_ip, got_port, query):
|
||||
raise RuntimeError
|
||||
dut1.expect("Found URL query => " + query, timeout=30)
|
||||
dut1.expect('Found URL query => ' + query, timeout=30)
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_http_server_lru_purge_enable(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/simple", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('http_server', 'examples/protocols/http_server/simple', dut_class=ttfw_idf.ESP32DUT)
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "simple.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'simple.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("http_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('http_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# Upload binary and start testing
|
||||
Utility.console_log("Starting http_server simple test app")
|
||||
Utility.console_log('Starting http_server simple test app')
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
Utility.console_log("Waiting to connect with AP")
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
Utility.console_log('Waiting to connect with AP')
|
||||
got_ip = dut1.expect(re.compile(r'(?:[\s\S]*)IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=30)[0]
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: '(\d+)'"), timeout=30)[0]
|
||||
|
||||
Utility.console_log("Got IP : " + got_ip)
|
||||
Utility.console_log("Got Port : " + got_port)
|
||||
Utility.console_log('Got IP : ' + got_ip)
|
||||
Utility.console_log('Got Port : ' + got_port)
|
||||
|
||||
# Expected Logs
|
||||
dut1.expect("Registering URI handlers", timeout=30)
|
||||
dut1.expect('Registering URI handlers', timeout=30)
|
||||
threads = []
|
||||
# Open 20 sockets, one from each thread
|
||||
for _ in range(20):
|
||||
@@ -163,7 +161,7 @@ def test_examples_protocol_http_server_lru_purge_enable(env, extra_data):
|
||||
thread.start()
|
||||
threads.append(thread)
|
||||
except OSError as err:
|
||||
Utility.console_log("Error: unable to start thread, " + err)
|
||||
Utility.console_log('Error: unable to start thread, ' + err)
|
||||
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
@@ -14,15 +14,14 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import division
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
import re
|
||||
from tiny_test_fw import Utility
|
||||
import ttfw_idf
|
||||
import os
|
||||
import websocket
|
||||
from __future__ import division, print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import ttfw_idf
|
||||
import websocket
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
OPCODE_TEXT = 0x1
|
||||
OPCODE_BIN = 0x2
|
||||
@@ -37,7 +36,7 @@ class WsClient:
|
||||
self.ws = websocket.WebSocket()
|
||||
|
||||
def __enter__(self):
|
||||
self.ws.connect("ws://{}:{}/ws".format(self.ip, self.port))
|
||||
self.ws.connect('ws://{}:{}/ws'.format(self.ip, self.port))
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
@@ -46,7 +45,7 @@ class WsClient:
|
||||
def read(self):
|
||||
return self.ws.recv_data(control_frame=True)
|
||||
|
||||
def write(self, data="", opcode=OPCODE_TEXT):
|
||||
def write(self, data='', opcode=OPCODE_TEXT):
|
||||
if opcode == OPCODE_BIN:
|
||||
return self.ws.send_binary(data.encode())
|
||||
if opcode == OPCODE_PING:
|
||||
@@ -54,27 +53,27 @@ class WsClient:
|
||||
return self.ws.send(data)
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_http_ws_echo_server(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/ws_echo_server", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('http_server', 'examples/protocols/http_server/ws_echo_server', dut_class=ttfw_idf.ESP32DUT)
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "ws_echo_server.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'ws_echo_server.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("http_ws_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('http_ws_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# Upload binary and start testing
|
||||
Utility.console_log("Starting ws-echo-server test app based on http_server")
|
||||
Utility.console_log('Starting ws-echo-server test app based on http_server')
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
Utility.console_log("Waiting to connect with AP")
|
||||
got_ip = dut1.expect(re.compile(r"IPv4 address: (\d+.\d+.\d+.\d+)"), timeout=60)[0]
|
||||
Utility.console_log('Waiting to connect with AP')
|
||||
got_ip = dut1.expect(re.compile(r'IPv4 address: (\d+.\d+.\d+.\d+)'), timeout=60)[0]
|
||||
got_port = dut1.expect(re.compile(r"Starting server on port: '(\d+)'"), timeout=60)[0]
|
||||
|
||||
Utility.console_log("Got IP : " + got_ip)
|
||||
Utility.console_log("Got Port : " + got_port)
|
||||
Utility.console_log('Got IP : ' + got_ip)
|
||||
Utility.console_log('Got Port : ' + got_port)
|
||||
|
||||
# Start ws server test
|
||||
with WsClient(got_ip, int(got_port)) as ws:
|
||||
@@ -82,23 +81,23 @@ def test_examples_protocol_http_ws_echo_server(env, extra_data):
|
||||
for expected_opcode in [OPCODE_TEXT, OPCODE_BIN, OPCODE_PING]:
|
||||
ws.write(data=DATA, opcode=expected_opcode)
|
||||
opcode, data = ws.read()
|
||||
Utility.console_log("Testing opcode {}: Received opcode:{}, data:{}".format(expected_opcode, opcode, data))
|
||||
Utility.console_log('Testing opcode {}: Received opcode:{}, data:{}'.format(expected_opcode, opcode, data))
|
||||
data = data.decode()
|
||||
if expected_opcode == OPCODE_PING:
|
||||
dut1.expect("Got a WS PING frame, Replying PONG")
|
||||
dut1.expect('Got a WS PING frame, Replying PONG')
|
||||
if opcode != OPCODE_PONG or data != DATA:
|
||||
raise RuntimeError("Failed to receive correct opcode:{} or data:{}".format(opcode, data))
|
||||
raise RuntimeError('Failed to receive correct opcode:{} or data:{}'.format(opcode, data))
|
||||
continue
|
||||
dut_data = dut1.expect(re.compile(r"Got packet with message: ([A-Za-z0-9_]*)"))[0]
|
||||
dut_opcode = int(dut1.expect(re.compile(r"Packet type: ([0-9]*)"))[0])
|
||||
dut_data = dut1.expect(re.compile(r'Got packet with message: ([A-Za-z0-9_]*)'))[0]
|
||||
dut_opcode = int(dut1.expect(re.compile(r'Packet type: ([0-9]*)'))[0])
|
||||
if opcode != expected_opcode or data != DATA or opcode != dut_opcode or data != dut_data:
|
||||
raise RuntimeError("Failed to receive correct opcode:{} or data:{}".format(opcode, data))
|
||||
ws.write(data="Trigger async", opcode=OPCODE_TEXT)
|
||||
raise RuntimeError('Failed to receive correct opcode:{} or data:{}'.format(opcode, data))
|
||||
ws.write(data='Trigger async', opcode=OPCODE_TEXT)
|
||||
opcode, data = ws.read()
|
||||
Utility.console_log("Testing async send: Received opcode:{}, data:{}".format(opcode, data))
|
||||
Utility.console_log('Testing async send: Received opcode:{}, data:{}'.format(opcode, data))
|
||||
data = data.decode()
|
||||
if opcode != OPCODE_TEXT or data != "Async data":
|
||||
raise RuntimeError("Failed to receive correct opcode:{} or data:{}".format(opcode, data))
|
||||
if opcode != OPCODE_TEXT or data != 'Async data':
|
||||
raise RuntimeError('Failed to receive correct opcode:{} or data:{}'.format(opcode, data))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import os
|
||||
import re
|
||||
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_EthKitV1")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_EthKitV1')
|
||||
def test_examples_protocol_https_request(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -13,24 +14,24 @@ def test_examples_protocol_https_request(env, extra_data):
|
||||
certificate verification options
|
||||
3. send http request
|
||||
"""
|
||||
dut1 = env.get_dut("https_request", "examples/protocols/https_request", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('https_request', 'examples/protocols/https_request', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "https_request.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'https_request.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("https_request_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('https_request_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# start tes
|
||||
Utility.console_log("Starting https_request simple test app")
|
||||
Utility.console_log('Starting https_request simple test app')
|
||||
dut1.start_app()
|
||||
|
||||
# Check for connection using crt bundle
|
||||
Utility.console_log("Testing for \"https_request using crt bundle\"")
|
||||
try:
|
||||
dut1.expect(re.compile("https_request using crt bundle"), timeout=30)
|
||||
dut1.expect_all("Certificate validated",
|
||||
"Connection established...",
|
||||
"Reading HTTP response...",
|
||||
"HTTP/1.1 200 OK",
|
||||
re.compile("connection closed"))
|
||||
dut1.expect(re.compile('https_request using crt bundle'), timeout=30)
|
||||
dut1.expect_all('Certificate validated',
|
||||
'Connection established...',
|
||||
'Reading HTTP response...',
|
||||
'HTTP/1.1 200 OK',
|
||||
re.compile('connection closed'))
|
||||
except Exception:
|
||||
Utility.console_log("Failed the test for \"https_request using crt bundle\"")
|
||||
raise
|
||||
@@ -39,11 +40,11 @@ def test_examples_protocol_https_request(env, extra_data):
|
||||
# Check for connection using cacert_buf
|
||||
Utility.console_log("Testing for \"https_request using cacert_buf\"")
|
||||
try:
|
||||
dut1.expect(re.compile("https_request using cacert_buf"), timeout=20)
|
||||
dut1.expect_all("Connection established...",
|
||||
"Reading HTTP response...",
|
||||
"HTTP/1.1 200 OK",
|
||||
re.compile("connection closed"))
|
||||
dut1.expect(re.compile('https_request using cacert_buf'), timeout=20)
|
||||
dut1.expect_all('Connection established...',
|
||||
'Reading HTTP response...',
|
||||
'HTTP/1.1 200 OK',
|
||||
re.compile('connection closed'))
|
||||
except Exception:
|
||||
Utility.console_log("Passed the test for \"https_request using cacert_buf\"")
|
||||
raise
|
||||
@@ -52,32 +53,32 @@ def test_examples_protocol_https_request(env, extra_data):
|
||||
# Check for connection using global ca_store
|
||||
Utility.console_log("Testing for \"https_request using global ca_store\"")
|
||||
try:
|
||||
dut1.expect(re.compile("https_request using global ca_store"), timeout=20)
|
||||
dut1.expect_all("Connection established...",
|
||||
"Reading HTTP response...",
|
||||
"HTTP/1.1 200 OK",
|
||||
re.compile("connection closed"))
|
||||
dut1.expect(re.compile('https_request using global ca_store'), timeout=20)
|
||||
dut1.expect_all('Connection established...',
|
||||
'Reading HTTP response...',
|
||||
'HTTP/1.1 200 OK',
|
||||
re.compile('connection closed'))
|
||||
except Exception:
|
||||
Utility.console_log("Failed the test for \"https_request using global ca_store\"")
|
||||
raise
|
||||
Utility.console_log("Passed the test for \"https_request using global ca_store\"")
|
||||
|
||||
# Check for connection using crt bundle with mbedtls dynamic resource enabled
|
||||
dut1 = env.get_dut("https_request", "examples/protocols/https_request", dut_class=ttfw_idf.ESP32DUT, app_config_name='ssldyn')
|
||||
dut1 = env.get_dut('https_request', 'examples/protocols/https_request', dut_class=ttfw_idf.ESP32DUT, app_config_name='ssldyn')
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "https_request.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'https_request.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("https_request_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('https_request_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# start test
|
||||
dut1.start_app()
|
||||
# only check if one connection is established
|
||||
Utility.console_log("Testing for \"https_request using crt bundle\" with mbedtls dynamic resource enabled")
|
||||
try:
|
||||
dut1.expect(re.compile("https_request using crt bundle"), timeout=30)
|
||||
dut1.expect_all("Connection established...",
|
||||
"Reading HTTP response...",
|
||||
"HTTP/1.1 200 OK",
|
||||
re.compile("connection closed"))
|
||||
dut1.expect(re.compile('https_request using crt bundle'), timeout=30)
|
||||
dut1.expect_all('Connection established...',
|
||||
'Reading HTTP response...',
|
||||
'HTTP/1.1 200 OK',
|
||||
re.compile('connection closed'))
|
||||
except Exception:
|
||||
Utility.console_log("Failed the test for \"https_request using crt bundle\" when mbedtls dynamic resource was enabled")
|
||||
raise
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import os
|
||||
import re
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI", ignore=True)
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI', ignore=True)
|
||||
def test_examples_protocol_https_x509_bundle(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -11,28 +12,28 @@ def test_examples_protocol_https_x509_bundle(env, extra_data):
|
||||
2. connect to multiple URLs
|
||||
3. send http request
|
||||
"""
|
||||
dut1 = env.get_dut("https_x509_bundle", "examples/protocols/https_x509_bundle")
|
||||
dut1 = env.get_dut('https_x509_bundle', 'examples/protocols/https_x509_bundle')
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "https_x509_bundle.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'https_x509_bundle.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("https_x509_bundle_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('https_x509_bundle_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# start test
|
||||
dut1.start_app()
|
||||
num_URLS = dut1.expect(re.compile(r"Connecting to (\d+) URLs"), timeout=30)
|
||||
dut1.expect(re.compile(r"Connection established to ([\s\S]*)"), timeout=30)
|
||||
dut1.expect("Completed {} connections".format(num_URLS[0]), timeout=60)
|
||||
num_URLS = dut1.expect(re.compile(r'Connecting to (\d+) URLs'), timeout=30)
|
||||
dut1.expect(re.compile(r'Connection established to ([\s\S]*)'), timeout=30)
|
||||
dut1.expect('Completed {} connections'.format(num_URLS[0]), timeout=60)
|
||||
|
||||
# test mbedtls dynamic resource
|
||||
dut1 = env.get_dut("https_x509_bundle", "examples/protocols/https_x509_bundle", app_config_name='ssldyn')
|
||||
dut1 = env.get_dut('https_x509_bundle', 'examples/protocols/https_x509_bundle', app_config_name='ssldyn')
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "https_x509_bundle.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'https_x509_bundle.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("https_x509_bundle_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('https_x509_bundle_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# start test
|
||||
dut1.start_app()
|
||||
num_URLS = dut1.expect(re.compile(r"Connecting to (\d+) URLs"), timeout=30)
|
||||
dut1.expect(re.compile(r"Connection established to ([\s\S]*)"), timeout=30)
|
||||
dut1.expect("Completed {} connections".format(num_URLS[0]), timeout=60)
|
||||
num_URLS = dut1.expect(re.compile(r'Connecting to (\d+) URLs'), timeout=30)
|
||||
dut1.expect(re.compile(r'Connection established to ([\s\S]*)'), timeout=30)
|
||||
dut1.expect('Completed {} connections'.format(num_URLS[0]), timeout=60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from __future__ import unicode_literals
|
||||
import re
|
||||
import ttfw_idf
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import re
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from threading import Event, Thread
|
||||
|
||||
import dpkt
|
||||
import dpkt.dns
|
||||
from threading import Thread, Event
|
||||
import subprocess
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import DUT
|
||||
|
||||
stop_mdns_server = Event()
|
||||
esp_answered = Event()
|
||||
@@ -18,7 +18,7 @@ esp_answered = Event()
|
||||
def get_dns_query_for_esp(esp_host):
|
||||
dns = dpkt.dns.DNS(b'\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01')
|
||||
dns.qd[0].name = esp_host + u'.local'
|
||||
print("Created query for esp host: {} ".format(dns.__repr__()))
|
||||
print('Created query for esp host: {} '.format(dns.__repr__()))
|
||||
return dns.pack()
|
||||
|
||||
|
||||
@@ -32,26 +32,26 @@ def get_dns_answer_to_mdns(tester_host):
|
||||
arr.name = tester_host
|
||||
arr.ip = socket.inet_aton('127.0.0.1')
|
||||
dns. an.append(arr)
|
||||
print("Created answer to mdns query: {} ".format(dns.__repr__()))
|
||||
print('Created answer to mdns query: {} '.format(dns.__repr__()))
|
||||
return dns.pack()
|
||||
|
||||
|
||||
def get_dns_answer_to_mdns_lwip(tester_host, id):
|
||||
dns = dpkt.dns.DNS(b"\x5e\x39\x84\x00\x00\x01\x00\x01\x00\x00\x00\x00\x0a\x64\x61\x76\x69\x64"
|
||||
b"\x2d\x63\x6f\x6d\x70\x05\x6c\x6f\x63\x61\x6c\x00\x00\x01\x00\x01\xc0\x0c"
|
||||
b"\x00\x01\x00\x01\x00\x00\x00\x0a\x00\x04\xc0\xa8\x0a\x6c")
|
||||
dns = dpkt.dns.DNS(b'\x5e\x39\x84\x00\x00\x01\x00\x01\x00\x00\x00\x00\x0a\x64\x61\x76\x69\x64'
|
||||
b'\x2d\x63\x6f\x6d\x70\x05\x6c\x6f\x63\x61\x6c\x00\x00\x01\x00\x01\xc0\x0c'
|
||||
b'\x00\x01\x00\x01\x00\x00\x00\x0a\x00\x04\xc0\xa8\x0a\x6c')
|
||||
dns.qd[0].name = tester_host
|
||||
dns.an[0].name = tester_host
|
||||
dns.an[0].ip = socket.inet_aton('127.0.0.1')
|
||||
dns.an[0].rdata = socket.inet_aton('127.0.0.1')
|
||||
dns.id = id
|
||||
print("Created answer to mdns (lwip) query: {} ".format(dns.__repr__()))
|
||||
print('Created answer to mdns (lwip) query: {} '.format(dns.__repr__()))
|
||||
return dns.pack()
|
||||
|
||||
|
||||
def mdns_server(esp_host):
|
||||
global esp_answered
|
||||
UDP_IP = "0.0.0.0"
|
||||
UDP_IP = '0.0.0.0'
|
||||
UDP_PORT = 5353
|
||||
MCAST_GRP = '224.0.0.251'
|
||||
TESTER_NAME = u'tinytester.local'
|
||||
@@ -60,7 +60,7 @@ def mdns_server(esp_host):
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
||||
sock.bind((UDP_IP,UDP_PORT))
|
||||
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
|
||||
mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
|
||||
sock.settimeout(30)
|
||||
while not stop_mdns_server.is_set():
|
||||
@@ -72,14 +72,14 @@ def mdns_server(esp_host):
|
||||
dns = dpkt.dns.DNS(data)
|
||||
if len(dns.qd) > 0 and dns.qd[0].type == dpkt.dns.DNS_A:
|
||||
if dns.qd[0].name == TESTER_NAME:
|
||||
print("Received query: {} ".format(dns.__repr__()))
|
||||
print('Received query: {} '.format(dns.__repr__()))
|
||||
sock.sendto(get_dns_answer_to_mdns(TESTER_NAME), (MCAST_GRP,UDP_PORT))
|
||||
elif dns.qd[0].name == TESTER_NAME_LWIP:
|
||||
print("Received query: {} ".format(dns.__repr__()))
|
||||
print('Received query: {} '.format(dns.__repr__()))
|
||||
sock.sendto(get_dns_answer_to_mdns_lwip(TESTER_NAME_LWIP, dns.id), addr)
|
||||
if len(dns.an) > 0 and dns.an[0].type == dpkt.dns.DNS_A:
|
||||
if dns.an[0].name == esp_host + u'.local':
|
||||
print("Received answer to esp32-mdns query: {}".format(dns.__repr__()))
|
||||
print('Received answer to esp32-mdns query: {}'.format(dns.__repr__()))
|
||||
esp_answered.set()
|
||||
except socket.timeout:
|
||||
break
|
||||
@@ -87,7 +87,7 @@ def mdns_server(esp_host):
|
||||
continue
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_mdns(env, extra_data):
|
||||
global stop_mdns_server
|
||||
"""
|
||||
@@ -97,21 +97,21 @@ def test_examples_protocol_mdns(env, extra_data):
|
||||
3. check the mdns name is accessible
|
||||
4. check DUT output if mdns advertized host is resolved
|
||||
"""
|
||||
dut1 = env.get_dut("mdns-test", "examples/protocols/mdns", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('mdns-test', 'examples/protocols/mdns', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mdns-test.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'mdns-test.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("mdns-test_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('mdns-test_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# 1. start mdns application
|
||||
dut1.start_app()
|
||||
# 2. get the dut host name (and IP address)
|
||||
specific_host = dut1.expect(re.compile(r"mdns hostname set to: \[([^\]]+)\]"), timeout=30)
|
||||
specific_host = dut1.expect(re.compile(r'mdns hostname set to: \[([^\]]+)\]'), timeout=30)
|
||||
specific_host = str(specific_host[0])
|
||||
thread1 = Thread(target=mdns_server, args=(specific_host,))
|
||||
thread1.start()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)[0]
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
ip_address = dut1.expect(re.compile(r' sta ip: ([^,]+),'), timeout=30)[0]
|
||||
print('Connected to AP with IP: {}'.format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
stop_mdns_server.set()
|
||||
thread1.join()
|
||||
@@ -121,15 +121,15 @@ def test_examples_protocol_mdns(env, extra_data):
|
||||
if not esp_answered.wait(timeout=30):
|
||||
raise ValueError('Test has failed: did not receive mdns answer within timeout')
|
||||
# 4. check DUT output if mdns advertized host is resolved
|
||||
dut1.expect(re.compile(r"mdns-test: Query A: tinytester.local resolved to: 127.0.0.1"), timeout=30)
|
||||
dut1.expect(re.compile(r"mdns-test: gethostbyname: tinytester-lwip.local resolved to: 127.0.0.1"), timeout=30)
|
||||
dut1.expect(re.compile(r"mdns-test: getaddrinfo: tinytester-lwip.local resolved to: 127.0.0.1"), timeout=30)
|
||||
dut1.expect(re.compile(r'mdns-test: Query A: tinytester.local resolved to: 127.0.0.1'), timeout=30)
|
||||
dut1.expect(re.compile(r'mdns-test: gethostbyname: tinytester-lwip.local resolved to: 127.0.0.1'), timeout=30)
|
||||
dut1.expect(re.compile(r'mdns-test: getaddrinfo: tinytester-lwip.local resolved to: 127.0.0.1'), timeout=30)
|
||||
# 5. check the DUT answers to `dig` command
|
||||
dig_output = subprocess.check_output(['dig', '+short', '-p', '5353', '@224.0.0.251',
|
||||
'{}.local'.format(specific_host)])
|
||||
print('Resolving {} using "dig" succeeded with:\n{}'.format(specific_host, dig_output))
|
||||
if not ip_address.encode('utf-8') in dig_output:
|
||||
raise ValueError("Test has failed: Incorrectly resolved DUT hostname using dig"
|
||||
raise ValueError('Test has failed: Incorrectly resolved DUT hostname using dig'
|
||||
"Output should've contained DUT's IP address:{}".format(ip_address))
|
||||
finally:
|
||||
stop_mdns_server.set()
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
# Need Python 3 string formatting functions
|
||||
from __future__ import print_function
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
from threading import Thread
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
LOG_LEVEL = logging.DEBUG
|
||||
LOGGER_NAME = "modbus_test"
|
||||
LOGGER_NAME = 'modbus_test'
|
||||
|
||||
# Allowed parameter reads
|
||||
TEST_READ_MIN_COUNT = 10 # Minimum number of correct readings
|
||||
@@ -27,38 +27,38 @@ TEST_SLAVE_ASCII = 'slave_ascii'
|
||||
|
||||
# Define tuple of strings to expect for each DUT.
|
||||
#
|
||||
master_expect = ("MASTER_TEST: Modbus master stack initialized...", "MASTER_TEST: Start modbus test...", "MASTER_TEST: Destroy master...")
|
||||
slave_expect = ("SLAVE_TEST: Modbus slave stack initialized.", "SLAVE_TEST: Start modbus test...", "SLAVE_TEST: Modbus controller destroyed.")
|
||||
master_expect = ('MASTER_TEST: Modbus master stack initialized...', 'MASTER_TEST: Start modbus test...', 'MASTER_TEST: Destroy master...')
|
||||
slave_expect = ('SLAVE_TEST: Modbus slave stack initialized.', 'SLAVE_TEST: Start modbus test...', 'SLAVE_TEST: Modbus controller destroyed.')
|
||||
|
||||
# The dictionary for expected values in listing
|
||||
expect_dict_master_ok = {"START": (),
|
||||
"READ_PAR_OK": (),
|
||||
"ALARM_MSG": (u'7',)}
|
||||
expect_dict_master_ok = {'START': (),
|
||||
'READ_PAR_OK': (),
|
||||
'ALARM_MSG': (u'7',)}
|
||||
|
||||
expect_dict_master_err = {"READ_PAR_ERR": (u'263', u'ESP_ERR_TIMEOUT'),
|
||||
"READ_STK_ERR": (u'107', u'ESP_ERR_TIMEOUT')}
|
||||
expect_dict_master_err = {'READ_PAR_ERR': (u'263', u'ESP_ERR_TIMEOUT'),
|
||||
'READ_STK_ERR': (u'107', u'ESP_ERR_TIMEOUT')}
|
||||
|
||||
# The dictionary for regular expression patterns to check in listing
|
||||
pattern_dict_master_ok = {"START": (r'.*I \([0-9]+\) MASTER_TEST: Start modbus test...'),
|
||||
"READ_PAR_OK": (r'.*I\s\([0-9]+\) MASTER_TEST: Characteristic #[0-9]+ [a-zA-Z0-9_]+'
|
||||
pattern_dict_master_ok = {'START': (r'.*I \([0-9]+\) MASTER_TEST: Start modbus test...'),
|
||||
'READ_PAR_OK': (r'.*I\s\([0-9]+\) MASTER_TEST: Characteristic #[0-9]+ [a-zA-Z0-9_]+'
|
||||
r'\s\([a-zA-Z\%\/]+\) value = [a-zA-Z0-9\.\s]*\(0x[a-zA-Z0-9]+\) read successful.'),
|
||||
"ALARM_MSG": (r'.*I \([0-9]*\) MASTER_TEST: Alarm triggered by cid #([0-9]+).')}
|
||||
'ALARM_MSG': (r'.*I \([0-9]*\) MASTER_TEST: Alarm triggered by cid #([0-9]+).')}
|
||||
|
||||
pattern_dict_master_err = {"READ_PAR_ERR_TOUT": (r'.*E \([0-9]+\) MASTER_TEST: Characteristic #[0-9]+'
|
||||
pattern_dict_master_err = {'READ_PAR_ERR_TOUT': (r'.*E \([0-9]+\) MASTER_TEST: Characteristic #[0-9]+'
|
||||
r'\s\([a-zA-Z0-9_]+\) read fail, err = [0-9]+ \([_A-Z]+\).'),
|
||||
"READ_STK_ERR_TOUT": (r'.*E \([0-9]+\) MB_CONTROLLER_MASTER: [a-zA-Z0-9_]+\([0-9]+\):\s'
|
||||
'READ_STK_ERR_TOUT': (r'.*E \([0-9]+\) MB_CONTROLLER_MASTER: [a-zA-Z0-9_]+\([0-9]+\):\s'
|
||||
r'SERIAL master get parameter failure error=\(0x([a-zA-Z0-9]+)\) \(([_A-Z]+)\).')}
|
||||
|
||||
# The dictionary for expected values in listing
|
||||
expect_dict_slave_ok = {"START": (),
|
||||
"READ_PAR_OK": (),
|
||||
"DESTROY": ()}
|
||||
expect_dict_slave_ok = {'START': (),
|
||||
'READ_PAR_OK': (),
|
||||
'DESTROY': ()}
|
||||
|
||||
# The dictionary for regular expression patterns to check in listing
|
||||
pattern_dict_slave_ok = {"START": (r'.*I \([0-9]+\) SLAVE_TEST: Start modbus test...'),
|
||||
"READ_PAR_OK": (r'.*I\s\([0-9]+\) SLAVE_TEST: [A-Z]+ READ \([a-zA-Z0-9_]+ us\),\s'
|
||||
pattern_dict_slave_ok = {'START': (r'.*I \([0-9]+\) SLAVE_TEST: Start modbus test...'),
|
||||
'READ_PAR_OK': (r'.*I\s\([0-9]+\) SLAVE_TEST: [A-Z]+ READ \([a-zA-Z0-9_]+ us\),\s'
|
||||
r'ADDR:[0-9]+, TYPE:[0-9]+, INST_ADDR:0x[a-zA-Z0-9]+, SIZE:[0-9]+'),
|
||||
"DESTROY": (r'.*I\s\([0-9]+\) SLAVE_TEST: Modbus controller destroyed.')}
|
||||
'DESTROY': (r'.*I\s\([0-9]+\) SLAVE_TEST: Modbus controller destroyed.')}
|
||||
|
||||
logger = logging.getLogger(LOGGER_NAME)
|
||||
|
||||
@@ -89,8 +89,8 @@ class DutTestThread(Thread):
|
||||
|
||||
# Check DUT exceptions
|
||||
dut_exceptions = self.dut.get_exceptions()
|
||||
if "Guru Meditation Error:" in dut_exceptions:
|
||||
raise Exception("%s generated an exception: %s\n" % (str(self.dut), dut_exceptions))
|
||||
if 'Guru Meditation Error:' in dut_exceptions:
|
||||
raise Exception('%s generated an exception: %s\n' % (str(self.dut), dut_exceptions))
|
||||
|
||||
# Mark thread has run to completion without any exceptions
|
||||
self.data = self.dut.stop_capture_raw_data()
|
||||
@@ -102,7 +102,7 @@ def test_filter_output(data=None, start_pattern=None, end_pattern=None):
|
||||
"""
|
||||
start_index = str(data).find(start_pattern)
|
||||
end_index = str(data).find(end_pattern)
|
||||
logger.debug("Listing start index= %d, end=%d" % (start_index, end_index))
|
||||
logger.debug('Listing start index= %d, end=%d' % (start_index, end_index))
|
||||
if start_index == -1 or end_index == -1:
|
||||
return data
|
||||
return data[start_index:end_index + len(end_pattern)]
|
||||
@@ -145,9 +145,9 @@ def test_check_output(data=None, check_dict=None, expect_dict=None):
|
||||
for line in data_lines:
|
||||
group, index = test_expect_re(line, pattern)
|
||||
if index is not None:
|
||||
logger.debug("Found key{%s}=%s, line: \n%s" % (key, group, line))
|
||||
logger.debug('Found key{%s}=%s, line: \n%s' % (key, group, line))
|
||||
if expect_dict[key] == group:
|
||||
logger.debug("The result is correct for the key:%s, expected:%s == returned:%s" % (key, str(expect_dict[key]), str(group)))
|
||||
logger.debug('The result is correct for the key:%s, expected:%s == returned:%s' % (key, str(expect_dict[key]), str(group)))
|
||||
match_count += 1
|
||||
return match_count
|
||||
|
||||
@@ -158,7 +158,7 @@ def test_check_mode(dut=None, mode_str=None, value=None):
|
||||
global logger
|
||||
try:
|
||||
opt = dut.app.get_sdkconfig()[mode_str]
|
||||
logger.info("%s {%s} = %s.\n" % (str(dut), mode_str, opt))
|
||||
logger.info('%s {%s} = %s.\n' % (str(dut), mode_str, opt))
|
||||
return value == opt
|
||||
except Exception:
|
||||
logger.info('ENV_TEST_FAILURE: %s: Cannot find option %s in sdkconfig.' % (str(dut), mode_str))
|
||||
@@ -170,30 +170,30 @@ def test_modbus_communication(env, comm_mode):
|
||||
global logger
|
||||
|
||||
# Get device under test. "dut1 - master", "dut2 - slave" must be properly connected through RS485 interface driver
|
||||
dut_master = env.get_dut("modbus_master", "examples/protocols/modbus/serial/mb_master", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut_slave = env.get_dut("modbus_slave", "examples/protocols/modbus/serial/mb_slave", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut_master = env.get_dut('modbus_master', 'examples/protocols/modbus/serial/mb_master', dut_class=ttfw_idf.ESP32DUT)
|
||||
dut_slave = env.get_dut('modbus_slave', 'examples/protocols/modbus/serial/mb_slave', dut_class=ttfw_idf.ESP32DUT)
|
||||
|
||||
try:
|
||||
logger.debug("Environment vars: %s\r\n" % os.environ)
|
||||
logger.debug("DUT slave sdkconfig: %s\r\n" % dut_slave.app.get_sdkconfig())
|
||||
logger.debug("DUT master sdkconfig: %s\r\n" % dut_master.app.get_sdkconfig())
|
||||
logger.debug('Environment vars: %s\r\n' % os.environ)
|
||||
logger.debug('DUT slave sdkconfig: %s\r\n' % dut_slave.app.get_sdkconfig())
|
||||
logger.debug('DUT master sdkconfig: %s\r\n' % dut_master.app.get_sdkconfig())
|
||||
|
||||
# Check Kconfig configuration options for each built example
|
||||
if test_check_mode(dut_master, "CONFIG_MB_COMM_MODE_ASCII", "y") and test_check_mode(dut_slave, "CONFIG_MB_COMM_MODE_ASCII", "y"):
|
||||
logger.info("ENV_TEST_INFO: Modbus ASCII test mode selected in the configuration. \n")
|
||||
if test_check_mode(dut_master, 'CONFIG_MB_COMM_MODE_ASCII', 'y') and test_check_mode(dut_slave, 'CONFIG_MB_COMM_MODE_ASCII', 'y'):
|
||||
logger.info('ENV_TEST_INFO: Modbus ASCII test mode selected in the configuration. \n')
|
||||
slave_name = TEST_SLAVE_ASCII
|
||||
master_name = TEST_MASTER_ASCII
|
||||
elif test_check_mode(dut_master, "CONFIG_MB_COMM_MODE_RTU", "y") and test_check_mode(dut_slave, "CONFIG_MB_COMM_MODE_RTU", "y"):
|
||||
logger.info("ENV_TEST_INFO: Modbus RTU test mode selected in the configuration. \n")
|
||||
elif test_check_mode(dut_master, 'CONFIG_MB_COMM_MODE_RTU', 'y') and test_check_mode(dut_slave, 'CONFIG_MB_COMM_MODE_RTU', 'y'):
|
||||
logger.info('ENV_TEST_INFO: Modbus RTU test mode selected in the configuration. \n')
|
||||
slave_name = TEST_SLAVE_RTU
|
||||
master_name = TEST_MASTER_RTU
|
||||
else:
|
||||
logger.error("ENV_TEST_FAILURE: Communication mode in master and slave configuration don't match.\n")
|
||||
raise Exception("ENV_TEST_FAILURE: Communication mode in master and slave configuration don't match.\n")
|
||||
# Check if slave address for example application is default one to be able to communicate
|
||||
if not test_check_mode(dut_slave, "CONFIG_MB_SLAVE_ADDR", "1"):
|
||||
logger.error("ENV_TEST_FAILURE: Slave address option is incorrect.\n")
|
||||
raise Exception("ENV_TEST_FAILURE: Slave address option is incorrect.\n")
|
||||
if not test_check_mode(dut_slave, 'CONFIG_MB_SLAVE_ADDR', '1'):
|
||||
logger.error('ENV_TEST_FAILURE: Slave address option is incorrect.\n')
|
||||
raise Exception('ENV_TEST_FAILURE: Slave address option is incorrect.\n')
|
||||
|
||||
# Flash app onto each DUT
|
||||
dut_master.start_app()
|
||||
@@ -212,15 +212,15 @@ def test_modbus_communication(env, comm_mode):
|
||||
dut_master_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT)
|
||||
|
||||
if dut_slave_thread.isAlive():
|
||||
logger.error("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
logger.error('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
raise Exception("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
raise Exception('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
|
||||
if dut_master_thread.isAlive():
|
||||
logger.error("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
logger.error('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
raise Exception("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
raise Exception('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
finally:
|
||||
dut_master.close()
|
||||
@@ -228,43 +228,43 @@ def test_modbus_communication(env, comm_mode):
|
||||
|
||||
# Check if test threads completed successfully and captured data
|
||||
if not dut_slave_thread.result or dut_slave_thread.data is None:
|
||||
logger.error("The thread %s was not run successfully." % dut_slave_thread.tname)
|
||||
raise Exception("The thread %s was not run successfully." % dut_slave_thread.tname)
|
||||
logger.error('The thread %s was not run successfully.' % dut_slave_thread.tname)
|
||||
raise Exception('The thread %s was not run successfully.' % dut_slave_thread.tname)
|
||||
|
||||
if not dut_master_thread.result or dut_master_thread.data is None:
|
||||
logger.error("The thread %s was not run successfully." % dut_slave_thread.tname)
|
||||
raise Exception("The thread %s was not run successfully." % dut_master_thread.tname)
|
||||
logger.error('The thread %s was not run successfully.' % dut_slave_thread.tname)
|
||||
raise Exception('The thread %s was not run successfully.' % dut_master_thread.tname)
|
||||
|
||||
# Filter output to get test messages
|
||||
master_output = test_filter_output(dut_master_thread.data, master_expect[0], master_expect[len(master_expect) - 1])
|
||||
if master_output is not None:
|
||||
logger.info("The data for master thread is captured.")
|
||||
logger.info('The data for master thread is captured.')
|
||||
logger.debug(master_output)
|
||||
|
||||
slave_output = test_filter_output(dut_slave_thread.data, slave_expect[0], slave_expect[len(slave_expect) - 1])
|
||||
if slave_output is not None:
|
||||
logger.info("The data for slave thread is captured.")
|
||||
logger.info('The data for slave thread is captured.')
|
||||
logger.debug(slave_output)
|
||||
|
||||
# Check if parameters are read correctly by master
|
||||
match_count = test_check_output(master_output, pattern_dict_master_ok, expect_dict_master_ok)
|
||||
if match_count < TEST_READ_MIN_COUNT:
|
||||
logger.error("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count))
|
||||
raise Exception("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count))
|
||||
logger.info("OK pattern test for %s, match_count=%d." % (dut_master_thread.tname, match_count))
|
||||
logger.error('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
|
||||
raise Exception('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
|
||||
logger.info('OK pattern test for %s, match_count=%d.' % (dut_master_thread.tname, match_count))
|
||||
|
||||
# If the test completed successfully (alarm triggered) but there are some errors during reading of parameters
|
||||
match_count = test_check_output(master_output, pattern_dict_master_err, expect_dict_master_err)
|
||||
if match_count > TEST_READ_MAX_ERR_COUNT:
|
||||
logger.error("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count))
|
||||
raise Exception("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count))
|
||||
logger.info("ERROR pattern test for %s, match_count=%d." % (dut_master_thread.tname, match_count))
|
||||
logger.error('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
|
||||
raise Exception('There are errors reading parameters from %s, %d' % (dut_master_thread.tname, match_count))
|
||||
logger.info('ERROR pattern test for %s, match_count=%d.' % (dut_master_thread.tname, match_count))
|
||||
|
||||
match_count = test_check_output(slave_output, pattern_dict_slave_ok, expect_dict_slave_ok)
|
||||
if match_count < TEST_READ_MIN_COUNT:
|
||||
logger.error("There are errors reading parameters from %s, %d" % (dut_slave_thread.tname, match_count))
|
||||
raise Exception("There are errors reading parameters from %s, %d" % (dut_slave_thread.tname, match_count))
|
||||
logger.info("OK pattern test for %s, match_count=%d." % (dut_slave_thread.tname, match_count))
|
||||
logger.error('There are errors reading parameters from %s, %d' % (dut_slave_thread.tname, match_count))
|
||||
raise Exception('There are errors reading parameters from %s, %d' % (dut_slave_thread.tname, match_count))
|
||||
logger.info('OK pattern test for %s, match_count=%d.' % (dut_slave_thread.tname, match_count))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -282,7 +282,7 @@ if __name__ == '__main__':
|
||||
fh.setFormatter(formatter)
|
||||
logger.addHandler(fh)
|
||||
logger.addHandler(ch)
|
||||
logger.info("Start script %s." % os.path.basename(__file__))
|
||||
print("Logging file name: %s" % logger.handlers[0].baseFilename)
|
||||
logger.info('Start script %s.' % os.path.basename(__file__))
|
||||
print('Logging file name: %s' % logger.handlers[0].baseFilename)
|
||||
test_modbus_communication()
|
||||
logging.shutdown()
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
from threading import Thread
|
||||
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import DUT
|
||||
|
||||
LOG_LEVEL = logging.DEBUG
|
||||
LOGGER_NAME = "modbus_test"
|
||||
LOGGER_NAME = 'modbus_test'
|
||||
|
||||
# Allowed options for the test
|
||||
TEST_READ_MAX_ERR_COUNT = 3 # Maximum allowed read errors during initialization
|
||||
@@ -69,7 +69,7 @@ class DutTestThread(Thread):
|
||||
super(DutTestThread, self).__init__()
|
||||
|
||||
def __enter__(self):
|
||||
logger.debug("Restart %s." % self.tname)
|
||||
logger.debug('Restart %s.' % self.tname)
|
||||
# Reset DUT first
|
||||
self.dut.reset()
|
||||
# Capture output from the DUT
|
||||
@@ -80,7 +80,7 @@ class DutTestThread(Thread):
|
||||
""" The exit method of context manager
|
||||
"""
|
||||
if exc_type is not None or exc_value is not None:
|
||||
logger.info("Thread %s rised an exception type: %s, value: %s" % (self.tname, str(exc_type), str(exc_value)))
|
||||
logger.info('Thread %s rised an exception type: %s, value: %s' % (self.tname, str(exc_type), str(exc_value)))
|
||||
|
||||
def run(self):
|
||||
""" The function implements thread functionality
|
||||
@@ -94,8 +94,8 @@ class DutTestThread(Thread):
|
||||
|
||||
# Check DUT exceptions
|
||||
dut_exceptions = self.dut.get_exceptions()
|
||||
if "Guru Meditation Error:" in dut_exceptions:
|
||||
raise Exception("%s generated an exception: %s\n" % (str(self.dut), dut_exceptions))
|
||||
if 'Guru Meditation Error:' in dut_exceptions:
|
||||
raise Exception('%s generated an exception: %s\n' % (str(self.dut), dut_exceptions))
|
||||
|
||||
# Mark thread has run to completion without any exceptions
|
||||
self.data = self.dut.stop_capture_raw_data(capture_id=self.dut.name)
|
||||
@@ -108,13 +108,13 @@ class DutTestThread(Thread):
|
||||
self.dut.read()
|
||||
result = self.dut.expect(re.compile(message), TEST_EXPECT_STR_TIMEOUT)
|
||||
if int(result[0]) != index:
|
||||
raise Exception("Incorrect index of IP=%d for %s\n" % (int(result[0]), str(self.dut)))
|
||||
message = "IP%s=%s" % (result[0], self.ip_addr)
|
||||
self.dut.write(message, "\r\n", False)
|
||||
logger.debug("Sent message for %s: %s" % (self.tname, message))
|
||||
raise Exception('Incorrect index of IP=%d for %s\n' % (int(result[0]), str(self.dut)))
|
||||
message = 'IP%s=%s' % (result[0], self.ip_addr)
|
||||
self.dut.write(message, '\r\n', False)
|
||||
logger.debug('Sent message for %s: %s' % (self.tname, message))
|
||||
message = r'.*IP\([0-9]+\) = \[([0-9a-zA-Z\.\:]+)\] set from stdin.*'
|
||||
result = self.dut.expect(re.compile(message), TEST_EXPECT_STR_TIMEOUT)
|
||||
logger.debug("Thread %s initialized with slave IP (%s)." % (self.tname, result[0]))
|
||||
logger.debug('Thread %s initialized with slave IP (%s).' % (self.tname, result[0]))
|
||||
|
||||
def test_start(self, timeout_value):
|
||||
""" The method to initialize and handle test stages
|
||||
@@ -122,37 +122,37 @@ class DutTestThread(Thread):
|
||||
def handle_get_ip4(data):
|
||||
""" Handle get_ip v4
|
||||
"""
|
||||
logger.debug("%s[STACK_IPV4]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[STACK_IPV4]: %s' % (self.tname, str(data)))
|
||||
self.test_stage = STACK_IPV4
|
||||
|
||||
def handle_get_ip6(data):
|
||||
""" Handle get_ip v6
|
||||
"""
|
||||
logger.debug("%s[STACK_IPV6]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[STACK_IPV6]: %s' % (self.tname, str(data)))
|
||||
self.test_stage = STACK_IPV6
|
||||
|
||||
def handle_init(data):
|
||||
""" Handle init
|
||||
"""
|
||||
logger.debug("%s[STACK_INIT]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[STACK_INIT]: %s' % (self.tname, str(data)))
|
||||
self.test_stage = STACK_INIT
|
||||
|
||||
def handle_connect(data):
|
||||
""" Handle connect
|
||||
"""
|
||||
logger.debug("%s[STACK_CONNECT]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[STACK_CONNECT]: %s' % (self.tname, str(data)))
|
||||
self.test_stage = STACK_CONNECT
|
||||
|
||||
def handle_test_start(data):
|
||||
""" Handle connect
|
||||
"""
|
||||
logger.debug("%s[STACK_START]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[STACK_START]: %s' % (self.tname, str(data)))
|
||||
self.test_stage = STACK_START
|
||||
|
||||
def handle_par_ok(data):
|
||||
""" Handle parameter ok
|
||||
"""
|
||||
logger.debug("%s[READ_PAR_OK]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[READ_PAR_OK]: %s' % (self.tname, str(data)))
|
||||
if self.test_stage >= STACK_START:
|
||||
self.param_ok_count += 1
|
||||
self.test_stage = STACK_PAR_OK
|
||||
@@ -160,14 +160,14 @@ class DutTestThread(Thread):
|
||||
def handle_par_fail(data):
|
||||
""" Handle parameter fail
|
||||
"""
|
||||
logger.debug("%s[READ_PAR_FAIL]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[READ_PAR_FAIL]: %s' % (self.tname, str(data)))
|
||||
self.param_fail_count += 1
|
||||
self.test_stage = STACK_PAR_FAIL
|
||||
|
||||
def handle_destroy(data):
|
||||
""" Handle destroy
|
||||
"""
|
||||
logger.debug("%s[DESTROY]: %s" % (self.tname, str(data)))
|
||||
logger.debug('%s[DESTROY]: %s' % (self.tname, str(data)))
|
||||
self.test_stage = STACK_DESTROY
|
||||
self.test_finish = True
|
||||
|
||||
@@ -183,7 +183,7 @@ class DutTestThread(Thread):
|
||||
(re.compile(self.expected[STACK_DESTROY]), handle_destroy),
|
||||
timeout=timeout_value)
|
||||
except DUT.ExpectTimeout:
|
||||
logger.debug("%s, expect timeout on stage #%d (%s seconds)" % (self.tname, self.test_stage, timeout_value))
|
||||
logger.debug('%s, expect timeout on stage #%d (%s seconds)' % (self.tname, self.test_stage, timeout_value))
|
||||
self.test_finish = True
|
||||
|
||||
|
||||
@@ -193,7 +193,7 @@ def test_check_mode(dut=None, mode_str=None, value=None):
|
||||
global logger
|
||||
try:
|
||||
opt = dut.app.get_sdkconfig()[mode_str]
|
||||
logger.debug("%s {%s} = %s.\n" % (str(dut), mode_str, opt))
|
||||
logger.debug('%s {%s} = %s.\n' % (str(dut), mode_str, opt))
|
||||
return value == opt
|
||||
except Exception:
|
||||
logger.error('ENV_TEST_FAILURE: %s: Cannot find option %s in sdkconfig.' % (str(dut), mode_str))
|
||||
@@ -208,8 +208,8 @@ def test_modbus_communication(env, comm_mode):
|
||||
# Get device under test. Both duts must be able to be connected to WiFi router
|
||||
dut_master = env.get_dut('modbus_tcp_master', os.path.join(rel_project_path, TEST_MASTER_TCP))
|
||||
dut_slave = env.get_dut('modbus_tcp_slave', os.path.join(rel_project_path, TEST_SLAVE_TCP))
|
||||
log_file = os.path.join(env.log_path, "modbus_tcp_test.log")
|
||||
print("Logging file name: %s" % log_file)
|
||||
log_file = os.path.join(env.log_path, 'modbus_tcp_test.log')
|
||||
print('Logging file name: %s' % log_file)
|
||||
|
||||
try:
|
||||
# create file handler which logs even debug messages
|
||||
@@ -229,29 +229,29 @@ def test_modbus_communication(env, comm_mode):
|
||||
logger.addHandler(ch)
|
||||
|
||||
# Check Kconfig configuration options for each built example
|
||||
if (test_check_mode(dut_master, "CONFIG_FMB_COMM_MODE_TCP_EN", "y") and
|
||||
test_check_mode(dut_slave, "CONFIG_FMB_COMM_MODE_TCP_EN", "y")):
|
||||
if (test_check_mode(dut_master, 'CONFIG_FMB_COMM_MODE_TCP_EN', 'y') and
|
||||
test_check_mode(dut_slave, 'CONFIG_FMB_COMM_MODE_TCP_EN', 'y')):
|
||||
slave_name = TEST_SLAVE_TCP
|
||||
master_name = TEST_MASTER_TCP
|
||||
else:
|
||||
logger.error("ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n")
|
||||
raise Exception("ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n")
|
||||
logger.error('ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n')
|
||||
raise Exception('ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n')
|
||||
address = None
|
||||
if test_check_mode(dut_master, "CONFIG_MB_SLAVE_IP_FROM_STDIN", "y"):
|
||||
logger.info("ENV_TEST_INFO: Set slave IP address through STDIN.\n")
|
||||
if test_check_mode(dut_master, 'CONFIG_MB_SLAVE_IP_FROM_STDIN', 'y'):
|
||||
logger.info('ENV_TEST_INFO: Set slave IP address through STDIN.\n')
|
||||
# Flash app onto DUT (Todo: Debug case when the slave flashed before master then expect does not work correctly for no reason
|
||||
dut_slave.start_app()
|
||||
dut_master.start_app()
|
||||
if test_check_mode(dut_master, "CONFIG_EXAMPLE_CONNECT_IPV6", "y"):
|
||||
if test_check_mode(dut_master, 'CONFIG_EXAMPLE_CONNECT_IPV6', 'y'):
|
||||
address = dut_slave.expect(re.compile(pattern_dict_slave[STACK_IPV6]), TEST_EXPECT_STR_TIMEOUT)
|
||||
else:
|
||||
address = dut_slave.expect(re.compile(pattern_dict_slave[STACK_IPV4]), TEST_EXPECT_STR_TIMEOUT)
|
||||
if address is not None:
|
||||
print("Found IP slave address: %s" % address[0])
|
||||
print('Found IP slave address: %s' % address[0])
|
||||
else:
|
||||
raise Exception("ENV_TEST_FAILURE: Slave IP address is not found in the output. Check network settings.\n")
|
||||
raise Exception('ENV_TEST_FAILURE: Slave IP address is not found in the output. Check network settings.\n')
|
||||
else:
|
||||
raise Exception("ENV_TEST_FAILURE: Slave IP resolver is not configured correctly.\n")
|
||||
raise Exception('ENV_TEST_FAILURE: Slave IP resolver is not configured correctly.\n')
|
||||
|
||||
# Create thread for each dut
|
||||
with DutTestThread(dut=dut_master, name=master_name, ip_addr=address[0], expect=pattern_dict_master) as dut_master_thread:
|
||||
@@ -266,21 +266,21 @@ def test_modbus_communication(env, comm_mode):
|
||||
dut_master_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT)
|
||||
|
||||
if dut_slave_thread.isAlive():
|
||||
logger.error("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
logger.error('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
raise Exception("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
raise Exception('ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
|
||||
if dut_master_thread.isAlive():
|
||||
logger.error("TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
logger.error('TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
raise Exception("TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" %
|
||||
raise Exception('TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n' %
|
||||
(dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT))
|
||||
|
||||
logger.info("TEST_INFO: %s error count = %d, %s error count = %d.\n" %
|
||||
logger.info('TEST_INFO: %s error count = %d, %s error count = %d.\n' %
|
||||
(dut_master_thread.tname, dut_master_thread.param_fail_count,
|
||||
dut_slave_thread.tname, dut_slave_thread.param_fail_count))
|
||||
logger.info("TEST_INFO: %s ok count = %d, %s ok count = %d.\n" %
|
||||
logger.info('TEST_INFO: %s ok count = %d, %s ok count = %d.\n' %
|
||||
(dut_master_thread.tname, dut_master_thread.param_ok_count,
|
||||
dut_slave_thread.tname, dut_slave_thread.param_ok_count))
|
||||
|
||||
@@ -288,10 +288,10 @@ def test_modbus_communication(env, comm_mode):
|
||||
(dut_slave_thread.param_fail_count > TEST_READ_MAX_ERR_COUNT) or
|
||||
(dut_slave_thread.param_ok_count == 0) or
|
||||
(dut_master_thread.param_ok_count == 0)):
|
||||
raise Exception("TEST_FAILURE: %s parameter read error(ok) count = %d(%d), %s parameter read error(ok) count = %d(%d).\n" %
|
||||
raise Exception('TEST_FAILURE: %s parameter read error(ok) count = %d(%d), %s parameter read error(ok) count = %d(%d).\n' %
|
||||
(dut_master_thread.tname, dut_master_thread.param_fail_count, dut_master_thread.param_ok_count,
|
||||
dut_slave_thread.tname, dut_slave_thread.param_fail_count, dut_slave_thread.param_ok_count))
|
||||
logger.info("TEST_SUCCESS: The Modbus parameter test is completed successfully.\n")
|
||||
logger.info('TEST_SUCCESS: The Modbus parameter test is completed successfully.\n')
|
||||
|
||||
finally:
|
||||
dut_master.close()
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
import re
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
from builtins import str
|
||||
from threading import Event, Thread
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
from threading import Thread, Event
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
import ttfw_idf
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
|
||||
event_client_connected = Event()
|
||||
event_stop_client = Event()
|
||||
event_client_received_correct = Event()
|
||||
event_client_received_binary = Event()
|
||||
message_log = ""
|
||||
message_log = ''
|
||||
|
||||
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
print('Connected with result code ' + str(rc))
|
||||
event_client_connected.set()
|
||||
client.subscribe("/topic/qos0")
|
||||
client.subscribe('/topic/qos0')
|
||||
|
||||
|
||||
def mqtt_client_task(client):
|
||||
@@ -36,33 +35,33 @@ def on_message(client, userdata, msg):
|
||||
global message_log
|
||||
global event_client_received_correct
|
||||
global event_client_received_binary
|
||||
if msg.topic == "/topic/binary":
|
||||
if msg.topic == '/topic/binary':
|
||||
binary = userdata
|
||||
size = os.path.getsize(binary)
|
||||
print("Receiving binary from esp and comparing with {}, size {}...".format(binary, size))
|
||||
with open(binary, "rb") as f:
|
||||
print('Receiving binary from esp and comparing with {}, size {}...'.format(binary, size))
|
||||
with open(binary, 'rb') as f:
|
||||
bin = f.read()
|
||||
if bin == msg.payload[:size]:
|
||||
print("...matches!")
|
||||
print('...matches!')
|
||||
event_client_received_binary.set()
|
||||
return
|
||||
else:
|
||||
recv_binary = binary + ".received"
|
||||
with open(recv_binary, "w") as fw:
|
||||
recv_binary = binary + '.received'
|
||||
with open(recv_binary, 'w') as fw:
|
||||
fw.write(msg.payload)
|
||||
raise ValueError('Received binary (saved as: {}) does not match the original file: {}'.format(recv_binary, binary))
|
||||
payload = msg.payload.decode()
|
||||
if not event_client_received_correct.is_set() and payload == "data":
|
||||
client.subscribe("/topic/binary")
|
||||
client.publish("/topic/qos0", "send binary please")
|
||||
if msg.topic == "/topic/qos0" and payload == "data":
|
||||
if not event_client_received_correct.is_set() and payload == 'data':
|
||||
client.subscribe('/topic/binary')
|
||||
client.publish('/topic/qos0', 'send binary please')
|
||||
if msg.topic == '/topic/qos0' and payload == 'data':
|
||||
event_client_received_correct.set()
|
||||
message_log += "Received data:" + msg.topic + " " + payload + "\n"
|
||||
message_log += 'Received data:' + msg.topic + ' ' + payload + '\n'
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_mqtt_ssl(env, extra_data):
|
||||
broker_url = ""
|
||||
broker_url = ''
|
||||
broker_port = 0
|
||||
"""
|
||||
steps: |
|
||||
@@ -72,15 +71,15 @@ def test_examples_protocol_mqtt_ssl(env, extra_data):
|
||||
4. Test ESP32 client received correct qos0 message
|
||||
5. Test python client receives binary data from running partition and compares it with the binary
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_ssl", "examples/protocols/mqtt/ssl", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('mqtt_ssl', 'examples/protocols/mqtt/ssl', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_ssl.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'mqtt_ssl.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("mqtt_ssl_bin_size", "{}KB"
|
||||
ttfw_idf.log_performance('mqtt_ssl_bin_size', '{}KB'
|
||||
.format(bin_size // 1024))
|
||||
# Look for host:port in sdkconfig
|
||||
try:
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()['CONFIG_BROKER_URI'])
|
||||
broker_url = value.group(1)
|
||||
broker_port = int(value.group(2))
|
||||
except Exception:
|
||||
@@ -97,31 +96,31 @@ def test_examples_protocol_mqtt_ssl(env, extra_data):
|
||||
None,
|
||||
None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
|
||||
client.tls_insecure_set(True)
|
||||
print("Connecting...")
|
||||
print('Connecting...')
|
||||
client.connect(broker_url, broker_port, 60)
|
||||
except Exception:
|
||||
print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
|
||||
print('ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:'.format(broker_url, sys.exc_info()[0]))
|
||||
raise
|
||||
# Starting a py-client in a separate thread
|
||||
thread1 = Thread(target=mqtt_client_task, args=(client,))
|
||||
thread1.start()
|
||||
try:
|
||||
print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
|
||||
print('Connecting py-client to broker {}:{}...'.format(broker_url, broker_port))
|
||||
if not event_client_connected.wait(timeout=30):
|
||||
raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
|
||||
raise ValueError('ENV_TEST_FAILURE: Test script cannot connect to broker: {}'.format(broker_url))
|
||||
dut1.start_app()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
ip_address = dut1.expect(re.compile(r' sta ip: ([^,]+),'), timeout=30)
|
||||
print('Connected to AP with IP: {}'.format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
print('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
raise
|
||||
print("Checking py-client received msg published from esp...")
|
||||
print('Checking py-client received msg published from esp...')
|
||||
if not event_client_received_correct.wait(timeout=30):
|
||||
raise ValueError('Wrong data received, msg log: {}'.format(message_log))
|
||||
print("Checking esp-client received msg published from py-client...")
|
||||
dut1.expect(re.compile(r"DATA=send binary please"), timeout=30)
|
||||
print("Receiving binary data from running partition...")
|
||||
print('Checking esp-client received msg published from py-client...')
|
||||
dut1.expect(re.compile(r'DATA=send binary please'), timeout=30)
|
||||
print('Receiving binary data from running partition...')
|
||||
if not event_client_received_binary.wait(timeout=30):
|
||||
raise ValueError('Binary not received within timeout')
|
||||
finally:
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import socket
|
||||
from threading import Thread
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from threading import Thread
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import DUT
|
||||
|
||||
msgid = -1
|
||||
|
||||
|
||||
def get_my_ip():
|
||||
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s1.connect(("8.8.8.8", 80))
|
||||
s1.connect(('8.8.8.8', 80))
|
||||
my_ip = s1.getsockname()[0]
|
||||
s1.close()
|
||||
return my_ip
|
||||
@@ -22,7 +22,7 @@ def get_my_ip():
|
||||
|
||||
def mqqt_server_sketch(my_ip, port):
|
||||
global msgid
|
||||
print("Starting the server on {}".format(my_ip))
|
||||
print('Starting the server on {}'.format(my_ip))
|
||||
s = None
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
@@ -31,29 +31,29 @@ def mqqt_server_sketch(my_ip, port):
|
||||
s.listen(1)
|
||||
q,addr = s.accept()
|
||||
q.settimeout(30)
|
||||
print("connection accepted")
|
||||
print('connection accepted')
|
||||
except Exception:
|
||||
print("Local server on {}:{} listening/accepting failure: {}"
|
||||
"Possibly check permissions or firewall settings"
|
||||
"to accept connections on this address".format(my_ip, port, sys.exc_info()[0]))
|
||||
print('Local server on {}:{} listening/accepting failure: {}'
|
||||
'Possibly check permissions or firewall settings'
|
||||
'to accept connections on this address'.format(my_ip, port, sys.exc_info()[0]))
|
||||
raise
|
||||
data = q.recv(1024)
|
||||
# check if received initial empty message
|
||||
print("received from client {}".format(data))
|
||||
print('received from client {}'.format(data))
|
||||
data = bytearray([0x20, 0x02, 0x00, 0x00])
|
||||
q.send(data)
|
||||
# try to receive qos1
|
||||
data = q.recv(1024)
|
||||
msgid = struct.unpack(">H", data[15:17])[0]
|
||||
print("received from client {}, msgid: {}".format(data, msgid))
|
||||
msgid = struct.unpack('>H', data[15:17])[0]
|
||||
print('received from client {}, msgid: {}'.format(data, msgid))
|
||||
data = bytearray([0x40, 0x02, data[15], data[16]])
|
||||
q.send(data)
|
||||
time.sleep(5)
|
||||
s.close()
|
||||
print("server closed")
|
||||
print('server closed')
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_mqtt_qos1(env, extra_data):
|
||||
global msgid
|
||||
"""
|
||||
@@ -63,11 +63,11 @@ def test_examples_protocol_mqtt_qos1(env, extra_data):
|
||||
3. Test evaluates that qos1 message is queued and removed from queued after ACK received
|
||||
4. Test the broker received the same message id evaluated in step 3
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_tcp", "examples/protocols/mqtt/tcp", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('mqtt_tcp', 'examples/protocols/mqtt/tcp', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_tcp.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'mqtt_tcp.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("mqtt_tcp_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('mqtt_tcp_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# 1. start mqtt broker sketch
|
||||
host_ip = get_my_ip()
|
||||
thread1 = Thread(target=mqqt_server_sketch, args=(host_ip,1883))
|
||||
@@ -76,23 +76,23 @@ def test_examples_protocol_mqtt_qos1(env, extra_data):
|
||||
dut1.start_app()
|
||||
# waiting for getting the IP address
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
ip_address = dut1.expect(re.compile(r' sta ip: ([^,]+),'), timeout=30)
|
||||
print('Connected to AP with IP: {}'.format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
|
||||
print("writing to device: {}".format("mqtt://" + host_ip + "\n"))
|
||||
dut1.write("mqtt://" + host_ip + "\n")
|
||||
print('writing to device: {}'.format('mqtt://' + host_ip + '\n'))
|
||||
dut1.write('mqtt://' + host_ip + '\n')
|
||||
thread1.join()
|
||||
print("Message id received from server: {}".format(msgid))
|
||||
print('Message id received from server: {}'.format(msgid))
|
||||
# 3. check the message id was enqueued and then deleted
|
||||
msgid_enqueued = dut1.expect(re.compile(r"OUTBOX: ENQUEUE msgid=([0-9]+)"), timeout=30)
|
||||
msgid_deleted = dut1.expect(re.compile(r"OUTBOX: DELETED msgid=([0-9]+)"), timeout=30)
|
||||
msgid_enqueued = dut1.expect(re.compile(r'OUTBOX: ENQUEUE msgid=([0-9]+)'), timeout=30)
|
||||
msgid_deleted = dut1.expect(re.compile(r'OUTBOX: DELETED msgid=([0-9]+)'), timeout=30)
|
||||
# 4. check the msgid of received data are the same as that of enqueued and deleted from outbox
|
||||
if (msgid_enqueued[0] == str(msgid) and msgid_deleted[0] == str(msgid)):
|
||||
print("PASS: Received correct msg id")
|
||||
print('PASS: Received correct msg id')
|
||||
else:
|
||||
print("Failure!")
|
||||
print('Failure!')
|
||||
raise ValueError('Mismatch of msgid: received: {}, enqueued {}, deleted {}'.format(msgid, msgid_enqueued, msgid_deleted))
|
||||
|
||||
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import paho.mqtt.client as mqtt
|
||||
from threading import Thread, Event
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from builtins import str
|
||||
from threading import Event, Thread
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import DUT
|
||||
|
||||
event_client_connected = Event()
|
||||
event_stop_client = Event()
|
||||
event_client_received_correct = Event()
|
||||
message_log = ""
|
||||
message_log = ''
|
||||
|
||||
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
print('Connected with result code ' + str(rc))
|
||||
event_client_connected.set()
|
||||
client.subscribe("/topic/qos0")
|
||||
client.subscribe('/topic/qos0')
|
||||
|
||||
|
||||
def mqtt_client_task(client):
|
||||
@@ -32,16 +32,16 @@ def mqtt_client_task(client):
|
||||
def on_message(client, userdata, msg):
|
||||
global message_log
|
||||
payload = msg.payload.decode()
|
||||
if not event_client_received_correct.is_set() and payload == "data":
|
||||
client.publish("/topic/qos0", "data_to_esp32")
|
||||
if msg.topic == "/topic/qos0" and payload == "data":
|
||||
if not event_client_received_correct.is_set() and payload == 'data':
|
||||
client.publish('/topic/qos0', 'data_to_esp32')
|
||||
if msg.topic == '/topic/qos0' and payload == 'data':
|
||||
event_client_received_correct.set()
|
||||
message_log += "Received data:" + msg.topic + " " + payload + "\n"
|
||||
message_log += 'Received data:' + msg.topic + ' ' + payload + '\n'
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_mqtt_ws(env, extra_data):
|
||||
broker_url = ""
|
||||
broker_url = ''
|
||||
broker_port = 0
|
||||
"""
|
||||
steps: |
|
||||
@@ -50,14 +50,14 @@ def test_examples_protocol_mqtt_ws(env, extra_data):
|
||||
3. Test evaluates it received correct qos0 message
|
||||
4. Test ESP32 client received correct qos0 message
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_websocket", "examples/protocols/mqtt/ws", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('mqtt_websocket', 'examples/protocols/mqtt/ws', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_websocket.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'mqtt_websocket.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("mqtt_websocket_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('mqtt_websocket_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# Look for host:port in sdkconfig
|
||||
try:
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()['CONFIG_BROKER_URI'])
|
||||
broker_url = value.group(1)
|
||||
broker_port = int(value.group(2))
|
||||
except Exception:
|
||||
@@ -66,33 +66,33 @@ def test_examples_protocol_mqtt_ws(env, extra_data):
|
||||
client = None
|
||||
# 1. Test connects to a broker
|
||||
try:
|
||||
client = mqtt.Client(transport="websockets")
|
||||
client = mqtt.Client(transport='websockets')
|
||||
client.on_connect = on_connect
|
||||
client.on_message = on_message
|
||||
print("Connecting...")
|
||||
print('Connecting...')
|
||||
client.connect(broker_url, broker_port, 60)
|
||||
except Exception:
|
||||
print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
|
||||
print('ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:'.format(broker_url, sys.exc_info()[0]))
|
||||
raise
|
||||
# Starting a py-client in a separate thread
|
||||
thread1 = Thread(target=mqtt_client_task, args=(client,))
|
||||
thread1.start()
|
||||
try:
|
||||
print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
|
||||
print('Connecting py-client to broker {}:{}...'.format(broker_url, broker_port))
|
||||
if not event_client_connected.wait(timeout=30):
|
||||
raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
|
||||
raise ValueError('ENV_TEST_FAILURE: Test script cannot connect to broker: {}'.format(broker_url))
|
||||
dut1.start_app()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
ip_address = dut1.expect(re.compile(r' sta ip: ([^,]+),'), timeout=30)
|
||||
print('Connected to AP with IP: {}'.format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
print('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
raise
|
||||
print("Checking py-client received msg published from esp...")
|
||||
print('Checking py-client received msg published from esp...')
|
||||
if not event_client_received_correct.wait(timeout=30):
|
||||
raise ValueError('Wrong data received, msg log: {}'.format(message_log))
|
||||
print("Checking esp-client received msg published from py-client...")
|
||||
dut1.expect(re.compile(r"DATA=data_to_esp32"), timeout=30)
|
||||
print('Checking esp-client received msg published from py-client...')
|
||||
dut1.expect(re.compile(r'DATA=data_to_esp32'), timeout=30)
|
||||
finally:
|
||||
event_stop_client.set()
|
||||
thread1.join()
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
from __future__ import unicode_literals
|
||||
from __future__ import unicode_literals
|
||||
from builtins import str
|
||||
import re
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
from builtins import str
|
||||
from threading import Event, Thread
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
from threading import Thread, Event
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
import ttfw_idf
|
||||
|
||||
from tiny_test_fw import DUT
|
||||
|
||||
event_client_connected = Event()
|
||||
event_stop_client = Event()
|
||||
event_client_received_correct = Event()
|
||||
message_log = ""
|
||||
message_log = ''
|
||||
|
||||
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print("Connected with result code " + str(rc))
|
||||
print('Connected with result code ' + str(rc))
|
||||
event_client_connected.set()
|
||||
client.subscribe("/topic/qos0")
|
||||
client.subscribe('/topic/qos0')
|
||||
|
||||
|
||||
def mqtt_client_task(client):
|
||||
@@ -34,16 +33,16 @@ def mqtt_client_task(client):
|
||||
def on_message(client, userdata, msg):
|
||||
global message_log
|
||||
payload = msg.payload.decode()
|
||||
if not event_client_received_correct.is_set() and payload == "data":
|
||||
client.publish("/topic/qos0", "data_to_esp32")
|
||||
if msg.topic == "/topic/qos0" and payload == "data":
|
||||
if not event_client_received_correct.is_set() and payload == 'data':
|
||||
client.publish('/topic/qos0', 'data_to_esp32')
|
||||
if msg.topic == '/topic/qos0' and payload == 'data':
|
||||
event_client_received_correct.set()
|
||||
message_log += "Received data:" + msg.topic + " " + payload + "\n"
|
||||
message_log += 'Received data:' + msg.topic + ' ' + payload + '\n'
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_mqtt_wss(env, extra_data):
|
||||
broker_url = ""
|
||||
broker_url = ''
|
||||
broker_port = 0
|
||||
"""
|
||||
steps: |
|
||||
@@ -52,14 +51,14 @@ def test_examples_protocol_mqtt_wss(env, extra_data):
|
||||
3. Test evaluates it received correct qos0 message
|
||||
4. Test ESP32 client received correct qos0 message
|
||||
"""
|
||||
dut1 = env.get_dut("mqtt_websocket_secure", "examples/protocols/mqtt/wss", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('mqtt_websocket_secure', 'examples/protocols/mqtt/wss', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "mqtt_websocket_secure.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'mqtt_websocket_secure.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("mqtt_websocket_secure_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('mqtt_websocket_secure_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
# Look for host:port in sdkconfig
|
||||
try:
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()["CONFIG_BROKER_URI"])
|
||||
value = re.search(r'\:\/\/([^:]+)\:([0-9]+)', dut1.app.get_sdkconfig()['CONFIG_BROKER_URI'])
|
||||
broker_url = value.group(1)
|
||||
broker_port = int(value.group(2))
|
||||
except Exception:
|
||||
@@ -68,36 +67,36 @@ def test_examples_protocol_mqtt_wss(env, extra_data):
|
||||
client = None
|
||||
# 1. Test connects to a broker
|
||||
try:
|
||||
client = mqtt.Client(transport="websockets")
|
||||
client = mqtt.Client(transport='websockets')
|
||||
client.on_connect = on_connect
|
||||
client.on_message = on_message
|
||||
client.tls_set(None,
|
||||
None,
|
||||
None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
|
||||
print("Connecting...")
|
||||
print('Connecting...')
|
||||
client.connect(broker_url, broker_port, 60)
|
||||
except Exception:
|
||||
print("ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:".format(broker_url, sys.exc_info()[0]))
|
||||
print('ENV_TEST_FAILURE: Unexpected error while connecting to broker {}: {}:'.format(broker_url, sys.exc_info()[0]))
|
||||
raise
|
||||
# Starting a py-client in a separate thread
|
||||
thread1 = Thread(target=mqtt_client_task, args=(client,))
|
||||
thread1.start()
|
||||
try:
|
||||
print("Connecting py-client to broker {}:{}...".format(broker_url, broker_port))
|
||||
print('Connecting py-client to broker {}:{}...'.format(broker_url, broker_port))
|
||||
if not event_client_connected.wait(timeout=30):
|
||||
raise ValueError("ENV_TEST_FAILURE: Test script cannot connect to broker: {}".format(broker_url))
|
||||
raise ValueError('ENV_TEST_FAILURE: Test script cannot connect to broker: {}'.format(broker_url))
|
||||
dut1.start_app()
|
||||
try:
|
||||
ip_address = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
print("Connected to AP with IP: {}".format(ip_address))
|
||||
ip_address = dut1.expect(re.compile(r' sta ip: ([^,]+),'), timeout=30)
|
||||
print('Connected to AP with IP: {}'.format(ip_address))
|
||||
except DUT.ExpectTimeout:
|
||||
print('ENV_TEST_FAILURE: Cannot connect to AP')
|
||||
raise
|
||||
print("Checking py-client received msg published from esp...")
|
||||
print('Checking py-client received msg published from esp...')
|
||||
if not event_client_received_correct.wait(timeout=30):
|
||||
raise ValueError('Wrong data received, msg log: {}'.format(message_log))
|
||||
print("Checking esp-client received msg published from py-client...")
|
||||
dut1.expect(re.compile(r"DATA=data_to_esp32"), timeout=30)
|
||||
print('Checking esp-client received msg published from py-client...')
|
||||
dut1.expect(re.compile(r'DATA=data_to_esp32'), timeout=30)
|
||||
finally:
|
||||
event_stop_client.set()
|
||||
thread1.join()
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
from __future__ import unicode_literals
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
import os
|
||||
import serial
|
||||
import threading
|
||||
import time
|
||||
|
||||
import serial
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
|
||||
class SerialThread(object):
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from __future__ import unicode_literals
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
import datetime
|
||||
import re
|
||||
|
||||
import ttfw_idf
|
||||
from tiny_test_fw import Utility
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import input
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import netifaces
|
||||
import socket
|
||||
from threading import Thread, Event
|
||||
import ttfw_idf
|
||||
import sys
|
||||
from builtins import input
|
||||
from threading import Event, Thread
|
||||
|
||||
import netifaces
|
||||
import ttfw_idf
|
||||
|
||||
# ----------- Config ----------
|
||||
PORT = 3333
|
||||
@@ -26,7 +26,7 @@ INTERFACE = 'eth0'
|
||||
|
||||
def get_my_ip(type):
|
||||
for i in netifaces.ifaddresses(INTERFACE)[type]:
|
||||
return i['addr'].replace("%{}".format(INTERFACE), "")
|
||||
return i['addr'].replace('%{}'.format(INTERFACE), '')
|
||||
|
||||
|
||||
class TcpServer:
|
||||
@@ -44,11 +44,11 @@ class TcpServer:
|
||||
try:
|
||||
self.socket.bind(('', self.port))
|
||||
except socket.error as e:
|
||||
print("Bind failed:{}".format(e))
|
||||
print('Bind failed:{}'.format(e))
|
||||
raise
|
||||
self.socket.listen(1)
|
||||
|
||||
print("Starting server on port={} family_addr={}".format(self.port, self.family_addr))
|
||||
print('Starting server on port={} family_addr={}'.format(self.port, self.family_addr))
|
||||
self.server_thread = Thread(target=self.run_server)
|
||||
self.server_thread.start()
|
||||
return self
|
||||
@@ -68,7 +68,7 @@ class TcpServer:
|
||||
while not self.shutdown.is_set():
|
||||
try:
|
||||
conn, address = self.socket.accept() # accept new connection
|
||||
print("Connection from: {}".format(address))
|
||||
print('Connection from: {}'.format(address))
|
||||
conn.setblocking(1)
|
||||
data = conn.recv(1024)
|
||||
if not data:
|
||||
@@ -79,13 +79,13 @@ class TcpServer:
|
||||
conn.send(reply.encode())
|
||||
conn.close()
|
||||
except socket.error as e:
|
||||
print("Running server failed:{}".format(e))
|
||||
print('Running server failed:{}'.format(e))
|
||||
raise
|
||||
if not self.persist:
|
||||
break
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_socket_tcpclient(env, extra_data):
|
||||
"""
|
||||
steps:
|
||||
@@ -93,39 +93,39 @@ def test_examples_protocol_socket_tcpclient(env, extra_data):
|
||||
2. have the board connect to the server
|
||||
3. send and receive data
|
||||
"""
|
||||
dut1 = env.get_dut("tcp_client", "examples/protocols/sockets/tcp_client", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('tcp_client', 'examples/protocols/sockets/tcp_client', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "tcp_client.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'tcp_client.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("tcp_client_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('tcp_client_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# start test
|
||||
dut1.start_app()
|
||||
|
||||
ipv4 = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)[0]
|
||||
ipv4 = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)[0]
|
||||
ipv6_r = r':'.join((r'[0-9a-fA-F]{4}',) * 8) # expect all 8 octets from IPv6 (assumes it's printed in the long form)
|
||||
ipv6 = dut1.expect(re.compile(r' IPv6 address: ({})'.format(ipv6_r)), timeout=30)[0]
|
||||
print("Connected with IPv4={} and IPv6={}".format(ipv4, ipv6))
|
||||
print('Connected with IPv4={} and IPv6={}'.format(ipv4, ipv6))
|
||||
|
||||
# test IPv4
|
||||
with TcpServer(PORT, socket.AF_INET):
|
||||
server_ip = get_my_ip(netifaces.AF_INET)
|
||||
print("Connect tcp client to server IP={}".format(server_ip))
|
||||
print('Connect tcp client to server IP={}'.format(server_ip))
|
||||
dut1.write(server_ip)
|
||||
dut1.expect(re.compile(r"OK: Message from ESP32"))
|
||||
dut1.expect(re.compile(r'OK: Message from ESP32'))
|
||||
# test IPv6
|
||||
with TcpServer(PORT, socket.AF_INET6):
|
||||
server_ip = get_my_ip(netifaces.AF_INET6)
|
||||
print("Connect tcp client to server IP={}".format(server_ip))
|
||||
print('Connect tcp client to server IP={}'.format(server_ip))
|
||||
dut1.write(server_ip)
|
||||
dut1.expect(re.compile(r"OK: Message from ESP32"))
|
||||
dut1.expect(re.compile(r'OK: Message from ESP32'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if sys.argv[1:] and sys.argv[1].startswith("IPv"): # if additional arguments provided:
|
||||
if sys.argv[1:] and sys.argv[1].startswith('IPv'): # if additional arguments provided:
|
||||
# Usage: example_test.py <IPv4|IPv6>
|
||||
family_addr = socket.AF_INET6 if sys.argv[1] == "IPv6" else socket.AF_INET
|
||||
family_addr = socket.AF_INET6 if sys.argv[1] == 'IPv6' else socket.AF_INET
|
||||
with TcpServer(PORT, family_addr, persist=True) as s:
|
||||
print(input("Press Enter stop the server..."))
|
||||
print(input('Press Enter stop the server...'))
|
||||
else:
|
||||
test_examples_protocol_socket_tcpclient()
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import socket
|
||||
import ttfw_idf
|
||||
import sys
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
# ----------- Config ----------
|
||||
PORT = 3333
|
||||
@@ -46,28 +46,28 @@ def tcp_client(address, payload):
|
||||
return data.decode()
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_socket_tcpserver(env, extra_data):
|
||||
MESSAGE = "Data to ESP"
|
||||
MESSAGE = 'Data to ESP'
|
||||
"""
|
||||
steps:
|
||||
1. join AP
|
||||
2. have the board connect to the server
|
||||
3. send and receive data
|
||||
"""
|
||||
dut1 = env.get_dut("tcp_client", "examples/protocols/sockets/tcp_server", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('tcp_client', 'examples/protocols/sockets/tcp_server', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "tcp_server.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'tcp_server.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("tcp_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('tcp_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# start test
|
||||
dut1.start_app()
|
||||
|
||||
ipv4 = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)[0]
|
||||
ipv4 = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)[0]
|
||||
ipv6_r = r':'.join((r'[0-9a-fA-F]{4}',) * 8) # expect all 8 octets from IPv6 (assumes it's printed in the long form)
|
||||
ipv6 = dut1.expect(re.compile(r' IPv6 address: ({})'.format(ipv6_r)), timeout=30)[0]
|
||||
print("Connected with IPv4={} and IPv6={}".format(ipv4, ipv6))
|
||||
print('Connected with IPv4={} and IPv6={}'.format(ipv4, ipv6))
|
||||
|
||||
# test IPv4
|
||||
received = tcp_client(ipv4, MESSAGE)
|
||||
@@ -75,7 +75,7 @@ def test_examples_protocol_socket_tcpserver(env, extra_data):
|
||||
raise
|
||||
dut1.expect(MESSAGE)
|
||||
# test IPv6
|
||||
received = tcp_client("{}%{}".format(ipv6, INTERFACE), MESSAGE)
|
||||
received = tcp_client('{}%{}'.format(ipv6, INTERFACE), MESSAGE)
|
||||
if not received == MESSAGE:
|
||||
raise
|
||||
dut1.expect(MESSAGE)
|
||||
|
||||
@@ -6,17 +6,17 @@
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from builtins import input
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import re
|
||||
import netifaces
|
||||
import socket
|
||||
from threading import Thread, Event
|
||||
import ttfw_idf
|
||||
import sys
|
||||
from builtins import input
|
||||
from threading import Event, Thread
|
||||
|
||||
import netifaces
|
||||
import ttfw_idf
|
||||
|
||||
# ----------- Config ----------
|
||||
PORT = 3333
|
||||
@@ -26,7 +26,7 @@ INTERFACE = 'eth0'
|
||||
|
||||
def get_my_ip(type):
|
||||
for i in netifaces.ifaddresses(INTERFACE)[type]:
|
||||
return i['addr'].replace("%{}".format(INTERFACE), "")
|
||||
return i['addr'].replace('%{}'.format(INTERFACE), '')
|
||||
|
||||
|
||||
class UdpServer:
|
||||
@@ -44,10 +44,10 @@ class UdpServer:
|
||||
try:
|
||||
self.socket.bind(('', self.port))
|
||||
except socket.error as e:
|
||||
print("Bind failed:{}".format(e))
|
||||
print('Bind failed:{}'.format(e))
|
||||
raise
|
||||
|
||||
print("Starting server on port={} family_addr={}".format(self.port, self.family_addr))
|
||||
print('Starting server on port={} family_addr={}'.format(self.port, self.family_addr))
|
||||
self.server_thread = Thread(target=self.run_server)
|
||||
self.server_thread.start()
|
||||
return self
|
||||
@@ -72,13 +72,13 @@ class UdpServer:
|
||||
reply = 'OK: ' + data
|
||||
self.socket.sendto(reply.encode(), addr)
|
||||
except socket.error as e:
|
||||
print("Running server failed:{}".format(e))
|
||||
print('Running server failed:{}'.format(e))
|
||||
raise
|
||||
if not self.persist:
|
||||
break
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_socket_udpclient(env, extra_data):
|
||||
"""
|
||||
steps:
|
||||
@@ -86,39 +86,39 @@ def test_examples_protocol_socket_udpclient(env, extra_data):
|
||||
2. have the board connect to the server
|
||||
3. send and receive data
|
||||
"""
|
||||
dut1 = env.get_dut("udp_client", "examples/protocols/sockets/udp_client", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('udp_client', 'examples/protocols/sockets/udp_client', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "udp_client.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'udp_client.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("udp_client_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('udp_client_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# start test
|
||||
dut1.start_app()
|
||||
|
||||
ipv4 = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)[0]
|
||||
ipv4 = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)[0]
|
||||
ipv6_r = r':'.join((r'[0-9a-fA-F]{4}',) * 8) # expect all 8 octets from IPv6 (assumes it's printed in the long form)
|
||||
ipv6 = dut1.expect(re.compile(r' IPv6 address: ({})'.format(ipv6_r)), timeout=30)[0]
|
||||
print("Connected with IPv4={} and IPv6={}".format(ipv4, ipv6))
|
||||
print('Connected with IPv4={} and IPv6={}'.format(ipv4, ipv6))
|
||||
|
||||
# test IPv4
|
||||
with UdpServer(PORT, socket.AF_INET):
|
||||
server_ip = get_my_ip(netifaces.AF_INET)
|
||||
print("Connect udp client to server IP={}".format(server_ip))
|
||||
print('Connect udp client to server IP={}'.format(server_ip))
|
||||
dut1.write(server_ip)
|
||||
dut1.expect(re.compile(r"OK: Message from ESP32"))
|
||||
dut1.expect(re.compile(r'OK: Message from ESP32'))
|
||||
# test IPv6
|
||||
with UdpServer(PORT, socket.AF_INET6):
|
||||
server_ip = get_my_ip(netifaces.AF_INET6)
|
||||
print("Connect udp client to server IP={}".format(server_ip))
|
||||
print('Connect udp client to server IP={}'.format(server_ip))
|
||||
dut1.write(server_ip)
|
||||
dut1.expect(re.compile(r"OK: Message from ESP32"))
|
||||
dut1.expect(re.compile(r'OK: Message from ESP32'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if sys.argv[1:] and sys.argv[1].startswith("IPv"): # if additional arguments provided:
|
||||
if sys.argv[1:] and sys.argv[1].startswith('IPv'): # if additional arguments provided:
|
||||
# Usage: example_test.py <IPv4|IPv6>
|
||||
family_addr = socket.AF_INET6 if sys.argv[1] == "IPv6" else socket.AF_INET
|
||||
family_addr = socket.AF_INET6 if sys.argv[1] == 'IPv6' else socket.AF_INET
|
||||
with UdpServer(PORT, family_addr, persist=True) as s:
|
||||
print(input("Press Enter stop the server..."))
|
||||
print(input('Press Enter stop the server...'))
|
||||
else:
|
||||
test_examples_protocol_socket_udpclient()
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import socket
|
||||
import ttfw_idf
|
||||
import sys
|
||||
|
||||
import ttfw_idf
|
||||
|
||||
# ----------- Config ----------
|
||||
PORT = 3333
|
||||
@@ -44,28 +44,28 @@ def udp_client(address, payload):
|
||||
return reply.decode()
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_socket_udpserver(env, extra_data):
|
||||
MESSAGE = "Data to ESP"
|
||||
MESSAGE = 'Data to ESP'
|
||||
"""
|
||||
steps:
|
||||
1. join AP
|
||||
2. have the board connect to the server
|
||||
3. send and receive data
|
||||
"""
|
||||
dut1 = env.get_dut("udp_server", "examples/protocols/sockets/udp_server", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('udp_server', 'examples/protocols/sockets/udp_server', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "udp_server.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'udp_server.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("udp_server_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('udp_server_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
# start test
|
||||
dut1.start_app()
|
||||
|
||||
ipv4 = dut1.expect(re.compile(r" IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)"), timeout=30)[0]
|
||||
ipv4 = dut1.expect(re.compile(r' IPv4 address: ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)'), timeout=30)[0]
|
||||
ipv6_r = r':'.join((r'[0-9a-fA-F]{4}',) * 8) # expect all 8 octets from IPv6 (assumes it's printed in the long form)
|
||||
ipv6 = dut1.expect(re.compile(r' IPv6 address: ({})'.format(ipv6_r)), timeout=30)[0]
|
||||
print("Connected with IPv4={} and IPv6={}".format(ipv4, ipv6))
|
||||
print('Connected with IPv4={} and IPv6={}'.format(ipv4, ipv6))
|
||||
|
||||
# test IPv4
|
||||
received = udp_client(ipv4, MESSAGE)
|
||||
@@ -73,7 +73,7 @@ def test_examples_protocol_socket_udpserver(env, extra_data):
|
||||
raise
|
||||
dut1.expect(MESSAGE)
|
||||
# test IPv6
|
||||
received = udp_client("{}%{}".format(ipv6, INTERFACE), MESSAGE)
|
||||
received = udp_client('{}%{}'.format(ipv6, INTERFACE), MESSAGE)
|
||||
if not received == MESSAGE:
|
||||
raise
|
||||
dut1.expect(MESSAGE)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
from __future__ import print_function
|
||||
from __future__ import unicode_literals
|
||||
import re
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
import os
|
||||
import socket
|
||||
import random
|
||||
import re
|
||||
import socket
|
||||
import string
|
||||
from threading import Event, Thread
|
||||
|
||||
import ttfw_idf
|
||||
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
|
||||
from tiny_test_fw import Utility
|
||||
from threading import Thread, Event
|
||||
import ttfw_idf
|
||||
|
||||
|
||||
def get_my_ip():
|
||||
@@ -66,15 +67,15 @@ class Websocket(object):
|
||||
|
||||
|
||||
def test_echo(dut):
|
||||
dut.expect("WEBSOCKET_EVENT_CONNECTED")
|
||||
dut.expect('WEBSOCKET_EVENT_CONNECTED')
|
||||
for i in range(0, 10):
|
||||
dut.expect(re.compile(r"Received=hello (\d)"), timeout=30)
|
||||
print("All echos received")
|
||||
dut.expect(re.compile(r'Received=hello (\d)'), timeout=30)
|
||||
print('All echos received')
|
||||
|
||||
|
||||
def test_close(dut):
|
||||
code = dut.expect(re.compile(r"WEBSOCKET: Received closed message with code=(\d*)"), timeout=60)[0]
|
||||
print("Received close frame with code {}".format(code))
|
||||
code = dut.expect(re.compile(r'WEBSOCKET: Received closed message with code=(\d*)'), timeout=60)[0]
|
||||
print('Received close frame with code {}'.format(code))
|
||||
|
||||
|
||||
def test_recv_long_msg(dut, websocket, msg_len, repeats):
|
||||
@@ -86,17 +87,17 @@ def test_recv_long_msg(dut, websocket, msg_len, repeats):
|
||||
recv_msg = ''
|
||||
while len(recv_msg) < msg_len:
|
||||
# Filter out color encoding
|
||||
match = dut.expect(re.compile(r"Received=([a-zA-Z0-9]*).*\n"), timeout=30)[0]
|
||||
match = dut.expect(re.compile(r'Received=([a-zA-Z0-9]*).*\n'), timeout=30)[0]
|
||||
recv_msg += match
|
||||
|
||||
if recv_msg == send_msg:
|
||||
print("Sent message and received message are equal")
|
||||
print('Sent message and received message are equal')
|
||||
else:
|
||||
raise ValueError("DUT received string do not match sent string, \nexpected: {}\nwith length {}\
|
||||
\nreceived: {}\nwith length {}".format(send_msg, len(send_msg), recv_msg, len(recv_msg)))
|
||||
raise ValueError('DUT received string do not match sent string, \nexpected: {}\nwith length {}\
|
||||
\nreceived: {}\nwith length {}'.format(send_msg, len(send_msg), recv_msg, len(recv_msg)))
|
||||
|
||||
|
||||
@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
|
||||
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
|
||||
def test_examples_protocol_websocket(env, extra_data):
|
||||
"""
|
||||
steps:
|
||||
@@ -104,17 +105,17 @@ def test_examples_protocol_websocket(env, extra_data):
|
||||
2. connect to uri specified in the config
|
||||
3. send and receive data
|
||||
"""
|
||||
dut1 = env.get_dut("websocket", "examples/protocols/websocket", dut_class=ttfw_idf.ESP32DUT)
|
||||
dut1 = env.get_dut('websocket', 'examples/protocols/websocket', dut_class=ttfw_idf.ESP32DUT)
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "websocket-example.bin")
|
||||
binary_file = os.path.join(dut1.app.binary_path, 'websocket-example.bin')
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
ttfw_idf.log_performance("websocket_bin_size", "{}KB".format(bin_size // 1024))
|
||||
ttfw_idf.log_performance('websocket_bin_size', '{}KB'.format(bin_size // 1024))
|
||||
|
||||
try:
|
||||
if "CONFIG_WEBSOCKET_URI_FROM_STDIN" in dut1.app.get_sdkconfig():
|
||||
if 'CONFIG_WEBSOCKET_URI_FROM_STDIN' in dut1.app.get_sdkconfig():
|
||||
uri_from_stdin = True
|
||||
else:
|
||||
uri = dut1.app.get_sdkconfig()["CONFIG_WEBSOCKET_URI"].strip('"')
|
||||
uri = dut1.app.get_sdkconfig()['CONFIG_WEBSOCKET_URI'].strip('"')
|
||||
uri_from_stdin = False
|
||||
|
||||
except Exception:
|
||||
@@ -127,9 +128,9 @@ def test_examples_protocol_websocket(env, extra_data):
|
||||
if uri_from_stdin:
|
||||
server_port = 4455
|
||||
with Websocket(server_port) as ws:
|
||||
uri = "ws://{}:{}".format(get_my_ip(), server_port)
|
||||
print("DUT connecting to {}".format(uri))
|
||||
dut1.expect("Please enter uri of websocket endpoint", timeout=30)
|
||||
uri = 'ws://{}:{}'.format(get_my_ip(), server_port)
|
||||
print('DUT connecting to {}'.format(uri))
|
||||
dut1.expect('Please enter uri of websocket endpoint', timeout=30)
|
||||
dut1.write(uri)
|
||||
test_echo(dut1)
|
||||
# Message length should exceed DUT's buffer size to test fragmentation, default is 1024 byte
|
||||
@@ -137,7 +138,7 @@ def test_examples_protocol_websocket(env, extra_data):
|
||||
test_close(dut1)
|
||||
|
||||
else:
|
||||
print("DUT connecting to {}".format(uri))
|
||||
print('DUT connecting to {}'.format(uri))
|
||||
test_echo(dut1)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user