circuitpython/tests/net_inet/asyncio_tls_open_connection_readline.py
Damien George 2bba507148 tests: Require SSL certificate file to be available for test to run.
Previously, any test needing an SSL certificate file would automatically
skip if the file could not be found.  But that makes it too easy to
accidentally skip tests.

Instead, change it so that the test fails if the certificate file doesn't
exist.  That matches, for example, the fact that the test fails if
networking (LAN, WiFi) is not active.

Signed-off-by: Damien George <damien@micropython.org>
2025-08-15 01:03:00 +10:00

53 lines
1.6 KiB
Python

import ssl
import os
import asyncio
# This certificate was obtained from micropython.org using openssl:
# $ openssl s_client -showcerts -connect micropython.org:443 </dev/null 2>/dev/null
# The certificate is from Let's Encrypt:
# 1 s:/C=US/O=Let's Encrypt/CN=R3
# i:/C=US/O=Internet Security Research Group/CN=ISRG Root X1
# Validity
# Not Before: Sep 4 00:00:00 2020 GMT
# Not After : Sep 15 16:00:00 2025 GMT
# Copy PEM content to a file (certmpy.pem) and convert to DER e.g.
# $ openssl x509 -in certmpy.pem -out certmpy.der -outform DER
# Then convert to hex format, eg using binascii.hexlify(data).
# Note that the instructions above is to obtain an intermediate
# root CA cert that works for MicroPython. However CPython needs the ultimate root CA
# cert from ISRG
ca_cert_chain = "isrg.der"
with open(ca_cert_chain, "rb") as ca:
cadata = ca.read()
client_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
client_ctx.verify_mode = ssl.CERT_REQUIRED
client_ctx.load_verify_locations(cadata=cadata)
async def http_get(url, port, sslctx):
reader, writer = await asyncio.open_connection(url, port, ssl=sslctx)
print("write GET")
writer.write(b"GET / HTTP/1.0\r\n\r\n")
await writer.drain()
print("read response")
while True:
data = await reader.readline()
# avoid printing datetime which makes the test fail
if b"GMT" not in data:
print("read:", data)
if not data:
break
print("close")
writer.close()
await writer.wait_closed()
print("done")
asyncio.run(http_get("micropython.org", 443, client_ctx))