|
| 1 | +from copy import deepcopy |
| 2 | +from typing import Any, Dict |
| 3 | + |
| 4 | +from automapper import mapper |
| 5 | + |
| 6 | + |
| 7 | +class Candy: |
| 8 | + def __init__(self, name: str, brand: str): |
| 9 | + self.name = name |
| 10 | + self.brand = brand |
| 11 | + |
| 12 | + |
| 13 | +class Shop: |
| 14 | + def __init__(self, products: Dict[str, Any], annual_income: int): |
| 15 | + self.products: Dict[str, Any] = deepcopy(products) |
| 16 | + self.annual_income = annual_income |
| 17 | + |
| 18 | + |
| 19 | +class ShopPublicInfo: |
| 20 | + def __init__(self, products: Dict[str, Any]): |
| 21 | + self.products: Dict[str, Any] = deepcopy(products) |
| 22 | + |
| 23 | + |
| 24 | +def test_map__with_dict_field(): |
| 25 | + products = { |
| 26 | + "magazines": ["Forbes", "Time", "The New Yorker"], |
| 27 | + "candies": [ |
| 28 | + Candy("Reese's cups", "The Hershey Company"), |
| 29 | + Candy("Snickers", "Mars, Incorporated"), |
| 30 | + ], |
| 31 | + } |
| 32 | + shop = Shop(products=products, annual_income=10000000) |
| 33 | + |
| 34 | + public_info = mapper.to(ShopPublicInfo).map(shop) |
| 35 | + |
| 36 | + assert public_info.products["magazines"] == shop.products["magazines"] |
| 37 | + assert id(public_info.products["magazines"]) != id(shop.products["magazines"]) |
| 38 | + |
| 39 | + assert public_info.products["candies"] != shop.products["candies"] |
| 40 | + assert public_info.products["candies"][0] != shop.products["candies"][0] |
| 41 | + assert public_info.products["candies"][1] != shop.products["candies"][1] |
| 42 | + |
| 43 | + assert public_info.products["candies"][0].name == "Reese's cups" |
| 44 | + assert public_info.products["candies"][0].brand == "The Hershey Company" |
| 45 | + |
| 46 | + assert public_info.products["candies"][1].name == "Snickers" |
| 47 | + assert public_info.products["candies"][1].brand == "Mars, Incorporated" |
0 commit comments