Dieser Code lieferte bei mir einen Fehler weil pytest nicht gefunden werden kann. (Wohlgemerkt, ich arbeite mit LibreOffice und greife nur auf die Python-Umgebung zurück die LibreOffice mitbringt) plus mysqlk/Python).__blackjack__ hat geschrieben: ↑Sonntag 19. September 2021, 19:32 Mit `singledispatch()` + Testcode für die Umwandlungsfunktion:Code: Alles auswählen
#!/usr/bin/env python3 from contextlib import closing from decimal import Decimal from functools import singledispatch import pytest from mysql.connector import connect @singledispatch def convert_to_string(value): return str(value) @convert_to_string.register(type(None)) def _convert_none(_value): return "" @convert_to_string.register(float) @convert_to_string.register(Decimal) def _convert_number(value): return format(value, ".2f").replace(".", ",") def get_data_for_grid(host, port, user, password, database, sql): with closing( connect( host=host, port=port, user=user, password=password, database=database, ) ) as connection: with closing(connection.cursor()) as cursor: cursor.execute(sql) return [ tuple(map(convert_to_string, row)) for row in cursor.fetchall() ] @pytest.mark.parametrize( "value, expected", [ ("test", "test"), (None, ""), (42, "42"), (2.3, "2,30"), (Decimal("4.2"), "4,20"), ], ) def test_convert_to_string(value, expected): assert convert_to_string(value) == expected
Wenn ich pytest lösche funktioniert es:
Code: Alles auswählen
#!/usr/bin/env python3
from contextlib import closing
from decimal import Decimal
from functools import singledispatch
from mysql.connector import connect
@singledispatch
def convert_to_string(value):
return str(value)
@convert_to_string.register(type(None))
def _convert_none(_value):
return ""
@convert_to_string.register(float)
@convert_to_string.register(Decimal)
def _convert_number(value):
return format(value, ".2f").replace(".", ",")
def get_data_for_grid(host, port, user, password, database, sql):
with closing(
connect(
host=host,
port=port,
user=user,
password=password,
database=database,
)
) as connection:
with closing(connection.cursor()) as cursor:
cursor.execute(sql)
return [
tuple(map(convert_to_string, row)) for row in cursor.fetchall()
]
def test_convert_to_string(value, expected):
assert convert_to_string(value) == expected
Gruß
Stephan