from __future__ import annotations import json import uuid from dataclasses import dataclass from enum import Enum from typing import Optional, get_type_hints, Dict from megasniff import SchemaDeflatorGenerator from src.megasniff import SchemaInflatorGenerator def test_dicts(): @dataclass() class A: a: dict[str, int] b: Dict[int, int] c: dict[str, list[int]] d: dict[str, dict[str, int | str]] infl = SchemaInflatorGenerator(store_sources=True) defl = SchemaDeflatorGenerator(store_sources=True) infl_fn = infl.schema_to_inflator(A) defl_fn = defl.schema_to_deflator(A) a = infl_fn({ 'a': { 1: '42', 2: '123', 'asdf': 42 }, 'b': { 1: 1, '2': '2', '3': 3, 4: '4' }, 'c': { 'a': [1, 2, 3, '4'] }, 'd': { 'a': { 'a': 1, 'b': '1', 'c': 'asdf' } } }) assert a.a['1'] == 42 assert a.a['2'] == 123 assert a.a['asdf'] == 42 assert a.b[1] == 1 assert a.b[2] == 2 assert a.b[3] == 3 assert a.b[4] == 4 assert a.c['a'][0] == 1 assert a.c['a'][1] == 2 assert a.c['a'][2] == 3 assert a.c['a'][3] == 4 assert a.d['a']['a'] == 1 assert a.d['a']['b'] == 1 assert a.d['a']['c'] == 'asdf' def test_uuid_dicts(): @dataclass() class A: a: dict[uuid.UUID, uuid.UUID] infl = SchemaInflatorGenerator(store_sources=True) defl = SchemaDeflatorGenerator(store_sources=True) infl_fn = infl.schema_to_inflator(A) defl_fn = defl.schema_to_deflator(A) uuids = [uuid.uuid4() for _ in range(32)] a = infl_fn({ 'a': { str(uuids[0]): str(uuids[0]), str(uuids[1]): str(uuids[2]), str(uuids[3]): str(uuids[4]), } }) assert a.a[uuids[0]] == uuids[0] assert a.a[uuids[1]] == uuids[2] assert a.a[uuids[3]] == uuids[4] ad = json.loads(json.dumps(defl_fn(a), default=str)) assert ad['a'][str(uuids[0])] == str(uuids[0]) assert ad['a'][str(uuids[1])] == str(uuids[2]) assert ad['a'][str(uuids[3])] == str(uuids[4])