def test_to_json(self): d = dict(a=[1, 2]) self.assertEqual(h.to_json(d), json.dumps(d, sort_keys=False, indent=None, separators=(",", ":"))) self.assertEqual(h.to_json(d, True), json.dumps(d, sort_keys=True, indent=2, separators=(", ", ": "))) with self.assertRaises(TypeError): d = dict(dt=datetime.now()) h.to_json(d) h.register_json_default(lambda o: hasattr(o, "isoformat"), lambda o: o.isoformat()) self.assertEqual(h.to_json(d), h.to_json(h.pick(d, ["dt"], transform=lambda n: n.isoformat())))
def to_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True): """Converts the class to a dictionary. :include_keys: if not None, only the attrs given will be included. :exclude_keys: if not None, all attrs except those listed will be included, with respect to use_default_excludes. :use_default_excludes: if True, then the class-level exclude_keys_serialize will be combined with exclude_keys if given, or used in place of exlcude_keys if not given. """ data = self.__dict__ if include_keys: return pick(data, include_keys, transform=self._other_to_dict) else: skeys = self.exclude_keys_serialize if use_default_excludes else None ekeys = exclude_keys return exclude( data, lambda k: (skeys is not None and k in skeys) or (ekeys is not None and k in ekeys), transform=self._other_to_dict)
def test_pick(self): d = dict(a=1, b=2, c=3, d=4) self.assertEqual(h.pick(d, ["a", "b"]), dict(a=1, b=2)) self.assertEqual(h.pick(d, lambda k: k <= "c"), dict(a=1, b=2, c=3)) self.assertEqual(h.pick(d, ["a", "b"], transform=lambda n: n * 2), dict(a=2, b=4))