Files
tsun-gen3-proxy/app/tests/test_async_stream.py
Stefan Allius c956c13d13 Dev 0.11 (#200)
* Code Cleanup (#158)


* print coverage report

* create sonar-project property file

* install all py dependencies in one step

* code cleanup

* reduce cognitive complexity

* do not build on *.yml changes

* optimise versionstring handling (#159)

- Reading the version string from the image updates
  it even if the image is re-pulled without re-deployment

* fix linter warning

* exclude *.pyi filese

* ignore some rules for tests

* cleanup (#160)

* Sonar qube 3 (#163)

fix SonarQube warnings in modbus.py

* Sonar qube 3 (#164)


* fix SonarQube warnings

* Sonar qube 3 (#165)

* cleanup

* Add support for TSUN Titan inverter
Fixes #161


* fix SonarQube warnings

* fix error

* rename field "config"

* SonarQube reads flake8 output

* don't stop on flake8 errors

* flake8 scan only app/src for SonarQube

* update flake8 run

* ignore flake8 C901

* cleanup

* fix linter warnings

* ignore changed *.yml files

* read sensor list solarman data packets

* catch 'No route to' error and log only in debug mode

* fix unit tests

* add sensor_list configuration

* adapt unit tests

* fix SonarQube warnings

* Sonar qube 3 (#166)

* add unittests for mqtt.py

* add mock

* move test requirements into a file

* fix unit tests

* fix formating

* initial version

* fix SonarQube warning

* Sonar qube 4 (#169)

* add unit test for inverter.py

* fix SonarQube warning

* Sonar qube 5 (#170)

* fix SonarLints warnings

* use random IP adresses for unit tests

* Docker: The description ist missing (#171)

Fixes #167

* S allius/issue167 (#172)

* cleanup

* Sonar qube 6 (#174)

* test class ModbusConn

* Sonar qube 3 (#178)

* add more unit tests

* GEN3: don't crash on overwritten msg in the receive buffer

* improve test coverage und reduce test delays

* reduce cognitive complexity

* fix merge

* fix merge conflikt

* fix merge conflict

* S allius/issue182 (#183)

* GEN3: After inverter firmware update the 'Unknown Msg Type' increases continuously
Fixes #182

* add support for Controller serial no and MAC

* test hardening

* GEN3: add support for new messages of version 3 firmwares

* bump libraries to latest versions

- bump aiomqtt to version 2.3.0
- bump aiohttp to version 3.10.5

* improve test coverage

* reduce cognective complexity

* fix target preview

* remove dubbled fixtures

* increase test coverage

* Update README.md (#185)

update badges

* S allius/issue186 (#187)

* Parse more values in Server Mode
Fixes #186

* read OUTPUT_COEFFICIENT and MAC_ADDR in SrvMode

* fix unit test

* increase test coverage

* S allius/issue186 (#188)

* increase test coverage

* update changelog

* add dokumentation

* change default config

* Update README.md (#189)

Config file is now foldable

* GEN3: Invalid Contact Info Msg (#192)

Fixes #191

* Refactoring async stream (#194)

* GEN3: Invalid Contact Info Msg
Fixes #191

* introduce ifc with FIFOs

* add object factory

* use AsyncIfc class with FIFO

* declare more methods as classmethods

* - refactoring

- remove _forward_buffer
- make async_write private

* remove _forward_buffer

* refactoring

* avoid mqtt handling for invalid serial numbers

* add two more callbacks

* FIX update_header_cb handling

* split AsyncStream in two classes

* split ConnectionG3(P) in server and client class

* update class diagramm

* refactor server creation

* remove duplicated imports

* reduce code duplication

* move StremPtr instances into Inverter class

* resolution of connection classes

- remove ConnectionG3Client
- remove ConnectionG3Server
- remove ConnectionG3PClient
- remove ConnectionG3PServer

* fix server connections

* fix client loop closing

* don't overwrite self.remote in constructor

* update class diagramm

* fixes

- fixes null pointer accesses
- initalize AsyncStreamClient with proper
  StreamPtr instance

* add close callback

* refactor close handling

* remove connection classes

* move more code into InverterBase class

* remove test_inverter_base.py

* add abstract inverter interface class

* initial commit

* fix sonar qube warnings

* rename class Inverter into Proxy

* fix typo

* move class InverterIfc into a separate file

* add more testcases

* use ProtocolIfc class

* add unit tests for AsyncStream class

* icrease test coverage

* reduce cognitive complexity

* increase test coverage

* increase tes coverage

* simplify heartbeat handler

* remove obsolete tx_get method

* add more unittests

* update changelog

* remove __del__ method for proper gc runs

* check releasing of ModbusConn instances

* call garbage collector to release unreachable objs

* decrease ref counter after the with block

* S allius/issue196 (#198)

* fix healthcheck

- on infrastructure with IPv6 support localhost
  might be resolved to an IPv6 adress. Since the
  proxy only support IPv4 for now, we replace
  localhost by 127.0.0.1, to fix this

* merge from main
2024-10-13 18:12:10 +02:00

533 lines
14 KiB
Python

# test_with_pytest.py
import pytest
import asyncio
import gc
import time
from app.src.infos import Infos
from app.src.inverter_base import InverterBase
from app.src.async_stream import AsyncStreamServer, AsyncStreamClient, StreamPtr
from app.src.messages import Message
from app.tests.test_modbus_tcp import FakeReader, FakeWriter
from app.tests.test_inverter_base import config_conn, patch_open_connection
pytest_plugins = ('pytest_asyncio',)
# initialize the proxy statistics
Infos.static_init()
class FakeProto(Message):
def __init__(self, server_side):
super().__init__(server_side, None, 10)
self.conn_no = 0
def fake_reader_fwd():
reader = FakeReader()
reader.test = FakeReader.RD_TEST_13_BYTES
reader.on_recv.set()
return reader
def test_timeout_cb():
reader = FakeReader()
writer = FakeWriter()
def timeout():
return 13
ifc = AsyncStreamClient(reader, writer, None, None)
assert 360 == ifc._AsyncStream__timeout()
ifc.prot_set_timeout_cb(timeout)
assert 13 == ifc._AsyncStream__timeout()
ifc.prot_set_timeout_cb(None)
assert 360 == ifc._AsyncStream__timeout()
# call healthy outside the contexter manager (__exit__() was called)
assert ifc.healthy()
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
def test_health():
reader = FakeReader()
writer = FakeWriter()
ifc = AsyncStreamClient(reader, writer, None, None)
ifc.proc_start = time.time()
assert ifc.healthy()
ifc.proc_start = time.time() -10
assert not ifc.healthy()
ifc.proc_start = None
assert ifc.healthy()
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_close_cb():
assert asyncio.get_running_loop()
reader = FakeReader()
writer = FakeWriter()
cnt = 0
def timeout():
return 0.1
def closed():
nonlocal cnt
nonlocal ifc
ifc.close() # clears the closed callback
cnt += 1
cnt = 0
ifc = AsyncStreamClient(reader, writer, None, closed)
ifc.prot_set_timeout_cb(timeout)
await ifc.client_loop('')
assert cnt == 1
ifc.prot_set_timeout_cb(timeout)
await ifc.client_loop('')
assert cnt == 1 # check that the closed method would not be called
del ifc
cnt = 0
ifc = AsyncStreamClient(reader, writer, None, None)
ifc.prot_set_timeout_cb(timeout)
await ifc.client_loop('')
assert cnt == 0
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_read():
global test
assert asyncio.get_running_loop()
reader = FakeReader()
reader.test = FakeReader.RD_TEST_13_BYTES
reader.on_recv.set()
writer = FakeWriter()
cnt = 0
def timeout():
return 1
def closed():
nonlocal cnt
nonlocal ifc
ifc.close() # clears the closed callback
cnt += 1
def app_read():
nonlocal ifc
ifc.proc_start -= 3
return 0.01 # async wait of 0.01
cnt = 0
ifc = AsyncStreamClient(reader, writer, None, closed)
ifc.proc_max = 0
ifc.prot_set_timeout_cb(timeout)
ifc.rx_set_cb(app_read)
await ifc.client_loop('')
print('End loop')
assert ifc.proc_max >= 3
assert 13 == ifc.rx_len()
assert cnt == 1
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_write():
global test
assert asyncio.get_running_loop()
reader = FakeReader()
reader.test = FakeReader.RD_TEST_13_BYTES
reader.on_recv.set()
writer = FakeWriter()
cnt = 0
def timeout():
return 1
def closed():
nonlocal cnt
nonlocal ifc
ifc.close() # clears the closed callback
cnt += 1
def app_read():
nonlocal ifc
ifc.proc_start -= 3
return 0.01 # async wait of 0.01
cnt = 0
ifc = AsyncStreamClient(reader, writer, None, closed)
ifc.proc_max = 10
ifc.prot_set_timeout_cb(timeout)
ifc.rx_set_cb(app_read)
ifc.tx_add(b'test-data-resp')
assert 14 == ifc.tx_len()
await ifc.client_loop('')
print('End loop')
assert ifc.proc_max >= 3
assert 13 == ifc.rx_len()
assert 0 == ifc.tx_len()
assert cnt == 1
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_publ_mqtt_cb():
assert asyncio.get_running_loop()
reader = FakeReader()
reader.test = FakeReader.RD_TEST_13_BYTES
reader.on_recv.set()
writer = FakeWriter()
cnt = 0
def timeout():
return 0.1
async def publ_mqtt():
nonlocal cnt
nonlocal ifc
cnt += 1
cnt = 0
ifc = AsyncStreamServer(reader, writer, publ_mqtt, None, None)
assert ifc.async_publ_mqtt
ifc.prot_set_timeout_cb(timeout)
await ifc.server_loop()
assert cnt == 3 # 2 calls in server_loop() and 1 in loop()
assert ifc.async_publ_mqtt
ifc.close() # clears the closed callback
assert not ifc.async_publ_mqtt
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_create_remote_cb():
assert asyncio.get_running_loop()
reader = FakeReader()
writer = FakeWriter()
cnt = 0
def timeout():
return 0.1
async def create_remote():
nonlocal cnt
nonlocal ifc
ifc.close() # clears the closed callback
cnt += 1
cnt = 0
ifc = AsyncStreamServer(reader, writer, None, create_remote, None)
assert ifc.create_remote
await ifc.create_remote()
assert cnt == 1
ifc.prot_set_timeout_cb(timeout)
await ifc.server_loop()
assert not ifc.create_remote
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_sw_exception():
global test
assert asyncio.get_running_loop()
reader = FakeReader()
reader.test = FakeReader.RD_TEST_SW_EXCEPT
reader.on_recv.set()
writer = FakeWriter()
cnt = 0
def timeout():
return 1
def closed():
nonlocal cnt
nonlocal ifc
ifc.close() # clears the closed callback
cnt += 1
cnt = 0
ifc = AsyncStreamClient(reader, writer, None, closed)
ifc.prot_set_timeout_cb(timeout)
await ifc.client_loop('')
print('End loop')
assert cnt == 1
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
@pytest.mark.asyncio
async def test_os_error():
global test
assert asyncio.get_running_loop()
reader = FakeReader()
reader.test = FakeReader.RD_TEST_OS_ERROR
reader.on_recv.set()
writer = FakeWriter()
cnt = 0
def timeout():
return 1
def closed():
nonlocal cnt
nonlocal ifc
ifc.close() # clears the closed callback
cnt += 1
cnt = 0
ifc = AsyncStreamClient(reader, writer, None, closed)
ifc.prot_set_timeout_cb(timeout)
await ifc.client_loop('')
print('End loop')
assert cnt == 1
del ifc
cnt = 0
for inv in InverterBase:
print(f'InverterBase refs:{gc.get_referrers(inv)}')
cnt += 1
assert cnt == 0
class TestType():
FWD_NO_EXCPT = 1
FWD_SW_EXCPT = 2
FWD_TIMEOUT = 3
FWD_OS_ERROR = 4
FWD_OS_ERROR_NO_STREAM = 5
FWD_RUNTIME_ERROR = 6
FWD_RUNTIME_ERROR_NO_STREAM = 7
def create_remote(remote, test_type, with_close_hdr:bool = False):
def update_hdr(buf):
return
def callback():
if test_type == TestType.FWD_SW_EXCPT:
remote.unknown_var += 1
elif test_type == TestType.FWD_TIMEOUT:
raise TimeoutError
elif test_type == TestType.FWD_OS_ERROR:
raise ConnectionRefusedError
elif test_type == TestType.FWD_OS_ERROR_NO_STREAM:
remote.stream = None
raise ConnectionRefusedError
elif test_type == TestType.FWD_RUNTIME_ERROR:
raise RuntimeError("Peer closed")
elif test_type == TestType.FWD_RUNTIME_ERROR_NO_STREAM:
remote.stream = None
raise RuntimeError("Peer closed")
def close():
return
if with_close_hdr:
close_hndl = close
else:
close_hndl = None
remote.ifc = AsyncStreamClient(
FakeReader(), FakeWriter(), StreamPtr(None), close_hndl)
remote.ifc.prot_set_update_header_cb(update_hdr)
remote.ifc.prot_set_init_new_client_conn_cb(callback)
remote.stream = FakeProto(False)
@pytest.mark.asyncio
async def test_forward():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote, ifc
create_remote(remote, TestType.FWD_NO_EXCPT)
ifc.fwd_add(b'test-forward_msg2 ')
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_with_conn():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote, ifc
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
create_remote(remote, TestType.FWD_NO_EXCPT)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 0
del ifc
@pytest.mark.asyncio
async def test_forward_no_conn():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_sw_except():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_SW_EXCPT)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_os_error():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_OS_ERROR)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_os_error2():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_OS_ERROR, True)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_os_error3():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_OS_ERROR_NO_STREAM)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_runtime_error():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_RUNTIME_ERROR)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_runtime_error2():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_RUNTIME_ERROR, True)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc
@pytest.mark.asyncio
async def test_forward_runtime_error3():
assert asyncio.get_running_loop()
remote = StreamPtr(None)
cnt = 0
async def _create_remote():
nonlocal cnt, remote
create_remote(remote, TestType.FWD_RUNTIME_ERROR_NO_STREAM, True)
cnt += 1
cnt = 0
ifc = AsyncStreamServer(fake_reader_fwd(), FakeWriter(), None, _create_remote, remote)
ifc.fwd_add(b'test-forward_msg')
await ifc.server_loop()
assert cnt == 1
del ifc