From a9710df552d82b3d239c02c8589cec80362f6660 Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Fri, 18 Aug 2023 11:55:17 -0400 Subject: [PATCH 01/12] Upgrade to pydantic v2 --- poetry.lock | 189 +++++++++++++++++++++++++++++++++++++------------ pyproject.toml | 2 +- 2 files changed, 145 insertions(+), 46 deletions(-) diff --git a/poetry.lock b/poetry.lock index e639d21d..2e3d375b 100644 --- a/poetry.lock +++ b/poetry.lock @@ -11,6 +11,20 @@ files = [ {file = "alabaster-0.7.13.tar.gz", hash = "sha256:a27a4a084d5e690e16e01e03ad2b2e552c61a65469419b907243193de1a84ae2"}, ] +[[package]] +name = "annotated-types" +version = "0.5.0" +description = "Reusable constraint types to use with typing.Annotated" +optional = false +python-versions = ">=3.7" +files = [ + {file = "annotated_types-0.5.0-py3-none-any.whl", hash = "sha256:58da39888f92c276ad970249761ebea80ba544b77acddaa1a4d6cf78287d45fd"}, + {file = "annotated_types-0.5.0.tar.gz", hash = "sha256:47cdc3490d9ac1506ce92c7aaa76c579dc3509ff11e098fc867e5130ab7be802"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.9\""} + [[package]] name = "astroid" version = "2.11.7" @@ -993,55 +1007,140 @@ files = [ [[package]] name = "pydantic" -version = "1.10.5" -description = "Data validation and settings management using python type hints" +version = "2.2.0" +description = "Data validation using Python type hints" optional = false python-versions = ">=3.7" files = [ - {file = "pydantic-1.10.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:5920824fe1e21cbb3e38cf0f3dd24857c8959801d1031ce1fac1d50857a03bfb"}, - {file = "pydantic-1.10.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:3bb99cf9655b377db1a9e47fa4479e3330ea96f4123c6c8200e482704bf1eda2"}, - {file = "pydantic-1.10.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2185a3b3d98ab4506a3f6707569802d2d92c3a7ba3a9a35683a7709ea6c2aaa2"}, - {file = "pydantic-1.10.5-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f582cac9d11c227c652d3ce8ee223d94eb06f4228b52a8adaafa9fa62e73d5c9"}, - {file = "pydantic-1.10.5-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:c9e5b778b6842f135902e2d82624008c6a79710207e28e86966cd136c621bfee"}, - {file = "pydantic-1.10.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:72ef3783be8cbdef6bca034606a5de3862be6b72415dc5cb1fb8ddbac110049a"}, - {file = "pydantic-1.10.5-cp310-cp310-win_amd64.whl", hash = "sha256:45edea10b75d3da43cfda12f3792833a3fa70b6eee4db1ed6aed528cef17c74e"}, - {file = "pydantic-1.10.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:63200cd8af1af2c07964546b7bc8f217e8bda9d0a2ef0ee0c797b36353914984"}, - {file = "pydantic-1.10.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:305d0376c516b0dfa1dbefeae8c21042b57b496892d721905a6ec6b79494a66d"}, - {file = "pydantic-1.10.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1fd326aff5d6c36f05735c7c9b3d5b0e933b4ca52ad0b6e4b38038d82703d35b"}, - {file = "pydantic-1.10.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6bb0452d7b8516178c969d305d9630a3c9b8cf16fcf4713261c9ebd465af0d73"}, - {file = "pydantic-1.10.5-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:9a9d9155e2a9f38b2eb9374c88f02fd4d6851ae17b65ee786a87d032f87008f8"}, - {file = "pydantic-1.10.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:f836444b4c5ece128b23ec36a446c9ab7f9b0f7981d0d27e13a7c366ee163f8a"}, - {file = "pydantic-1.10.5-cp311-cp311-win_amd64.whl", hash = "sha256:8481dca324e1c7b715ce091a698b181054d22072e848b6fc7895cd86f79b4449"}, - {file = "pydantic-1.10.5-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:87f831e81ea0589cd18257f84386bf30154c5f4bed373b7b75e5cb0b5d53ea87"}, - {file = "pydantic-1.10.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7ce1612e98c6326f10888df951a26ec1a577d8df49ddcaea87773bfbe23ba5cc"}, - {file = "pydantic-1.10.5-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:58e41dd1e977531ac6073b11baac8c013f3cd8706a01d3dc74e86955be8b2c0c"}, - {file = "pydantic-1.10.5-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:6a4b0aab29061262065bbdede617ef99cc5914d1bf0ddc8bcd8e3d7928d85bd6"}, - {file = "pydantic-1.10.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:36e44a4de37b8aecffa81c081dbfe42c4d2bf9f6dff34d03dce157ec65eb0f15"}, - {file = "pydantic-1.10.5-cp37-cp37m-win_amd64.whl", hash = "sha256:261f357f0aecda005934e413dfd7aa4077004a174dafe414a8325e6098a8e419"}, - {file = "pydantic-1.10.5-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:b429f7c457aebb7fbe7cd69c418d1cd7c6fdc4d3c8697f45af78b8d5a7955760"}, - {file = "pydantic-1.10.5-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:663d2dd78596c5fa3eb996bc3f34b8c2a592648ad10008f98d1348be7ae212fb"}, - {file = "pydantic-1.10.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:51782fd81f09edcf265823c3bf43ff36d00db246eca39ee765ef58dc8421a642"}, - {file = "pydantic-1.10.5-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c428c0f64a86661fb4873495c4fac430ec7a7cef2b8c1c28f3d1a7277f9ea5ab"}, - {file = "pydantic-1.10.5-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:76c930ad0746c70f0368c4596020b736ab65b473c1f9b3872310a835d852eb19"}, - {file = "pydantic-1.10.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:3257bd714de9db2102b742570a56bf7978e90441193acac109b1f500290f5718"}, - {file = "pydantic-1.10.5-cp38-cp38-win_amd64.whl", hash = "sha256:f5bee6c523d13944a1fdc6f0525bc86dbbd94372f17b83fa6331aabacc8fd08e"}, - {file = "pydantic-1.10.5-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:532e97c35719f137ee5405bd3eeddc5c06eb91a032bc755a44e34a712420daf3"}, - {file = "pydantic-1.10.5-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:ca9075ab3de9e48b75fa8ccb897c34ccc1519177ad8841d99f7fd74cf43be5bf"}, - {file = "pydantic-1.10.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd46a0e6296346c477e59a954da57beaf9c538da37b9df482e50f836e4a7d4bb"}, - {file = "pydantic-1.10.5-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3353072625ea2a9a6c81ad01b91e5c07fa70deb06368c71307529abf70d23325"}, - {file = "pydantic-1.10.5-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:3f9d9b2be177c3cb6027cd67fbf323586417868c06c3c85d0d101703136e6b31"}, - {file = "pydantic-1.10.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b473d00ccd5c2061fd896ac127b7755baad233f8d996ea288af14ae09f8e0d1e"}, - {file = "pydantic-1.10.5-cp39-cp39-win_amd64.whl", hash = "sha256:5f3bc8f103b56a8c88021d481410874b1f13edf6e838da607dcb57ecff9b4594"}, - {file = "pydantic-1.10.5-py3-none-any.whl", hash = "sha256:7c5b94d598c90f2f46b3a983ffb46ab806a67099d118ae0da7ef21a2a4033b28"}, - {file = "pydantic-1.10.5.tar.gz", hash = "sha256:9e337ac83686645a46db0e825acceea8e02fca4062483f40e9ae178e8bd1103a"}, + {file = "pydantic-2.2.0-py3-none-any.whl", hash = "sha256:a479d511d1337ad091bd1ef90a7aaf707326968cff78a579108bc289b7f5ecdd"}, + {file = "pydantic-2.2.0.tar.gz", hash = "sha256:5f30f37a75bca15930e256da6a401f1cb953eb3bc578d454c0876f4e1459a7fa"}, ] [package.dependencies] -typing-extensions = ">=4.2.0" +annotated-types = ">=0.4.0" +pydantic-core = "2.6.0" +typing-extensions = ">=4.6.1" [package.extras] -dotenv = ["python-dotenv (>=0.10.4)"] -email = ["email-validator (>=1.0.3)"] +email = ["email-validator (>=2.0.0)"] + +[[package]] +name = "pydantic-core" +version = "2.6.0" +description = "" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pydantic_core-2.6.0-cp310-cp310-macosx_10_7_x86_64.whl", hash = "sha256:2ae2d2aa91f442427d5d607f5bc07a6601aea7e9812c158b11dfac4fca28b24a"}, + {file = "pydantic_core-2.6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cddecc97d923c3fae698820a788d6e7fda61538244dd2a0808d6263115fe5870"}, + {file = "pydantic_core-2.6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:482a20567991170d0b55aa4d73084858ab8d54804ffef8061f254c0f8b9cf668"}, + {file = "pydantic_core-2.6.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:775710d825f2b2ffe8a0bfd8d17cb8de6a9e562e78f50171c5afa9c508faa45c"}, + {file = "pydantic_core-2.6.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4fd9661a30a370faae9303dfde31d09d5b6f28113f8dace9a63f51d205703a8d"}, + {file = "pydantic_core-2.6.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4e9430096484696a1837f55728c804917ad694f8e965ad0317ff896db21c3a7b"}, + {file = "pydantic_core-2.6.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:253d769ce88f6d5b8ae8965f08c486114e30b5e5478f327348b77615a2a543cb"}, + {file = "pydantic_core-2.6.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:959aa63057738b426137d3de99d8da118f5c8ba19a238fdb5e5f0717297e9da4"}, + {file = "pydantic_core-2.6.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:c2c54ce857d0adb549fc735ffe84b9d1e77d1b460656fb2d3faa9050a85d8d37"}, + {file = "pydantic_core-2.6.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fe66139cfdd02ec4a0aad0cecf53bf9933c748097a97beb9042c03f236dd68b9"}, + {file = "pydantic_core-2.6.0-cp310-none-win32.whl", hash = "sha256:1781e985a9493f3fdca4c010fc6a009ab4fd40a61ab78e5cc9820eb8010c1c4c"}, + {file = "pydantic_core-2.6.0-cp310-none-win_amd64.whl", hash = "sha256:1d1b6c14c1116e797758bf1ff93ff18ab493279609aec6a60e6dee9de9065255"}, + {file = "pydantic_core-2.6.0-cp311-cp311-macosx_10_7_x86_64.whl", hash = "sha256:2f80f6790e87ec29ba28aab9a66b07ee789ec8fa6ea94aeac47e27f0019a061c"}, + {file = "pydantic_core-2.6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:04d6de74f91ff1a88975bc5e3c7103b676106af380ce8d9b56649116e0855dc9"}, + {file = "pydantic_core-2.6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c7507d40bd5d055dadba8ae9b6008356f380ce102942e0740228d97e8bd4152"}, + {file = "pydantic_core-2.6.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:82e34dc040001f50bec1a7a5c09fb6566635078ce91943cd10445a560cb3fe23"}, + {file = "pydantic_core-2.6.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:49848c89575d7768ea8762cc029f573a3d611452c41d05ae75bdcea8f77a9e5c"}, + {file = "pydantic_core-2.6.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:04b0e91c338536e3e3f77c3ed5354d14c46163f1c6b0706037b0b4be409eb943"}, + {file = "pydantic_core-2.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6265372636a78bc6b8ba92f7d2dafca353c549edc8082a602d00a28f71a9155a"}, + {file = "pydantic_core-2.6.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42caa59248750573efbce6a74f3e121f9def86dc2087772d51f0907c2ed6dc61"}, + {file = "pydantic_core-2.6.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:fd29541fb6f7647f535c0067cabb50ec014f13fa599ac4e34152abb5cb046988"}, + {file = "pydantic_core-2.6.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e4d46cd802c163914f07124735371812e9bed8a39acbebcee5bd06d43f454e1a"}, + {file = "pydantic_core-2.6.0-cp311-none-win32.whl", hash = "sha256:75850d211015ae46e28b3e05ee0cc8687316505cad385170aff70ad60f143011"}, + {file = "pydantic_core-2.6.0-cp311-none-win_amd64.whl", hash = "sha256:ff462b08951adaf55dbcc623d9b57823e888ffa4886f902dfc2c69d6ddc1ce4b"}, + {file = "pydantic_core-2.6.0-cp311-none-win_arm64.whl", hash = "sha256:658f4e8afe60d8400526d6db28d4e88e76027cf6111716fc090de87d14b5c311"}, + {file = "pydantic_core-2.6.0-cp312-cp312-macosx_10_7_x86_64.whl", hash = "sha256:a7d7b5af9ee32517280228629daca013ecc9a7834075af3d928287539ccd54ec"}, + {file = "pydantic_core-2.6.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7d03de66eda2c3a6eab2c2cf43eeece37e4cf811e891361b1fb8d8d3cd109f3a"}, + {file = "pydantic_core-2.6.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:693df3a922d94ba1c42ea732df7ab2f0492d6081b0170e86753a45e8822342a6"}, + {file = "pydantic_core-2.6.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bf6cb8b9c23dbb074f2d97b02af4d9d5401bd8015daad3e92fc35f88c5c07ba6"}, + {file = "pydantic_core-2.6.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a8aee2623180f736fc426925489e84bd244e45de4175dec76f10d4fda775721b"}, + {file = "pydantic_core-2.6.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:582bfd6e7d09f5883f607b7171fcd2010d226497d9dfc9703c8aa8d58431fa84"}, + {file = "pydantic_core-2.6.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3b52ce001eacd9906955576c71ee3fad9a442117b86dd84e5ea18e6ce287078d"}, + {file = "pydantic_core-2.6.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:179da6a5264d11cf2defba17c0003f6e27922d95f37b4818905115e2c9b8f7ed"}, + {file = "pydantic_core-2.6.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:4118471f4ba0f92fbe84bb6c0f645b423eaa5453e0dc4b6c0a6759da818352ba"}, + {file = "pydantic_core-2.6.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:afd9d1ef2805729898f580ccde0e76a3edd39cf16778c2139222047c8d25893b"}, + {file = "pydantic_core-2.6.0-cp312-none-win32.whl", hash = "sha256:c029084413a8eeb7d7b179d647d1e1a5cbfd5e5a817862a0ba8c5024fc9febf2"}, + {file = "pydantic_core-2.6.0-cp312-none-win_amd64.whl", hash = "sha256:86a74d426ca995deb3c847a2b382775b93a306fce13ae7b66cdc5fb8090a3ac5"}, + {file = "pydantic_core-2.6.0-cp312-none-win_arm64.whl", hash = "sha256:5a878f37a144c5641ead8b0771164dd22237ed4013b9899f250f0992447114e0"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-macosx_10_7_x86_64.whl", hash = "sha256:f9ebd8c45c8729bb23bb902a5cff573996fe5d86c3fc8c17cde3443345533889"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-macosx_11_0_arm64.whl", hash = "sha256:0faddd509ca1811d7e595cb48dc9b63d080a95f8434c5dc6660f268694f3c20f"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:859e11c4543bfd16b8033d50a2d7e4190fc5c6e182a6419b0d7c41109e3841b9"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:9f1a5fafbbadca467f426eb796bec61a908a670dfdcb984d300b9dd4d8b82433"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e3247b6d304226b12e240ff3fb0eb56b45520cd609d382fde6338a5556d44783"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:67f7658ac47a88ea3859389c4a67713edce77ade653812e0a574bc8f0cb0d951"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:310a47d94895628d3563859cb970cad1b3ee7a5f2282d9bd5512b3c5a09d4379"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2ee383e256a0e4b8bff1832fb31c530380a1421a714276ffd32609ce58a4c77a"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:148162967ede812466915bee671403dd2ded9822332df6c52866348129d4e58e"}, + {file = "pydantic_core-2.6.0-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:d0d672be281d2e297f95ca301710aed9ad7e10c56a691337c2f22375feb60f29"}, + {file = "pydantic_core-2.6.0-cp37-none-win32.whl", hash = "sha256:ed683ff1663fd596ce84cf4d132f7ce7b94f0b60686ee06ca2c8e151ccb918e7"}, + {file = "pydantic_core-2.6.0-cp37-none-win_amd64.whl", hash = "sha256:301e47c7cabc1c435773fcf0c7278181add0f211ddaf4c683bbfb62e09457c33"}, + {file = "pydantic_core-2.6.0-cp38-cp38-macosx_10_7_x86_64.whl", hash = "sha256:14ec281d30dd1a7fbf62e0afe4bc7bfac4b5edcf8da7affef1a79e874f3899cb"}, + {file = "pydantic_core-2.6.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:d13fc39e2d2957f32d8fa9d013bd7165d00c43890bdaea1e20a726873c50531b"}, + {file = "pydantic_core-2.6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:905048671ef08f2a504cdf7e26ffbe88efd74494ba821f2cdb1e4b1506236047"}, + {file = "pydantic_core-2.6.0-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:99b6004cd989bbcaf32e0794e6f42460b6f5ac047b2eb443a661cfdba29704e5"}, + {file = "pydantic_core-2.6.0-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4bac3e606b7f8fffd5e3a0d7c5d6ab110075c9dc16b9f8932cb077b6d985f8de"}, + {file = "pydantic_core-2.6.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:77865eb89c646673bedc7de4acd0a076dd6bada2f01d010675031cd855b052cf"}, + {file = "pydantic_core-2.6.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdbc528c7c6fef0e9aa1b4ba620d707c9735cfc92e6b666b83862ee55faa9605"}, + {file = "pydantic_core-2.6.0-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7291e0e36c1bc5c3b20d3f3cf77ba9ac7a26423ec50781d4f0435c45ddfe18c2"}, + {file = "pydantic_core-2.6.0-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:f693255ffec26a090c76adfb8f6286b76f5f3c9aa245f4bbe03aede102d815ef"}, + {file = "pydantic_core-2.6.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:9e8d12016b2fdbf885e3c7580fa8f6d2e90838586faee511656f2022ebf71a2d"}, + {file = "pydantic_core-2.6.0-cp38-none-win32.whl", hash = "sha256:59420b2fe9edfdc640e79aac09461400862d2e699ca59e5b96e5595cc7554736"}, + {file = "pydantic_core-2.6.0-cp38-none-win_amd64.whl", hash = "sha256:757372e9b5c81cec72a077237d5d026ccd5ad9bf4931bebee4c92177d52b4eba"}, + {file = "pydantic_core-2.6.0-cp39-cp39-macosx_10_7_x86_64.whl", hash = "sha256:6798756a5bee9991af64763ee2f3580505932a3f432af9a73bc9fdaca460261f"}, + {file = "pydantic_core-2.6.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3170a13c8cdb564f544ce03a7f26962828cce3456413b325fca49d32ef47ed1f"}, + {file = "pydantic_core-2.6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:51eb518682898df170d3d2ddd9c1f2a9496d79e5bd611b508d1a698e50b13fc6"}, + {file = "pydantic_core-2.6.0-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fe01f83bea0e4715c49449039b3c60a59408f0ceee61bb8c9a64699545e5b786"}, + {file = "pydantic_core-2.6.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:11854f12f09d2a108d130645edbca7aecf24756455599b0b19dacd47499ccadc"}, + {file = "pydantic_core-2.6.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:16c572a839eb584115185146a04b15986e19e3cbf00e3788f8296b16ec7b3fd5"}, + {file = "pydantic_core-2.6.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1e89b0a3f05416a7e67ec7257cddcf44263a10cea618cfc89855d46997c13742"}, + {file = "pydantic_core-2.6.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5464f3d27376739c7fa0af47096ac3696db1d8996d086167b3643f0443a1a976"}, + {file = "pydantic_core-2.6.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0ff7df99df6ae485e33afafc7adbfae2e133501b5debea4f0c20cd1f679fa321"}, + {file = "pydantic_core-2.6.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ac4148c3bede4269f286c7d094e98c717f1101025145e89baacbafc7c5f7f74b"}, + {file = "pydantic_core-2.6.0-cp39-none-win32.whl", hash = "sha256:36d6211421a4dd6d11ccb08e9ac92d143132402403ab791688cfc01973ad3de1"}, + {file = "pydantic_core-2.6.0-cp39-none-win_amd64.whl", hash = "sha256:83f5a3e201fe16684c12e654423a0c293733a57a1f9a9f284dbfb1b59f0e79bb"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-macosx_10_7_x86_64.whl", hash = "sha256:eeb7b4e1dd925db174a410680c846cb7ab7eb1923f556b44cf53cea774dc42fa"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:b0b4bcc57b12980b67e5eed09732102b19380f79dcba09444faa7a5c1826a432"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a5534040341ac6ad4d133023cd45da3654fff77795481c8e4d4508cafd248ba5"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:358f5d48aa850054ef1b148f4c3000b2ea216db4ab611039080bea294002349c"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f5ca934143857626de2423d65d487687c87931a62044ed5ee0deee55018569f4"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:5b3159c893a1d6dc93080b882d7c4fa8651abbb228a4d920066f3f48b7a200ac"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:5d9510004c4db5c683e349905c9700217da10b35d4447c7a1dfff1b6dd26192a"}, + {file = "pydantic_core-2.6.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:fc54501cdffbc8a7dbe300d6e4745c910d767a1aa273febca965f5fa561036b1"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-macosx_10_7_x86_64.whl", hash = "sha256:6cc456fc3c7156b23866ab953d3ff57010ab6a4b79ba686109ef93581467f6c3"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aedc8671291d6ff17b9fc587fed982c4feeffdd28351c577695a5f07945c4625"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:997fa26fd71c5d8676fa6dfefc06be1fac65fd578934d40e7546c047b7bdd019"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4f346c8fbd953f47711c388d9b856cad87cf72a714302bc04056f89d6ac55388"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:d61acd378c38bdcc1c109605831695eb27bd755d1fc5c765e40878601bd0c66b"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:3427ca73cffe42297bbb0ed712642d8484c42671b329441a2e51ce139f7e2f93"}, + {file = "pydantic_core-2.6.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:dabfdc82432499ceb33bb204fa0e5c0004a7dc1d85ba0250c5849ddfddd94819"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-macosx_10_7_x86_64.whl", hash = "sha256:10da8e685fe25be11089a666346461e01e23164688a224e33fee25d2a86da4e0"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-macosx_11_0_arm64.whl", hash = "sha256:0dbd7262932b213b34f6c1bdd33b53b6ffc07e3cee21d63486d68e433020f452"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a9d6f16d771334c49a173403805ef874aff9800ea7c44f94ebf3817ae9c5631e"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:646324855acd153632bb86cbbd222771df7859b43d2891ace57c5b8c818ba8a7"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f52e9edca854804b780bba5c82f7a1aafebb7a7c496879a45423cf991c361f9e"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:95e569d8f702851ab48e349c5eb2f8ea673657b7ed5f2ac335d540ebc8519385"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:b2ddc15cf29dc4b385c667064d7efb96431006dcf523527c3d749494b73e73a6"}, + {file = "pydantic_core-2.6.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:0b52468b09ccee65bc96572345ec73dc89b42528874b626f7757000a6544d285"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-macosx_10_7_x86_64.whl", hash = "sha256:c020c5047b25e64c39006fa11f15d93adf4ae85154387f8e10232871ba78e7b2"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:892e7de51b8191929bf1246a04c13674a4d4b8dced8a4f86def85a1b0cb1a1e4"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d179b77fff4387a46ed0b63eb87ad6be58bb2a3a3415e69a44e918e8abcbd8c6"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3b35585d14028c1afa41c1183906ce4128128d1114be9958b5ad0fb3721b50a4"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ffe8b2c8e30a87f6d7c1a78e23b8270a1acde9140cde425fa94688d302c8b2c9"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:6cc57fb772b48e5fd3691ca82d3756b6e64b885676d27d66bff551d951a18e5c"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:3d72ebaa6451490ae05d3da858120b395b3bf1bebc8a5238ef803ff0f4f16f38"}, + {file = "pydantic_core-2.6.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:535f47fe0d2db647fdb0376cbbadd34fd00b3a5f56f772b0b0ef26928e8afa22"}, + {file = "pydantic_core-2.6.0.tar.gz", hash = "sha256:e50513d8dd8ea67259d45986e314f545f219ebb2496eea52269e457cdc7419f4"}, +] + +[package.dependencies] +typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0" [[package]] name = "pydocstyle" @@ -1636,13 +1735,13 @@ files = [ [[package]] name = "typing-extensions" -version = "4.5.0" +version = "4.7.1" description = "Backported and Experimental Type Hints for Python 3.7+" optional = false python-versions = ">=3.7" files = [ - {file = "typing_extensions-4.5.0-py3-none-any.whl", hash = "sha256:fb33085c39dd998ac16d1431ebc293a8b3eedd00fd4a32de0ff79002c19511b4"}, - {file = "typing_extensions-4.5.0.tar.gz", hash = "sha256:5cb5f4a79139d699607b3ef622a1dedafa84e115ab0024e0d9c044a9479ca7cb"}, + {file = "typing_extensions-4.7.1-py3-none-any.whl", hash = "sha256:440d5dd3af93b060174bf433bccd69b0babc3b15b1a8dca43789fd7f61514b36"}, + {file = "typing_extensions-4.7.1.tar.gz", hash = "sha256:b75ddc264f0ba5615db7ba217daeb99701ad295353c45f9e95963337ceeeffb2"}, ] [[package]] @@ -1782,4 +1881,4 @@ redis = ["redis"] [metadata] lock-version = "2.0" python-versions = "^3.7" -content-hash = "2213a75a00f27293bb23f2a74792c2f8e46b97148e9197ddf620c9239d88b634" +content-hash = "d09a0c7c2f2b1d47cb25fce836511da80eba52ae9bf0706378edddf23a128f92" diff --git a/pyproject.toml b/pyproject.toml index 22e1066d..df62f792 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,7 @@ include = [ [tool.poetry.dependencies] python = "^3.7" -pydantic = "^1.7.4,!=1.8,!=1.8.1" +pydantic = "^2.0.0" structlog = ">= 20.1.0, < 23.0.0" packaging = ">= 21.3, < 24.0" colorama = {version = "^0.4.3", optional = true} From eac352bf98e26328499fc2edf545592e286d35c7 Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Fri, 18 Aug 2023 11:57:26 -0400 Subject: [PATCH 02/12] Run pydantic-bump --- diffsync/__init__.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/diffsync/__init__.py b/diffsync/__init__.py index 412270d8..b53e679f 100644 --- a/diffsync/__init__.py +++ b/diffsync/__init__.py @@ -18,7 +18,7 @@ from typing import Callable, ClassVar, Dict, List, Optional, Tuple, Type, Union, Any, Set from typing_extensions import Self -from pydantic import BaseModel, PrivateAttr +from pydantic import ConfigDict, BaseModel, PrivateAttr import structlog # type: ignore from diffsync.diff import Diff @@ -99,12 +99,7 @@ class DiffSyncModel(BaseModel): _status_message: str = PrivateAttr("") """Message, if any, associated with the create/update/delete status value.""" - - class Config: # pylint: disable=too-few-public-methods - """Pydantic class configuration.""" - - # Let us have a DiffSync as an instance variable even though DiffSync is not a Pydantic model itself. - arbitrary_types_allowed = True + model_config = ConfigDict(arbitrary_types_allowed=True) def __init_subclass__(cls) -> None: """Validate that the various class attribute declarations correspond to actual instance fields. From 394c78f4eeb1693ee8ce8a697b9708d7146e8561 Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Fri, 18 Aug 2023 13:22:48 -0400 Subject: [PATCH 03/12] Fix compatibility with pydantic v2 --- diffsync/__init__.py | 18 +++++++++--------- examples/01-multiple-data-sources/models.py | 6 +++--- examples/03-remote-system/models.py | 2 +- examples/04-get-update-instantiate/models.py | 6 +++--- examples/05-nautobot-peeringdb/models.py | 12 ++++++------ examples/06-ip-prefixes/models.py | 6 +++--- tests/unit/conftest.py | 4 ++-- tests/unit/test_diffsync_model.py | 8 ++++---- 8 files changed, 31 insertions(+), 31 deletions(-) diff --git a/diffsync/__init__.py b/diffsync/__init__.py index b53e679f..404cf8c2 100644 --- a/diffsync/__init__.py +++ b/diffsync/__init__.py @@ -101,24 +101,24 @@ class DiffSyncModel(BaseModel): """Message, if any, associated with the create/update/delete status value.""" model_config = ConfigDict(arbitrary_types_allowed=True) - def __init_subclass__(cls) -> None: + @classmethod + def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: """Validate that the various class attribute declarations correspond to actual instance fields. Called automatically on subclass declaration. """ - variables = cls.__fields__.keys() # Make sure that any field referenced by name actually exists on the model for attr in cls._identifiers: - if attr not in variables and not hasattr(cls, attr): + if attr not in cls.model_fields and not hasattr(cls, attr): raise AttributeError(f"_identifiers {cls._identifiers} references missing or un-annotated attr {attr}") for attr in cls._shortname: - if attr not in variables: + if attr not in cls.model_fields: raise AttributeError(f"_shortname {cls._shortname} references missing or un-annotated attr {attr}") for attr in cls._attributes: - if attr not in variables: + if attr not in cls.model_fields: raise AttributeError(f"_attributes {cls._attributes} references missing or un-annotated attr {attr}") for attr in cls._children.values(): - if attr not in variables: + if attr not in cls.model_fields: raise AttributeError(f"_children {cls._children} references missing or un-annotated attr {attr}") # Any given field can only be in one of (_identifiers, _attributes, _children) @@ -142,7 +142,7 @@ def dict(self, **kwargs: Any) -> Dict: """Convert this DiffSyncModel to a dict, excluding the diffsync field by default as it is not serializable.""" if "exclude" not in kwargs: kwargs["exclude"] = {"diffsync"} - return super().dict(**kwargs) + return super().model_dump(**kwargs) def json(self, **kwargs: Any) -> StrType: """Convert this DiffSyncModel to a JSON string, excluding the diffsync field by default as it is not serializable.""" @@ -150,7 +150,7 @@ def json(self, **kwargs: Any) -> StrType: kwargs["exclude"] = {"diffsync"} if "exclude_defaults" not in kwargs: kwargs["exclude_defaults"] = True - return super().json(**kwargs) + return super().model_dump_json(**kwargs) def str(self, include_children: bool = True, indent: int = 0) -> StrType: """Build a detailed string representation of this DiffSyncModel and optionally its children.""" @@ -850,4 +850,4 @@ def count(self, model: Union[StrType, "DiffSyncModel", Type["DiffSyncModel"], No # DiffSyncModel references DiffSync and DiffSync references DiffSyncModel. Break the typing loop: -DiffSyncModel.update_forward_refs() +DiffSyncModel.model_rebuild() diff --git a/examples/01-multiple-data-sources/models.py b/examples/01-multiple-data-sources/models.py index 29085155..625415a7 100644 --- a/examples/01-multiple-data-sources/models.py +++ b/examples/01-multiple-data-sources/models.py @@ -40,8 +40,8 @@ class Device(DiffSyncModel): _children = {"interface": "interfaces"} name: str - site_name: Optional[str] # note that this attribute is NOT included in _attributes - role: Optional[str] # note that this attribute is NOT included in _attributes + site_name: Optional[str] = None # note that this attribute is NOT included in _attributes + role: Optional[str] = None # note that this attribute is NOT included in _attributes interfaces: List = [] @@ -56,4 +56,4 @@ class Interface(DiffSyncModel): name: str device_name: str - description: Optional[str] + description: Optional[str] = None diff --git a/examples/03-remote-system/models.py b/examples/03-remote-system/models.py index 6a1f85c1..00fff0ec 100644 --- a/examples/03-remote-system/models.py +++ b/examples/03-remote-system/models.py @@ -32,4 +32,4 @@ class Country(DiffSyncModel): slug: str name: str region: str - population: Optional[int] + population: Optional[int] = 0 diff --git a/examples/04-get-update-instantiate/models.py b/examples/04-get-update-instantiate/models.py index 9a105992..b0f785d9 100644 --- a/examples/04-get-update-instantiate/models.py +++ b/examples/04-get-update-instantiate/models.py @@ -38,8 +38,8 @@ class Device(DiffSyncModel): _children = {"interface": "interfaces", "site": "sites"} name: str - site_name: Optional[str] # note that this attribute is NOT included in _attributes - role: Optional[str] # note that this attribute is NOT included in _attributes + site_name: Optional[str] = None # note that this attribute is NOT included in _attributes + role: Optional[str] = None # note that this attribute is NOT included in _attributes interfaces: List = [] sites: List = [] @@ -55,4 +55,4 @@ class Interface(DiffSyncModel): name: str device_name: str - description: Optional[str] + description: Optional[str] = None diff --git a/examples/05-nautobot-peeringdb/models.py b/examples/05-nautobot-peeringdb/models.py index 2fecb044..46c58071 100644 --- a/examples/05-nautobot-peeringdb/models.py +++ b/examples/05-nautobot-peeringdb/models.py @@ -21,8 +21,8 @@ class RegionModel(DiffSyncModel): # Data type declarations for all identifiers and attributes name: str slug: str - description: Optional[str] - parent_name: Optional[str] # may be None + description: Optional[str] = None + parent_name: Optional[str] = None sites: List = [] # Not in _attributes or _identifiers, hence not included in diff calculations @@ -49,10 +49,10 @@ class SiteModel(DiffSyncModel): name: str slug: str status_slug: str - region_name: Optional[str] # may be None - description: Optional[str] - latitude: Optional[float] - longitude: Optional[float] + region_name: Optional[str] = None + description: Optional[str] = None + latitude: Optional[float] = None + longitude: Optional[float] = None # Not in _attributes or _identifiers, hence not included in diff calculations pk: Optional[Union[UUID, int]] diff --git a/examples/06-ip-prefixes/models.py b/examples/06-ip-prefixes/models.py index 2fc4abdd..cede29df 100644 --- a/examples/06-ip-prefixes/models.py +++ b/examples/06-ip-prefixes/models.py @@ -11,6 +11,6 @@ class Prefix(DiffSyncModel): _attributes = ("vrf", "vlan_id", "tenant") prefix: str - vrf: Optional[str] - vlan_id: Optional[int] - tenant: Optional[str] + vrf: Optional[str] = None + vlan_id: Optional[int] = None + tenant: Optional[str] = None diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index e0dd85c7..365ce4a5 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -115,7 +115,7 @@ class Device(DiffSyncModel): _children = {"interface": "interfaces"} name: str - site_name: Optional[str] # note this is not included in _attributes + site_name: Optional[str] = None # note this is not included in _attributes role: str interfaces: List = [] @@ -143,7 +143,7 @@ class Interface(DiffSyncModel): name: str interface_type: str = "ethernet" - description: Optional[str] + description: Optional[str] = None @pytest.fixture diff --git a/tests/unit/test_diffsync_model.py b/tests/unit/test_diffsync_model.py index 90ecbc85..e7d6a6b4 100644 --- a/tests/unit/test_diffsync_model.py +++ b/tests/unit/test_diffsync_model.py @@ -107,7 +107,7 @@ def test_diffsync_model_dict_with_data(make_interface): def test_diffsync_model_json_with_data(make_interface): intf = make_interface() # json() omits default values for brevity - assert intf.json() == '{"device_name": "device1", "name": "eth0"}' + assert intf.json() == '{"device_name":"device1","name":"eth0"}' def test_diffsync_model_str_with_data(make_interface): @@ -182,7 +182,7 @@ def test_diffsync_model_json_with_children(generic_diffsync, make_site, make_dev generic_diffsync.add(site1) generic_diffsync.add(device1) - assert site1.json() == '{"name": "site1", "devices": ["device1"]}' + assert site1.json() == '{"name":"site1","devices":["device1"]}' def test_diffsync_model_str_with_children(generic_diffsync, make_site, make_device, make_interface): @@ -294,7 +294,7 @@ class BadAttributes(DiffSyncModel): name: str # Note that short_name doesn't have a type annotation - making sure this works too - short_name = "short_name" + short_name: str = "short_name" assert "_attributes" in str(excinfo.value) assert "my_attr" in str(excinfo.value) @@ -310,7 +310,7 @@ class BadChildren(DiffSyncModel): _children = {"device": "devices"} name: str - short_name = "short_name" + short_name: str = "short_name" my_attr: int = 0 assert "_children" in str(excinfo.value) From fe4717eccecceb41276b826210598f217e7614d0 Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Fri, 18 Aug 2023 13:49:45 -0400 Subject: [PATCH 04/12] Bootstrap 2.0 migration docs for pydantic 2.0 change --- CHANGELOG.md | 40 ++++++++++++-------- docs/source/getting_started/index.rst | 6 +-- docs/source/index.rst | 1 + docs/source/upgrading/01-upgrading-to-2.0.md | 31 +++++++++++++++ docs/source/upgrading/index.rst | 5 +++ 5 files changed, 65 insertions(+), 18 deletions(-) create mode 100644 docs/source/upgrading/01-upgrading-to-2.0.md create mode 100644 docs/source/upgrading/index.rst diff --git a/CHANGELOG.md b/CHANGELOG.md index 84ad77e7..7d632bff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,16 @@ # Changelog -## v1.8.0 - 2023-04-18 +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [Unreleased] + +### Changed + +- **BREAKING CHANGE** #236/240 - Upgrade to Pydantic v2. + +## [1.8.0] - 2023-04-18 ### Added @@ -13,7 +23,7 @@ - #77/#188 - `sync_from()` and `sync_to()` now return the `Diff` that was applied. - #211 - Loosened `packaging` and `structlog` library dependency constraints for broader compatibility. -## v1.7.0 - 2022-11-03 +## [1.7.0] - 2022-11-03 ### Changed @@ -31,15 +41,15 @@ ### Fixed -- #149 Limit redundant CI concurrency +- #149 - Limit redundant CI concurrency -## v1.6.0 - 2022-07-09 +## [1.6.0] - 2022-07-09 ### Changed - #120 - Dropped support for Python 3.6, new minimum is Python 3.7 -## v1.5.1 - 2022-06-30 +## [1.5.1] - 2022-06-30 ### Added @@ -54,13 +64,13 @@ - #115 - Fixed ReadTheDocs rendering pipeline - #118 - Fixed a regression in `DiffSync.get(modelname, identifiers)` introduced in 1.5.0 -## v1.5.0 - 2022-06-07 +## [1.5.0] - 2022-06-07 ### Added - #106 - Add a new, optional, backend store based in Redis -## v1.4.3 - 2022-03-03 +## [1.4.3] - 2022-03-03 ### Fixed @@ -70,9 +80,9 @@ ### Changed -- #103 Update development dependencies +- #103 - Update development dependencies -## v1.4.2 - 2022-02-28 +## [1.4.2] - 2022-02-28 **WARNING** - #90 inadvertently introduced a breaking API change in DiffSync 1.4.0 through 1.4.2 (#101); this change was reverted in #102 for DiffSync 1.4.3 and later. We recommend not using this release, and moving to 1.4.3 instead. @@ -80,7 +90,7 @@ - #100 - Added explicit dependency on `packaging`. -## v1.4.1 - 2022-01-26 +## [1.4.1] - 2022-01-26 **WARNING** - #90 inadvertently introduced a breaking API change in DiffSync 1.4.0 through 1.4.2 (#101); this change was reverted in #102 for DiffSync 1.4.3 and later. We recommend not using this release, and moving to 1.4.3 instead. @@ -88,7 +98,7 @@ - #95 - Removed optional dependencies on `sphinx`, `m2r2`, `sphinx-rtd-theme`, `toml`. -## v1.4.0 - 2022-01-24 +## [1.4.0] - 2022-01-24 **WARNING** - #90 inadvertently introduced a breaking API change in DiffSync 1.4.0 through 1.4.2 (#101); this change was reverted in #102 for DiffSync 1.4.3 and later. We recommend not using this release, and moving to 1.4.3 instead. @@ -117,19 +127,19 @@ - #51 - Update minimum Pydantic version due to security advisory GHSA-5jqp-qgf6-3pvh - #63 - Fix type in Readme -## v1.3.0 - 2021-04-07 +## [1.3.0] - 2021-04-07 ### Added - #48 - added optional `callback` argument to `diff_from`/`diff_to`/`sync_from`/`sync_to` for use with progress reporting. -## v1.2.0 - 2020-12-08 +## [1.2.0] - 2020-12-08 ### Added - #45 - minimum Python version lowered from 3.7 to 3.6, also now tested against Python 3.9. -## v1.1.0 - 2020-12-01 +## [1.1.0] - 2020-12-01 ### Added @@ -147,6 +157,6 @@ - #44 - On CRUD failure, do not generate an extraneous "success" log message in addition to the "failed" message -## v1.0.0 - 2020-10-23 +## [1.0.0] - 2020-10-23 Initial release diff --git a/docs/source/getting_started/index.rst b/docs/source/getting_started/index.rst index 2b0e096e..9f461ee2 100644 --- a/docs/source/getting_started/index.rst +++ b/docs/source/getting_started/index.rst @@ -1,5 +1,5 @@ -############### -Getting Started -############### +######### +Upgrading +######### .. mdinclude:: 01-getting-started.md diff --git a/docs/source/index.rst b/docs/source/index.rst index 3b1a744b..2c851f5e 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -9,6 +9,7 @@ Welcome to DiffSync's documentation! getting_started/index core_engine/index examples/index + upgrading/index api/diffsync license/index diff --git a/docs/source/upgrading/01-upgrading-to-2.0.md b/docs/source/upgrading/01-upgrading-to-2.0.md new file mode 100644 index 00000000..10a7b089 --- /dev/null +++ b/docs/source/upgrading/01-upgrading-to-2.0.md @@ -0,0 +1,31 @@ +# Upgrading to 2.0 + +With diffsync 2.0, there a couple of breaking changes. What they are and how to deal with them is described in this document. + +## Upgrade to Pydantic's major version 2 + +A [migration guide](https://docs.pydantic.dev/latest/migration/) is available in the Pydantic documentation. Here are the key things that may apply to your usage of diffsync: + +- Any fields that are of type `Optional` now need to provide an explicit `None` default (you can use [bump-pydantic](https://github.com/pydantic/bump-pydantic) to deal with this automatically for the most part) + +```python +from typing import Optional + +from diffsync import DiffSyncModel + +# Before +class Person(DiffSyncModel): + _identifiers = ("name",) + _attributes = ("age",) + + name: str + age: Optional[int] + +# After +class BetterPerson(DiffSyncModel) + _identifiers = ("name",) + _attributes = ("age",) + + name: str + age: Optional[int] = None +``` \ No newline at end of file diff --git a/docs/source/upgrading/index.rst b/docs/source/upgrading/index.rst new file mode 100644 index 00000000..30b6e1e4 --- /dev/null +++ b/docs/source/upgrading/index.rst @@ -0,0 +1,5 @@ +######### +Upgrading +######### + +.. mdinclude:: 01-upgrading-to-2.0.md From 0ad1e2bfd93747b99b70e5afabb3566279bdb9ff Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Thu, 24 Aug 2023 16:29:03 -0600 Subject: [PATCH 05/12] renames diffsync.DiffSync to diffsync.Adapter --- README.md | 2 +- diffsync/__init__.py | 21 ++++++++------ diffsync/helpers.py | 10 +++---- diffsync/store/__init__.py | 4 +-- docs/source/core_engine/01-flags.md | 4 +-- docs/source/core_engine/03-store.md | 28 +++++++++++-------- .../getting_started/01-getting-started.md | 16 +++++------ .../01-multiple-data-sources/backend_a.py | 4 +-- .../01-multiple-data-sources/backend_b.py | 4 +-- .../01-multiple-data-sources/backend_c.py | 4 +-- examples/02-callback-function/main.py | 10 +++---- examples/03-remote-system/local_adapter.py | 4 +-- examples/03-remote-system/nautobot_adapter.py | 4 +-- examples/03-remote-system/nautobot_models.py | 4 +-- examples/04-get-update-instantiate/README.md | 6 ++-- .../04-get-update-instantiate/backends.py | 6 ++-- .../05-nautobot-peeringdb/adapter_nautobot.py | 4 +-- .../adapter_peeringdb.py | 4 +-- examples/06-ip-prefixes/adapter_ipam_a.py | 4 +-- examples/06-ip-prefixes/adapter_ipam_b.py | 4 +-- tests/unit/conftest.py | 10 +++---- tests/unit/test_diffsync.py | 8 +++--- tests/unit/test_diffsync_model_flags.py | 4 +-- 23 files changed, 88 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 96484f44..61eec471 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ DiffSync is at its most useful when you have multiple sources or sets of data to # Overview of DiffSync -DiffSync acts as an intermediate translation layer between all of the data sets you are diffing and/or syncing. In practical terms, this means that to use DiffSync, you will define a set of data models as well as the “adapters” needed to translate between each base data source and the data model. In Python terms, the adapters will be subclasses of the `DiffSync` class, and each data model class will be a subclass of the `DiffSyncModel` class. +DiffSync acts as an intermediate translation layer between all of the data sets you are diffing and/or syncing. In practical terms, this means that to use DiffSync, you will define a set of data models as well as the “adapters” needed to translate between each base data source and the data model. In Python terms, the adapters will be subclasses of the `Adapter` class, and each data model class will be a subclass of the `DiffSyncModel` class. ![Diffsync Components](https://raw.githubusercontent.com/networktocode/diffsync/develop/docs/images/diffsync_components.png "Diffsync Components") diff --git a/diffsync/__init__.py b/diffsync/__init__.py index 412270d8..916ca181 100644 --- a/diffsync/__init__.py +++ b/diffsync/__init__.py @@ -91,7 +91,7 @@ class DiffSyncModel(BaseModel): Can be set as a class attribute or an instance attribute as needed. """ - diffsync: Optional["DiffSync"] = None + diffsync: Optional["Adapter"] = None """Optional: the DiffSync instance that owns this model instance.""" _status: DiffSyncStatus = PrivateAttr(DiffSyncStatus.SUCCESS) @@ -183,7 +183,7 @@ def set_status(self, status: DiffSyncStatus, message: StrType = "") -> None: self._status_message = message @classmethod - def create_base(cls, diffsync: "DiffSync", ids: Dict, attrs: Dict) -> Optional[Self]: + def create_base(cls, diffsync: "Adapter", ids: Dict, attrs: Dict) -> Optional[Self]: """Instantiate this class, along with any platform-specific data creation. This method is not meant to be subclassed, users should redefine create() instead. @@ -201,7 +201,7 @@ def create_base(cls, diffsync: "DiffSync", ids: Dict, attrs: Dict) -> Optional[S return model @classmethod - def create(cls, diffsync: "DiffSync", ids: Dict, attrs: Dict) -> Optional[Self]: + def create(cls, diffsync: "Adapter", ids: Dict, attrs: Dict) -> Optional[Self]: """Instantiate this class, along with any platform-specific data creation. Subclasses must call `super().create()` or `self.create_base()`; they may wish to then override the default status information @@ -402,7 +402,7 @@ def remove_child(self, child: "DiffSyncModel") -> None: childs.remove(child.get_unique_id()) -class DiffSync: # pylint: disable=too-many-public-methods +class Adapter: # pylint: disable=too-many-public-methods """Class for storing a group of DiffSyncModel instances and diffing/synchronizing to another DiffSync instance.""" # In any subclass, you would add mapping of names to specific model classes here: @@ -535,7 +535,7 @@ def load_from_dict(self, data: Dict) -> None: def sync_from( # pylint: disable=too-many-arguments self, - source: "DiffSync", + source: "Adapter", diff_class: Type[Diff] = Diff, flags: DiffSyncFlags = DiffSyncFlags.NONE, callback: Optional[Callable[[StrType, int, int], None]] = None, @@ -573,7 +573,7 @@ def sync_from( # pylint: disable=too-many-arguments def sync_to( # pylint: disable=too-many-arguments self, - target: "DiffSync", + target: "Adapter", diff_class: Type[Diff] = Diff, flags: DiffSyncFlags = DiffSyncFlags.NONE, callback: Optional[Callable[[StrType, int, int], None]] = None, @@ -597,7 +597,7 @@ def sync_to( # pylint: disable=too-many-arguments def sync_complete( self, - source: "DiffSync", + source: "Adapter", diff: Diff, flags: DiffSyncFlags = DiffSyncFlags.NONE, logger: Optional[structlog.BoundLogger] = None, @@ -623,7 +623,7 @@ def sync_complete( def diff_from( self, - source: "DiffSync", + source: "Adapter", diff_class: Type[Diff] = Diff, flags: DiffSyncFlags = DiffSyncFlags.NONE, callback: Optional[Callable[[StrType, int, int], None]] = None, @@ -644,7 +644,7 @@ def diff_from( def diff_to( self, - target: "DiffSync", + target: "Adapter", diff_class: Type[Diff] = Diff, flags: DiffSyncFlags = DiffSyncFlags.NONE, callback: Optional[Callable[[StrType, int, int], None]] = None, @@ -854,5 +854,8 @@ def count(self, model: Union[StrType, "DiffSyncModel", Type["DiffSyncModel"], No return self.store.count(model=model) +# For backwards-compatibility, keep around the old name +DiffSync = Adapter + # DiffSyncModel references DiffSync and DiffSync references DiffSyncModel. Break the typing loop: DiffSyncModel.update_forward_refs() diff --git a/diffsync/helpers.py b/diffsync/helpers.py index 96882bae..b51f142a 100644 --- a/diffsync/helpers.py +++ b/diffsync/helpers.py @@ -26,7 +26,7 @@ if TYPE_CHECKING: # pragma: no cover # For type annotation purposes, we have a circular import loop between __init__.py and this file. - from . import DiffSync, DiffSyncModel # pylint: disable=cyclic-import + from . import Adapter, DiffSyncModel # pylint: disable=cyclic-import class DiffSyncDiffer: # pylint: disable=too-many-instance-attributes @@ -37,8 +37,8 @@ class DiffSyncDiffer: # pylint: disable=too-many-instance-attributes def __init__( # pylint: disable=too-many-arguments self, - src_diffsync: "DiffSync", - dst_diffsync: "DiffSync", + src_diffsync: "Adapter", + dst_diffsync: "Adapter", flags: DiffSyncFlags, diff_class: Type[Diff] = Diff, callback: Optional[Callable[[str, int, int], None]] = None, @@ -288,8 +288,8 @@ class DiffSyncSyncer: # pylint: disable=too-many-instance-attributes def __init__( # pylint: disable=too-many-arguments self, diff: Diff, - src_diffsync: "DiffSync", - dst_diffsync: "DiffSync", + src_diffsync: "Adapter", + dst_diffsync: "Adapter", flags: DiffSyncFlags, callback: Optional[Callable[[str, int, int], None]] = None, ): diff --git a/diffsync/store/__init__.py b/diffsync/store/__init__.py index 77f1a9f4..3dacf330 100644 --- a/diffsync/store/__init__.py +++ b/diffsync/store/__init__.py @@ -6,7 +6,7 @@ if TYPE_CHECKING: from diffsync import DiffSyncModel - from diffsync import DiffSync + from diffsync import Adapter class BaseStore: @@ -15,7 +15,7 @@ class BaseStore: def __init__( self, # pylint: disable=unused-argument *args: Any, # pylint: disable=unused-argument - diffsync: Optional["DiffSync"] = None, + diffsync: Optional["Adapter"] = None, name: str = "", **kwargs: Any, # pylint: disable=unused-argument ) -> None: diff --git a/docs/source/core_engine/01-flags.md b/docs/source/core_engine/01-flags.md index 542703ee..12f4ca9b 100644 --- a/docs/source/core_engine/01-flags.md +++ b/docs/source/core_engine/01-flags.md @@ -34,12 +34,12 @@ diff = nautobot.diff_from(local, flags=flags) Model flags are stored in the attribute `model_flags` of each model and are usually set when the data is being loaded into the adapter. ```python -from diffsync import DiffSync +from diffsync import Adapter from diffsync.enum import DiffSyncModelFlags from model import MyDeviceModel -class MyAdapter(DiffSync): +class MyAdapter(Adapter): device = MyDeviceModel def load(self, data): diff --git a/docs/source/core_engine/03-store.md b/docs/source/core_engine/03-store.md index 7a4a7bd1..a3cb6905 100644 --- a/docs/source/core_engine/03-store.md +++ b/docs/source/core_engine/03-store.md @@ -2,32 +2,36 @@ By default, `Diffsync` supports a local memory storage. All the loaded models from the adapters will be stored in memory, and become available for the diff calculation and sync process. This default behavior works well when executing all the steps in the same process, having access to the same memory space. However, if you want to scale out the execution of the tasks, running it in different processes or in totally different workers, a more distributed memory support is necessary. -The `store` is a class attribute in the `DiffSync` class, but all the store operations in that class are abstracted in the following methods: `get_all_model_names`, `get`, `get_by_uids`, `add`, `update`, `remove`, `get_or_instantiate`, `update_or_instantiate` and `count`. +The `store` is a class attribute in the `Adapter` class, but all the store operations in that class are abstracted in the following methods: `get_all_model_names`, `get`, `get_by_uids`, `add`, `update`, `remove`, `get_or_instantiate`, `update_or_instantiate` and `count`. ## Use the `LocalStore` Backend When you initialize the `Diffsync` Adapter class, there is an optional keyed-argument, `internal_storage_engine`, defaulting to the `LocalStore` class. ```python ->>> from diffsync import DiffSync ->>> adapter = DiffSync() ->>> type(adapter.store) - +>> > from diffsync import Adapter +>> > adapter = Adapter() +>> > type(adapter.store) +< + +class 'diffsync.store.local.LocalStore'> ``` ## Use the `RedisStore` Backend To get it, you have to install diffsync package with the "redis" extra option: `pip install diffsync[redis]` -The `RedisStore` backend, as the name suggests, connects to an external Redis service, to store data loaded by the `DiffSync` tasks. The biggest change is that it requires to initialize the Redis store class, before using it in the `DiffSync` adapter class. +The `RedisStore` backend, as the name suggests, connects to an external Redis service, to store data loaded by the `Adapter` tasks. The biggest change is that it requires to initialize the Redis store class, before using it in the `Adapter` adapter class. ```python ->>> from diffsync import DiffSync ->>> from diffsync.store.redis import RedisStore ->>> store = RedisStore(host="redis host") ->>> adapter = DiffSync(internal_storage_engine=store) ->>> type(adapter.store) - +>> > from diffsync import Adapter +>> > from diffsync.store.redis import RedisStore +>> > store = RedisStore(host="redis host") +>> > adapter = Adapter(internal_storage_engine=store) +>> > type(adapter.store) +< + +class 'diffsync.store.local.RedisStore'> ``` Notice that the `RedisStore` will validate, when initialized, that there is a reachability to the Redis host, and if not, will raise an exception: diff --git a/docs/source/getting_started/01-getting-started.md b/docs/source/getting_started/01-getting-started.md index 6f0cc0f8..9b99cc35 100644 --- a/docs/source/getting_started/01-getting-started.md +++ b/docs/source/getting_started/01-getting-started.md @@ -1,5 +1,5 @@ To be able to properly compare different datasets, DiffSync relies on a shared data model that both systems must use. -Specifically, each system or dataset must provide a `DiffSync` "adapter" subclass, which in turn represents its dataset as instances of one or more `DiffSyncModel` data model classes. +Specifically, each system or dataset must provide a `Adapter` "adapter" subclass, which in turn represents its dataset as instances of one or more `DiffSyncModel` data model classes. When comparing two systems, DiffSync detects the intersection between the two systems (which data models they have in common, and which attributes are shared between each pair of data models) and uses this intersection to compare and/or synchronize the data. @@ -41,24 +41,24 @@ Currently the relationships between models are very loose by design. Instead of # Define your system adapter with DiffSync -A `DiffSync` "adapter" subclass must reference each model available at the top of the object by its modelname and must have a `top_level` attribute defined to indicate how the diff and the synchronization should be done. In the example below, `"site"` is the only top level object so the synchronization engine will only check all known `Site` instances and all children of each Site. In this case, as shown in the code above, `Device`s are children of `Site`s, so this is exactly the intended logic. +A `Adapter` "adapter" subclass must reference each model available at the top of the object by its modelname and must have a `top_level` attribute defined to indicate how the diff and the synchronization should be done. In the example below, `"site"` is the only top level object so the synchronization engine will only check all known `Site` instances and all children of each Site. In this case, as shown in the code above, `Device`s are children of `Site`s, so this is exactly the intended logic. ```python -from diffsync import DiffSync +from diffsync import Adapter -class BackendA(DiffSync): +class BackendA(Adapter): site = Site device = Device top_level = ["site"] ``` -It's up to the implementer to populate the `DiffSync`'s internal cache with the appropriate data. In the example below we are using the `load()` method to populate the cache but it's not mandatory, it could be done differently. +It's up to the implementer to populate the `Adapter`'s internal cache with the appropriate data. In the example below we are using the `load()` method to populate the cache but it's not mandatory, it could be done differently. ## Model Processing Ordering Logic -The models will be processed in a specfic order as defined by `top_level` atttribute on the `DiffSync` object and then the `_children` attribute on the `DiffSyncModel`. The processing algorithm is technically a "Preorder Tree Traversal", which means that "a parent node is processed before any of its child nodes is done." This can be described as: +The models will be processed in a specfic order as defined by `top_level` atttribute on the `Adapter` object and then the `_children` attribute on the `DiffSyncModel`. The processing algorithm is technically a "Preorder Tree Traversal", which means that "a parent node is processed before any of its child nodes is done." This can be described as: - Start with the first element of the first model in `top_level` and process it. - If that model has `_children` set on it, for each child of each child model, in order: @@ -145,7 +145,7 @@ NetworkImporterAdapter >>> ``` -# Store data in a `DiffSync` object +# Store data in a `Adapter` object To add a site to the local cache/store, you need to pass a valid `DiffSyncModel` object to the `add()` function. @@ -174,7 +174,7 @@ convenient to manage individual records (as in a database) or modify the entire ## Manage individual records To update individual records in a remote system, you need to extend your `DiffSyncModel` class(es) to define your own `create`, `update` and/or `delete` methods for each model. -A `DiffSyncModel` instance stores a reference to its parent `DiffSync` adapter instance in case you need to use it to look up other model instances from the `DiffSync`'s cache. +A `DiffSyncModel` instance stores a reference to its parent `Adapter` adapter instance in case you need to use it to look up other model instances from the `Adapter`'s cache. ```python class Device(DiffSyncModel): diff --git a/examples/01-multiple-data-sources/backend_a.py b/examples/01-multiple-data-sources/backend_a.py index a92435bf..6edd7997 100644 --- a/examples/01-multiple-data-sources/backend_a.py +++ b/examples/01-multiple-data-sources/backend_a.py @@ -16,7 +16,7 @@ """ # pylint: disable=wrong-import-order -from diffsync import DiffSync +from diffsync import Adapter from models import Site, Device, Interface # pylint: disable=no-name-in-module DATA = { @@ -31,7 +31,7 @@ } -class BackendA(DiffSync): +class BackendA(Adapter): """Example of a DiffSync adapter implementation.""" site = Site diff --git a/examples/01-multiple-data-sources/backend_b.py b/examples/01-multiple-data-sources/backend_b.py index 6fc7c203..98db921b 100644 --- a/examples/01-multiple-data-sources/backend_b.py +++ b/examples/01-multiple-data-sources/backend_b.py @@ -16,7 +16,7 @@ """ # pylint: disable=wrong-import-order -from diffsync import DiffSync +from diffsync import Adapter from models import Site, Device, Interface # pylint: disable=no-name-in-module DATA = { @@ -35,7 +35,7 @@ } -class BackendB(DiffSync): +class BackendB(Adapter): """Example of a DiffSync adapter implementation.""" site = Site diff --git a/examples/01-multiple-data-sources/backend_c.py b/examples/01-multiple-data-sources/backend_c.py index a964e963..88ed91a7 100644 --- a/examples/01-multiple-data-sources/backend_c.py +++ b/examples/01-multiple-data-sources/backend_c.py @@ -16,7 +16,7 @@ """ # pylint: disable=wrong-import-order -from diffsync import DiffSync +from diffsync import Adapter from models import Site, Device, Interface # pylint: disable=no-name-in-module DATA = { @@ -31,7 +31,7 @@ } -class BackendC(DiffSync): +class BackendC(Adapter): """Example of a DiffSync adapter implementation.""" site = Site diff --git a/examples/02-callback-function/main.py b/examples/02-callback-function/main.py index 514f2cb7..84884f2f 100755 --- a/examples/02-callback-function/main.py +++ b/examples/02-callback-function/main.py @@ -17,7 +17,7 @@ """ import random -from diffsync import DiffSync, DiffSyncModel +from diffsync import Adapter, DiffSyncModel from diffsync.logging import enable_console_logging @@ -30,7 +30,7 @@ class Number(DiffSyncModel): number: int -class DiffSync1(DiffSync): +class Adapter1(Adapter): """DiffSync adapter that contains a number of Numbers constructed in order.""" number = Number @@ -43,7 +43,7 @@ def load(self, count): # pylint: disable=arguments-differ self.add(Number(number=(i + 1))) -class DiffSync2(DiffSync): +class Adapter2(Adapter): """DiffSync adapter that contains a number of Numbers spread randomly across a range.""" number = Number @@ -69,11 +69,11 @@ def main(): enable_console_logging(verbosity=0) # Show WARNING and ERROR logs only # Create a DiffSync1 instance and load it with records numbered 1-100 - ds1 = DiffSync1() + ds1 = Adapter1() ds1.load(count=100) # Create a DiffSync2 instance and load it with 100 random records in the range 1-200 - ds2 = DiffSync2() + ds2 = Adapter2() ds2.load(count=100) # Identify and attempt to resolve the differences between the two, diff --git a/examples/03-remote-system/local_adapter.py b/examples/03-remote-system/local_adapter.py index eb39fdc5..9f38d1e3 100644 --- a/examples/03-remote-system/local_adapter.py +++ b/examples/03-remote-system/local_adapter.py @@ -4,13 +4,13 @@ from slugify import slugify # pylint: disable=import-error from models import Region, Country # pylint: disable=no-name-in-module -from diffsync import DiffSync +from diffsync import Adapter COUNTRIES_FILE = "countries.json" -class LocalAdapter(DiffSync): +class LocalAdapter(Adapter): """DiffSync Adapter to Load the list of regions and countries from a local JSON file.""" # Define all data models that this adapter makes use of. diff --git a/examples/03-remote-system/nautobot_adapter.py b/examples/03-remote-system/nautobot_adapter.py index e0fb3868..9ec17c6f 100644 --- a/examples/03-remote-system/nautobot_adapter.py +++ b/examples/03-remote-system/nautobot_adapter.py @@ -4,7 +4,7 @@ from nautobot_models import NautobotCountry, NautobotRegion -from diffsync import DiffSync +from diffsync import Adapter # pylint: disable=attribute-defined-outside-init @@ -22,7 +22,7 @@ ] -class NautobotAdapter(DiffSync): +class NautobotAdapter(Adapter): """Example of a DiffSync adapter implementation using pynautobot to communicate with a remote Nautobot system.""" # We are using NautobotCountry and NautobotRegion instead of Region and Country diff --git a/examples/03-remote-system/nautobot_models.py b/examples/03-remote-system/nautobot_models.py index c1377d88..2baba778 100644 --- a/examples/03-remote-system/nautobot_models.py +++ b/examples/03-remote-system/nautobot_models.py @@ -3,7 +3,7 @@ from models import Region, Country # pylint: disable=no-name-in-module -from diffsync import DiffSync +from diffsync import Adapter # pylint: disable=no-member,too-few-public-methods @@ -30,7 +30,7 @@ class NautobotCountry(Country): """Store the nautobot uuid in the object to allow update and delete of existing object.""" @classmethod - def create(cls, diffsync: DiffSync, ids: dict, attrs: dict): + def create(cls, diffsync: Adapter, ids: dict, attrs: dict): """Create a country object in Nautobot. Args: diff --git a/examples/04-get-update-instantiate/README.md b/examples/04-get-update-instantiate/README.md index ecb1390d..14e2745a 100644 --- a/examples/04-get-update-instantiate/README.md +++ b/examples/04-get-update-instantiate/README.md @@ -1,12 +1,12 @@ # Example 4 - Using get or update helpers -This example aims to expand on [Example 1](https://github.com/networktocode/diffsync/tree/main/examples/01-multiple-data-sources/README.md) that will take advantage of two new helper methods on the `DiffSync` class; `get_or_instantiate` and `update_or_instantiate`. +This example aims to expand on [Example 1](https://github.com/networktocode/diffsync/tree/main/examples/01-multiple-data-sources/README.md) that will take advantage of two new helper methods on the `Adapter` class; `get_or_instantiate` and `update_or_instantiate`. Both methods act similar to Django's `get_or_create` function to return the object and then a boolean to identify whether the object was created or not. Let's dive into each of them. ## get_or_instantiate -The following arguments are supported: model (`DiffSyncModel`), ids (dictionary), and attrs (dictionary). The `model` and `ids` are used to find an existing object. If the object does not currently exist within the `DiffSync` adapter, it will then use `model`, `ids`, and `attrs` to add the object. +The following arguments are supported: model (`DiffSyncModel`), ids (dictionary), and attrs (dictionary). The `model` and `ids` are used to find an existing object. If the object does not currently exist within the `Adapter` adapter, it will then use `model`, `ids`, and `attrs` to add the object. It will then return a tuple that can be unpacked. @@ -69,4 +69,4 @@ BACKEND_DATA_A = [ device.add_child(intf) ``` -The new methods are helpful due to having devices that are part of the same site. As we iterate over the data and load it into the `DiffSync` adapter, we would have to account for `ObjectAlreadyExists` exceptions when we go to add each duplicate site we encounter within the data or possibly several other models depending how complex the synchronization of data is between backends. +The new methods are helpful due to having devices that are part of the same site. As we iterate over the data and load it into the `Adapter` adapter, we would have to account for `ObjectAlreadyExists` exceptions when we go to add each duplicate site we encounter within the data or possibly several other models depending how complex the synchronization of data is between backends. diff --git a/examples/04-get-update-instantiate/backends.py b/examples/04-get-update-instantiate/backends.py index bbc06e43..ba73a8e0 100644 --- a/examples/04-get-update-instantiate/backends.py +++ b/examples/04-get-update-instantiate/backends.py @@ -16,7 +16,7 @@ """ from models import Site, Device, Interface # pylint: disable=no-name-in-module -from diffsync import DiffSync +from diffsync import Adapter BACKEND_DATA_A = [ { @@ -74,7 +74,7 @@ ] -class BackendA(DiffSync): +class BackendA(Adapter): """Example of a DiffSync adapter implementation.""" site = Site @@ -104,7 +104,7 @@ def load(self): device.add_child(intf) -class BackendB(DiffSync): +class BackendB(Adapter): """Example of a DiffSync adapter implementation.""" site = Site diff --git a/examples/05-nautobot-peeringdb/adapter_nautobot.py b/examples/05-nautobot-peeringdb/adapter_nautobot.py index 7970274d..84be2d69 100644 --- a/examples/05-nautobot-peeringdb/adapter_nautobot.py +++ b/examples/05-nautobot-peeringdb/adapter_nautobot.py @@ -2,7 +2,7 @@ # pylint: disable=import-error,no-name-in-module import pynautobot from models import RegionModel, SiteModel -from diffsync import DiffSync +from diffsync import Adapter class RegionNautobotModel(RegionModel): @@ -116,7 +116,7 @@ def delete(self): # pylint: disable= useless-super-delegation return super().delete() -class NautobotRemote(DiffSync): +class NautobotRemote(Adapter): """DiffSync adapter class for loading data from a remote Nautobot instance using Python requests.""" # Model classes used by this adapter class diff --git a/examples/05-nautobot-peeringdb/adapter_peeringdb.py b/examples/05-nautobot-peeringdb/adapter_peeringdb.py index 08feb600..91cdf6ae 100644 --- a/examples/05-nautobot-peeringdb/adapter_peeringdb.py +++ b/examples/05-nautobot-peeringdb/adapter_peeringdb.py @@ -5,7 +5,7 @@ from slugify import slugify import pycountry from models import RegionModel, SiteModel -from diffsync import DiffSync +from diffsync import Adapter from diffsync.exceptions import ObjectNotFound @@ -13,7 +13,7 @@ PEERINGDB_API_KEY = os.environ.get("PEERINGDB_API_KEY", "").strip() -class PeeringDB(DiffSync): +class PeeringDB(Adapter): """DiffSync adapter using requests to communicate with PeeringDB.""" # Model classes used by this adapter class diff --git a/examples/06-ip-prefixes/adapter_ipam_a.py b/examples/06-ip-prefixes/adapter_ipam_a.py index 4b43595e..5463cd46 100644 --- a/examples/06-ip-prefixes/adapter_ipam_a.py +++ b/examples/06-ip-prefixes/adapter_ipam_a.py @@ -3,7 +3,7 @@ import ipaddress import yaml from models import Prefix # pylint: disable=no-name-in-module -from diffsync import DiffSync +from diffsync import Adapter dirname = os.path.dirname(os.path.realpath(__file__)) @@ -50,7 +50,7 @@ def delete(self): return super().delete() -class IpamA(DiffSync): +class IpamA(Adapter): """IPAM A DiffSync adapter implementation.""" prefix = IpamAPrefix diff --git a/examples/06-ip-prefixes/adapter_ipam_b.py b/examples/06-ip-prefixes/adapter_ipam_b.py index b29e76b8..7a6eadb3 100644 --- a/examples/06-ip-prefixes/adapter_ipam_b.py +++ b/examples/06-ip-prefixes/adapter_ipam_b.py @@ -2,7 +2,7 @@ import os import yaml from models import Prefix # pylint: disable=no-name-in-module -from diffsync import DiffSync +from diffsync import Adapter dirname = os.path.dirname(os.path.realpath(__file__)) @@ -55,7 +55,7 @@ def delete(self): return super().delete() -class IpamB(DiffSync): +class IpamB(Adapter): """IPAM A DiffSync adapter implementation.""" prefix = IpamBPrefix diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index e0dd85c7..498e8890 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -18,7 +18,7 @@ import pytest -from diffsync import DiffSync, DiffSyncModel +from diffsync import Adapter, DiffSyncModel from diffsync.diff import Diff, DiffElement from diffsync.exceptions import ObjectNotCreated, ObjectNotUpdated, ObjectNotDeleted @@ -35,7 +35,7 @@ class ErrorProneModelMixin: _counter: ClassVar[int] = 0 @classmethod - def create(cls, diffsync: DiffSync, ids: Dict, attrs: Dict): + def create(cls, diffsync: Adapter, ids: Dict, attrs: Dict): """As DiffSyncModel.create(), but periodically throw exceptions.""" cls._counter += 1 if not cls._counter % 5: @@ -69,7 +69,7 @@ class ExceptionModelMixin: """Test class that always throws exceptions when creating/updating/deleting instances.""" @classmethod - def create(cls, diffsync: DiffSync, ids: Dict, attrs: Dict): + def create(cls, diffsync: Adapter, ids: Dict, attrs: Dict): """As DiffSyncModel.create(), but always throw exceptions.""" raise NotImplementedError @@ -160,7 +160,7 @@ def interface(device_name="device1", name="eth0", **kwargs): @pytest.fixture def generic_diffsync(): """Provide a generic DiffSync instance.""" - return DiffSync() + return Adapter() class UnusedModel(DiffSyncModel): @@ -172,7 +172,7 @@ class UnusedModel(DiffSyncModel): name: str -class GenericBackend(DiffSync): +class GenericBackend(Adapter): """An example semi-abstract subclass of DiffSync.""" site = Site # to be overridden by subclasses diff --git a/tests/unit/test_diffsync.py b/tests/unit/test_diffsync.py index 74727be8..824b0f48 100644 --- a/tests/unit/test_diffsync.py +++ b/tests/unit/test_diffsync.py @@ -5,7 +5,7 @@ import pytest -from diffsync import DiffSync, DiffSyncModel +from diffsync import Adapter, DiffSyncModel from diffsync.enum import DiffSyncFlags, DiffSyncModelFlags from diffsync.exceptions import DiffClassMismatch, ObjectAlreadyExists, ObjectNotFound, ObjectCrudException @@ -351,7 +351,7 @@ def test_diffsync_subclass_validation_name_mismatch(): # pylint: disable=unused-variable with pytest.raises(AttributeError) as excinfo: - class BadElementName(DiffSync): + class BadElementName(Adapter): """DiffSync with a DiffSyncModel attribute whose name does not match the modelname.""" dev_class = Device # should be device = Device @@ -365,7 +365,7 @@ def test_diffsync_subclass_validation_missing_top_level(): # pylint: disable=unused-variable with pytest.raises(AttributeError) as excinfo: - class MissingTopLevel(DiffSync): + class MissingTopLevel(Adapter): """DiffSync whose top_level references an attribute that does not exist on the class.""" top_level = ["missing"] @@ -379,7 +379,7 @@ def test_diffsync_subclass_validation_top_level_not_diffsyncmodel(): # pylint: disable=unused-variable with pytest.raises(AttributeError) as excinfo: - class TopLevelNotDiffSyncModel(DiffSync): + class TopLevelNotDiffSyncModel(Adapter): """DiffSync whose top_level references an attribute that is not a DiffSyncModel subclass.""" age = 0 diff --git a/tests/unit/test_diffsync_model_flags.py b/tests/unit/test_diffsync_model_flags.py index 76457ccf..a7525d53 100644 --- a/tests/unit/test_diffsync_model_flags.py +++ b/tests/unit/test_diffsync_model_flags.py @@ -18,7 +18,7 @@ import pytest -from diffsync import DiffSync, DiffSyncModel +from diffsync import Adapter, DiffSyncModel from diffsync.enum import DiffSyncModelFlags from diffsync.exceptions import ObjectNotFound @@ -141,7 +141,7 @@ def delete(self): call_order.append(self.name) return super().delete() - class TestBackend(DiffSync): # pylint: disable=missing-class-docstring + class TestBackend(Adapter): # pylint: disable=missing-class-docstring top_level = ["parent"] parent = TestModelParent From 3ed568d299f2b3ec75c6c97e11140187350cfd89 Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Thu, 24 Aug 2023 17:06:48 -0600 Subject: [PATCH 06/12] pins poetry in Dockerfile to 1.5.1 --- .github/workflows/ci.yml | 4 +++- Dockerfile | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec1b68d0..43979776 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -130,6 +130,7 @@ jobs: fail-fast: true matrix: python-version: ["3.7", "3.8", "3.9", "3.10"] + poetry-version: ["1.5.1"] runs-on: "ubuntu-20.04" env: PYTHON_VER: "${{ matrix.python-version }}" @@ -137,9 +138,10 @@ jobs: - name: "Check out repository code" uses: "actions/checkout@v2" - name: "Setup environment" - uses: "networktocode/gh-action-setup-poetry-environment@v5" + uses: "networktocode/gh-action-setup-poetry-environment@3ea5d3e" with: python-version: "${{ matrix.python-version }}" + poetry-version: "${{ matrix.poetry-version }}" - name: "Install redis" run: "sudo apt-get install -y redis" - name: "Run poetry Install" diff --git a/Dockerfile b/Dockerfile index 824f054d..e5b36ce7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip \ - && pip install poetry + && pip install poetry==1.5.1 WORKDIR /local From b23d186fb3cbbabfc9ec652d8d93f8519df1a108 Mon Sep 17 00:00:00 2001 From: Leo Kirchner Date: Thu, 31 Aug 2023 12:31:46 -0600 Subject: [PATCH 07/12] fix ci --- .github/workflows/ci.yml | 2 +- tests/unit/test_diffsync.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 43979776..4e4cd622 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,7 +138,7 @@ jobs: - name: "Check out repository code" uses: "actions/checkout@v2" - name: "Setup environment" - uses: "networktocode/gh-action-setup-poetry-environment@3ea5d3e" + uses: "networktocode/gh-action-setup-poetry-environment@3ea5d3ecf382cdcb0c74d4c0ff0629d95fce63c7" with: python-version: "${{ matrix.python-version }}" poetry-version: "${{ matrix.poetry-version }}" diff --git a/tests/unit/test_diffsync.py b/tests/unit/test_diffsync.py index 824b0f48..6f7feaed 100644 --- a/tests/unit/test_diffsync.py +++ b/tests/unit/test_diffsync.py @@ -13,8 +13,8 @@ def test_diffsync_default_name_type(generic_diffsync): - assert generic_diffsync.type == "DiffSync" - assert generic_diffsync.name == "DiffSync" + assert generic_diffsync.type == "Adapter" + assert generic_diffsync.name == "Adapter" def test_diffsync_generic_load_is_noop(generic_diffsync): From 3d70c878695c1d87ca6fe877803d8f47ec598f79 Mon Sep 17 00:00:00 2001 From: James Harr Date: Mon, 20 Nov 2023 15:57:21 +0000 Subject: [PATCH 08/12] feat: Remove DiffSyncModel.diffsync field - Remove DiffSyncModel.diffsync field - Add diffsync parameter to DiffSyncModel.create/update/delete This closes #256 --- diffsync/__init__.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/diffsync/__init__.py b/diffsync/__init__.py index ddaf0bc5..e7a14d10 100644 --- a/diffsync/__init__.py +++ b/diffsync/__init__.py @@ -91,9 +91,6 @@ class DiffSyncModel(BaseModel): Can be set as a class attribute or an instance attribute as needed. """ - diffsync: Optional["Adapter"] = None - """Optional: the DiffSync instance that owns this model instance.""" - _status: DiffSyncStatus = PrivateAttr(DiffSyncStatus.SUCCESS) """Status of the last attempt at creating/updating/deleting this model.""" @@ -216,7 +213,7 @@ def create(cls, diffsync: "Adapter", ids: Dict, attrs: Dict) -> Optional[Self]: """ return cls.create_base(diffsync=diffsync, ids=ids, attrs=attrs) - def update_base(self, attrs: Dict) -> Optional[Self]: + def update_base(self, diffsync: "Adapter", attrs: Dict) -> Optional[Self]: """Base Update method to update the attributes of this instance, along with any platform-specific data updates. This method is not meant to be subclassed, users should redefine update() instead. @@ -234,7 +231,7 @@ def update_base(self, attrs: Dict) -> Optional[Self]: self.set_status(DiffSyncStatus.SUCCESS, "Updated successfully") return self - def update(self, attrs: Dict) -> Optional[Self]: + def update(self, diffsync: "Adapter", attrs: Dict) -> Optional[Self]: """Update the attributes of this instance, along with any platform-specific data updates. Subclasses must call `super().update()` or `self.update_base()`; they may wish to then override the default status information @@ -250,9 +247,9 @@ def update(self, attrs: Dict) -> Optional[Self]: Raises: ObjectNotUpdated: if an error occurred. """ - return self.update_base(attrs=attrs) + return self.update_base(diffsync=diffsync, attrs=attrs) - def delete_base(self) -> Optional[Self]: + def delete_base(self, diffsync: "Adapter") -> Optional[Self]: """Base delete method Delete any platform-specific data corresponding to this instance. This method is not meant to be subclassed, users should redefine delete() instead. @@ -263,7 +260,7 @@ def delete_base(self) -> Optional[Self]: self.set_status(DiffSyncStatus.SUCCESS, "Deleted successfully") return self - def delete(self) -> Optional[Self]: + def delete(self, diffsync: "Adapter") -> Optional[Self]: """Delete any platform-specific data corresponding to this instance. Subclasses must call `super().delete()` or `self.delete_base()`; they may wish to then override the default status information @@ -276,7 +273,7 @@ def delete(self) -> Optional[Self]: Raises: ObjectNotDeleted: if an error occurred. """ - return self.delete_base() + return self.delete_base(diffsync=diffsync) @classmethod def get_type(cls) -> StrType: From 095e8ed4d6b91581c7e897803360b9975a246136 Mon Sep 17 00:00:00 2001 From: James Harr Date: Mon, 20 Nov 2023 15:59:39 +0000 Subject: [PATCH 09/12] refactor: Fix calls that expect DiffSyncModel.diffsync field --- diffsync/__init__.py | 17 +++++++++++------ diffsync/helpers.py | 4 ++-- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/diffsync/__init__.py b/diffsync/__init__.py index e7a14d10..d42f772e 100644 --- a/diffsync/__init__.py +++ b/diffsync/__init__.py @@ -149,7 +149,7 @@ def json(self, **kwargs: Any) -> StrType: kwargs["exclude_defaults"] = True return super().model_dump_json(**kwargs) - def str(self, include_children: bool = True, indent: int = 0) -> StrType: + def str(self, diffsync: "Adapter", include_children: bool = True, indent: int = 0) -> StrType: """Build a detailed string representation of this DiffSyncModel and optionally its children.""" margin = " " * indent output = f"{margin}{self.get_type()}: {self.get_unique_id()}: {self.get_attrs()}" @@ -158,13 +158,15 @@ def str(self, include_children: bool = True, indent: int = 0) -> StrType: child_ids = getattr(self, fieldname) if not child_ids: output += ": []" - elif not self.diffsync or not include_children: + elif not diffsync or not include_children: output += f": {child_ids}" else: for child_id in child_ids: try: - child = self.diffsync.get(modelname, child_id) - output += "\n" + child.str(include_children=include_children, indent=indent + 4) + child = diffsync.get(modelname, child_id) + output += "\n" + child.str( + diffsync=diffsync, include_children=include_children, indent=indent + 4 + ) except ObjectNotFound: output += f"\n{margin} {child_id} (ERROR: details unavailable)" return output @@ -188,7 +190,8 @@ def create_base(cls, diffsync: "Adapter", ids: Dict, attrs: Dict) -> Optional[Se Returns: DiffSyncModel: instance of this class. """ - model = cls(**ids, diffsync=diffsync, **attrs) + # pylint: disable=unused-argument + model = cls(**ids, **attrs) model.set_status(DiffSyncStatus.SUCCESS, "Created successfully") return model @@ -224,6 +227,7 @@ def update_base(self, diffsync: "Adapter", attrs: Dict) -> Optional[Self]: Returns: DiffSyncModel: this instance. """ + # pylint: disable=unused-argument for attr, value in attrs.items(): # TODO: enforce that only attrs in self._attributes can be updated in this way? setattr(self, attr, value) @@ -257,6 +261,7 @@ def delete_base(self, diffsync: "Adapter") -> Optional[Self]: Returns: DiffSyncModel: this instance. """ + # pylint: disable=unused-argument self.set_status(DiffSyncStatus.SUCCESS, "Deleted successfully") return self @@ -506,7 +511,7 @@ def str(self, indent: int = 0) -> StrType: output += ": []" else: for model in models: - output += "\n" + model.str(indent=indent + 2) + output += "\n" + model.str(diffsync=self, indent=indent + 2) return output def load_from_dict(self, data: Dict) -> None: diff --git a/diffsync/helpers.py b/diffsync/helpers.py index b51f142a..cc6cf2cb 100644 --- a/diffsync/helpers.py +++ b/diffsync/helpers.py @@ -427,11 +427,11 @@ def sync_model( # pylint: disable=too-many-branches, unused-argument elif self.action == DiffSyncActions.UPDATE: if dst_model is None: raise ObjectNotUpdated(f"Failed to update {self.model_class.get_type()} {ids} - not found!") - dst_model = dst_model.update(attrs=attrs) + dst_model = dst_model.update(diffsync=self.dst_diffsync, attrs=attrs) elif self.action == DiffSyncActions.DELETE: if dst_model is None: raise ObjectNotDeleted(f"Failed to delete {self.model_class.get_type()} {ids} - not found!") - dst_model = dst_model.delete() + dst_model = dst_model.delete(diffsync=self.dst_diffsync) else: raise ObjectCrudException(f'Unknown action "{self.action}"!') From 2c7d924aa1707e5b138820a94b8e8e6ffa6b79c9 Mon Sep 17 00:00:00 2001 From: James Harr Date: Mon, 20 Nov 2023 16:00:34 +0000 Subject: [PATCH 10/12] refactor: Remove unnecessary DiffSyncModel.diffsync field handling from storage engines --- diffsync/store/__init__.py | 3 --- diffsync/store/local.py | 3 --- diffsync/store/redis.py | 3 --- 3 files changed, 9 deletions(-) diff --git a/diffsync/store/__init__.py b/diffsync/store/__init__.py index 3dacf330..2ed91238 100644 --- a/diffsync/store/__init__.py +++ b/diffsync/store/__init__.py @@ -95,9 +95,6 @@ def remove(self, *, obj: "DiffSyncModel", remove_children: bool = False) -> None self.remove_item(modelname, uid) - if obj.diffsync: - obj.diffsync = None - if remove_children: for child_type, child_fieldname in obj.get_children_mapping().items(): for child_id in getattr(obj, child_fieldname): diff --git a/diffsync/store/local.py b/diffsync/store/local.py index 82bb69ba..3ca8e972 100644 --- a/diffsync/store/local.py +++ b/diffsync/store/local.py @@ -108,9 +108,6 @@ def add(self, *, obj: "DiffSyncModel") -> None: # Return so we don't have to change anything on the existing object and underlying data return - if not obj.diffsync: - obj.diffsync = self.diffsync - self._data[modelname][uid] = obj def update(self, *, obj: "DiffSyncModel") -> None: diff --git a/diffsync/store/redis.py b/diffsync/store/redis.py index 927dbf5e..a867c004 100644 --- a/diffsync/store/redis.py +++ b/diffsync/store/redis.py @@ -65,7 +65,6 @@ def _get_object_from_redis_key(self, key: str) -> "DiffSyncModel": pickled_object = self._store.get(key) if pickled_object: obj_result = loads(pickled_object) # nosec - obj_result.diffsync = self.diffsync return obj_result raise ObjectNotFound(f"{key} not present in Cache") @@ -178,7 +177,6 @@ def add(self, *, obj: "DiffSyncModel") -> None: # Remove the diffsync object before sending to Redis obj_copy = copy.copy(obj) - obj_copy.diffsync = None self._store.set(object_key, dumps(obj_copy)) @@ -193,7 +191,6 @@ def update(self, *, obj: "DiffSyncModel") -> None: object_key = self._get_key_for_object(modelname, uid) obj_copy = copy.copy(obj) - obj_copy.diffsync = None self._store.set(object_key, dumps(obj_copy)) From 6813ec012c7aecd8e7fe07f6b778c86fe930f6b7 Mon Sep 17 00:00:00 2001 From: James Harr Date: Mon, 20 Nov 2023 16:01:02 +0000 Subject: [PATCH 11/12] test: Adapt tests to new API --- tests/unit/conftest.py | 12 ++++++------ tests/unit/test_diffsync.py | 2 +- tests/unit/test_diffsync_model.py | 18 ++++++++---------- tests/unit/test_diffsync_model_flags.py | 8 ++++---- 4 files changed, 19 insertions(+), 21 deletions(-) diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index c72d2134..ab5f3f40 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -44,7 +44,7 @@ def create(cls, diffsync: Adapter, ids: Dict, attrs: Dict): return None # non-fatal error return super().create(diffsync, ids, attrs) # type: ignore - def update(self, attrs: Dict): + def update(self, diffsync: Adapter, attrs: Dict): """As DiffSyncModel.update(), but periodically throw exceptions.""" # pylint: disable=protected-access self.__class__._counter += 1 @@ -52,9 +52,9 @@ def update(self, attrs: Dict): raise ObjectNotUpdated("Random update error!") if not self.__class__._counter % 4: return None # non-fatal error - return super().update(attrs) # type: ignore + return super().update(diffsync, attrs) # type: ignore - def delete(self): + def delete(self, diffsync: Adapter): """As DiffSyncModel.delete(), but periodically throw exceptions.""" # pylint: disable=protected-access self.__class__._counter += 1 @@ -62,7 +62,7 @@ def delete(self): raise ObjectNotDeleted("Random deletion error!") if not self.__class__._counter % 4: return None # non-fatal error - return super().delete() # type: ignore + return super().delete(diffsync) # type: ignore class ExceptionModelMixin: @@ -73,11 +73,11 @@ def create(cls, diffsync: Adapter, ids: Dict, attrs: Dict): """As DiffSyncModel.create(), but always throw exceptions.""" raise NotImplementedError - def update(self, attrs: Dict): + def update(self, diffsync: Adapter, attrs: Dict): """As DiffSyncModel.update(), but always throw exceptions.""" raise NotImplementedError - def delete(self): + def delete(self, diffsync: Adapter): """As DiffSyncModel.delete(), but always throw exceptions.""" raise NotImplementedError diff --git a/tests/unit/test_diffsync.py b/tests/unit/test_diffsync.py index 6f7feaed..bf65c5cc 100644 --- a/tests/unit/test_diffsync.py +++ b/tests/unit/test_diffsync.py @@ -961,7 +961,7 @@ def test_diffsync_sync_skip_children_on_delete(backend_a): class NoDeleteInterface(Interface): """Interface that shouldn't be deleted directly.""" - def delete(self): + def delete(self, diffsync): raise RuntimeError("Don't delete me, bro!") class NoDeleteInterfaceDiffSync(BackendA): diff --git a/tests/unit/test_diffsync_model.py b/tests/unit/test_diffsync_model.py index e7d6a6b4..f2b4d02f 100644 --- a/tests/unit/test_diffsync_model.py +++ b/tests/unit/test_diffsync_model.py @@ -50,7 +50,7 @@ def test_diffsync_model_json_with_no_data(generic_diffsync_model): def test_diffsync_model_str_with_no_data(generic_diffsync_model): - assert generic_diffsync_model.str() == "diffsyncmodel: : {}" + assert generic_diffsync_model.str(diffsync=None) == "diffsyncmodel: : {}" def test_diffsync_model_subclass_getters(make_site, make_device, make_interface): @@ -113,7 +113,7 @@ def test_diffsync_model_json_with_data(make_interface): def test_diffsync_model_str_with_data(make_interface): intf = make_interface() # str() only includes _attributes - assert intf.str() == "interface: device1__eth0: {'interface_type': 'ethernet', 'description': None}" + assert intf.str(diffsync=None) == "interface: device1__eth0: {'interface_type': 'ethernet', 'description': None}" def test_diffsync_model_subclass_add_remove(make_site, make_device, make_interface): @@ -196,7 +196,7 @@ def test_diffsync_model_str_with_children(generic_diffsync, make_site, make_devi generic_diffsync.add(device1) assert ( - site1.str() + site1.str(diffsync=generic_diffsync) == """\ site: site1: {} devices @@ -207,7 +207,7 @@ def test_diffsync_model_str_with_children(generic_diffsync, make_site, make_devi ) assert ( - site1.str(include_children=False) + site1.str(diffsync=generic_diffsync, include_children=False) == """\ site: site1: {} devices: ['device1']\ @@ -219,7 +219,6 @@ def test_diffsync_model_subclass_crud(generic_diffsync): """Test basic CRUD operations on generic DiffSyncModel subclasses.""" device1 = Device.create(generic_diffsync, {"name": "device1"}, {"role": "spine"}) assert isinstance(device1, Device) - assert device1.diffsync == generic_diffsync assert device1.name == "device1" assert device1.role == "spine" @@ -229,18 +228,17 @@ def test_diffsync_model_subclass_crud(generic_diffsync): {"description": "some description"}, ) assert isinstance(device1_eth0, Interface) - assert device1_eth0.diffsync == generic_diffsync assert device1_eth0.name == "eth0" assert device1_eth0.device_name == "device1" assert device1_eth0.description == "some description" - device1 = device1.update({"site_name": "site1", "role": "leaf"}) + device1 = device1.update(generic_diffsync, {"site_name": "site1", "role": "leaf"}) assert isinstance(device1, Device) assert device1.name == "device1" assert device1.site_name == "site1" assert device1.role == "leaf" - device1_eth0 = device1_eth0.update({"description": ""}) + device1_eth0 = device1_eth0.update(generic_diffsync, {"description": ""}) assert isinstance(device1_eth0, Interface) assert device1_eth0.name == "eth0" assert device1_eth0.device_name == "device1" @@ -248,10 +246,10 @@ def test_diffsync_model_subclass_crud(generic_diffsync): # TODO: negative tests - try to update identifiers with update(), for example - device1 = device1.delete() + device1 = device1.delete(generic_diffsync) assert isinstance(device1, Device) - device1_eth0.delete() + device1_eth0.delete(generic_diffsync) assert isinstance(device1_eth0, Interface) diff --git a/tests/unit/test_diffsync_model_flags.py b/tests/unit/test_diffsync_model_flags.py index a7525d53..70b88044 100644 --- a/tests/unit/test_diffsync_model_flags.py +++ b/tests/unit/test_diffsync_model_flags.py @@ -125,9 +125,9 @@ class TestModelChild(DiffSyncModel): # pylint: disable=missing-class-docstring name: str - def delete(self): + def delete(self, diffsync: Adapter): call_order.append(self.name) - return super().delete() + return super().delete(diffsync) class TestModelParent(DiffSyncModel): # pylint: disable=missing-class-docstring _modelname = "parent" @@ -137,9 +137,9 @@ class TestModelParent(DiffSyncModel): # pylint: disable=missing-class-docstring name: str children: List[TestModelChild] = [] - def delete(self): + def delete(self, diffsync: Adapter): call_order.append(self.name) - return super().delete() + return super().delete(diffsync) class TestBackend(Adapter): # pylint: disable=missing-class-docstring top_level = ["parent"] From 2fed5f2867e19cbf4c69d37709508d3d520688f6 Mon Sep 17 00:00:00 2001 From: James Harr Date: Mon, 20 Nov 2023 16:10:01 +0000 Subject: [PATCH 12/12] doc: Update docs+examples to show new signatures --- .../getting_started/01-getting-started.md | 8 +++---- examples/03-remote-system/nautobot_models.py | 14 +++++------ .../05-nautobot-peeringdb/adapter_nautobot.py | 24 ++++++++++--------- examples/06-ip-prefixes/adapter_ipam_a.py | 14 +++++------ examples/06-ip-prefixes/adapter_ipam_b.py | 14 +++++------ 5 files changed, 38 insertions(+), 36 deletions(-) diff --git a/docs/source/getting_started/01-getting-started.md b/docs/source/getting_started/01-getting-started.md index 9b99cc35..a2d48832 100644 --- a/docs/source/getting_started/01-getting-started.md +++ b/docs/source/getting_started/01-getting-started.md @@ -186,15 +186,15 @@ class Device(DiffSyncModel): # Call the super().create() method to create the in-memory DiffSyncModel instance return super().create(ids=ids, diffsync=diffsync, attrs=attrs) - def update(self, attrs): + def update(self, diffsync, attrs): ## TODO add your own logic here to update the device on the remote system # Call the super().update() method to update the in-memory DiffSyncModel instance - return super().update(attrs) + return super().update(diffsync, attrs) - def delete(self): + def delete(self, diffsync): ## TODO add your own logic here to delete the device on the remote system # Call the super().delete() method to remove the DiffSyncModel instance from its parent DiffSync adapter - super().delete() + super().delete(diffsync) return self ``` diff --git a/examples/03-remote-system/nautobot_models.py b/examples/03-remote-system/nautobot_models.py index 2baba778..66522069 100644 --- a/examples/03-remote-system/nautobot_models.py +++ b/examples/03-remote-system/nautobot_models.py @@ -64,7 +64,7 @@ def create(cls, diffsync: Adapter, ids: dict, attrs: dict): item = super().create(ids=ids, diffsync=diffsync, attrs=attrs) return item - def update(self, attrs: dict): + def update(self, diffsync: Adapter, attrs: dict): """Update a country object in Nautobot. Args: @@ -77,8 +77,8 @@ def update(self, attrs: dict): Raises: ObjectNotUpdated: if an error occurred. """ - # Retrive the pynautobot object from Nautobot since we only have the UUID internally - remote = self.diffsync.nautobot.dcim.regions.get(self.remote_id) + # Retrieve the pynautobot object from Nautobot since we only have the UUID internally + remote = diffsync.nautobot.dcim.regions.get(self.remote_id) # Convert the internal attrs to Nautobot format if "population" in attrs: @@ -89,17 +89,17 @@ def update(self, attrs: dict): remote.save() print(f"Updated Country {self.slug} | {attrs}") - return super().update(attrs) + return super().update(diffsync, attrs) - def delete(self): + def delete(self, diffsync: Adapter): """Delete a country object in Nautobot. Returns: NautobotCountry: DiffSync object """ # Retrieve the pynautobot object and delete the object in Nautobot - remote = self.diffsync.nautobot.dcim.regions.get(self.remote_id) + remote = diffsync.nautobot.dcim.regions.get(self.remote_id) remote.delete() - super().delete() + super().delete(diffsync) return self diff --git a/examples/05-nautobot-peeringdb/adapter_nautobot.py b/examples/05-nautobot-peeringdb/adapter_nautobot.py index 84be2d69..1f5dafcc 100644 --- a/examples/05-nautobot-peeringdb/adapter_nautobot.py +++ b/examples/05-nautobot-peeringdb/adapter_nautobot.py @@ -30,13 +30,14 @@ def create(cls, diffsync, ids, attrs): return super().create(diffsync, ids=ids, attrs=attrs) - def update(self, attrs): + def update(self, diffsync, attrs): """Update an existing Region record in remote Nautobot. Args: + diffsync (Adapter): Adapter this model instance belongs to attrs (dict): Updated values for this record's _attributes """ - region = self.diffsync.nautobot_api.dcim.regions.get(name=self.name) + region = diffsync.nautobot_api.dcim.regions.get(name=self.name) data = {} if "slug" in attrs: data["slug"] = attrs["slug"] @@ -44,18 +45,18 @@ def update(self, attrs): data["description"] = attrs["description"] if "parent_name" in attrs: if attrs["parent_name"]: - data["parent"] = str(self.diffsync.get(self.diffsync.region, attrs["parent_name"]).name) + data["parent"] = str(diffsync.get(diffsync.region, attrs["parent_name"]).name) else: data["parent"] = None region.update(data=data) - return super().update(attrs) + return super().update(diffsync, attrs) - def delete(self): # pylint: disable= useless-super-delegation + def delete(self, diffsync): # pylint: disable= useless-super-delegation """Delete an existing Region record from remote Nautobot.""" # Not implemented - return super().delete() + return super().delete(diffsync) class SiteNautobotModel(SiteModel): @@ -81,13 +82,14 @@ def create(cls, diffsync, ids, attrs): ) return super().create(diffsync, ids=ids, attrs=attrs) - def update(self, attrs): + def update(self, diffsync, attrs): """Update an existing Site record in remote Nautobot. Args: + diffsync (Adapter): Adapter this model instance belongs to attrs (dict): Updated values for this record's _attributes """ - site = self.diffsync.nautobot_api.dcim.sites.get(name=self.name) + site = diffsync.nautobot_api.dcim.sites.get(name=self.name) data = {} if "slug" in attrs: @@ -108,12 +110,12 @@ def update(self, attrs): site.update(data=data) - return super().update(attrs) + return super().update(diffsync, attrs) - def delete(self): # pylint: disable= useless-super-delegation + def delete(self, diffsync): # pylint: disable= useless-super-delegation """Delete an existing Site record from remote Nautobot.""" # Not implemented - return super().delete() + return super().delete(diffsync) class NautobotRemote(Adapter): diff --git a/examples/06-ip-prefixes/adapter_ipam_a.py b/examples/06-ip-prefixes/adapter_ipam_a.py index 5463cd46..386786d2 100644 --- a/examples/06-ip-prefixes/adapter_ipam_a.py +++ b/examples/06-ip-prefixes/adapter_ipam_a.py @@ -26,9 +26,9 @@ def create(cls, diffsync, ids, attrs): return super().create(diffsync, ids=ids, attrs=attrs) - def update(self, attrs): + def update(self, diffsync, attrs): """Update a Prefix record in IPAM A.""" - for elem in self.diffsync.data: + for elem in diffsync.data: if elem["cidr"] == self.prefix: if "vrf" in attrs: elem["vrf"] = attrs["vrf"] @@ -38,16 +38,16 @@ def update(self, attrs): elem["customer_id"] = attrs["tenant"] break - return super().update(attrs) + return super().update(diffsync, attrs) - def delete(self): + def delete(self, diffsync): """Delete a Prefix record in IPAM A.""" - for index, elem in enumerate(self.diffsync.data): + for index, elem in enumerate(diffsync.data): if elem["cidr"] == self.prefix: - del self.diffsync.data[index] + del diffsync.data[index] break - return super().delete() + return super().delete(diffsync) class IpamA(Adapter): diff --git a/examples/06-ip-prefixes/adapter_ipam_b.py b/examples/06-ip-prefixes/adapter_ipam_b.py index 7a6eadb3..08efcd7c 100644 --- a/examples/06-ip-prefixes/adapter_ipam_b.py +++ b/examples/06-ip-prefixes/adapter_ipam_b.py @@ -25,12 +25,12 @@ def create(cls, diffsync, ids, attrs): return super().create(diffsync, ids=ids, attrs=attrs) - def update(self, attrs): + def update(self, diffsync, attrs): """Update a Prefix record in IPAM B.""" network = self.prefix.split("/")[0] prefix_length = int(self.prefix.split("/")[1]) - for elem in self.diffsync.data: + for elem in diffsync.data: if elem["network"] == network and elem["prefix_length"] == prefix_length: if "vrf" in attrs: elem["vrf"] = attrs["vrf"] @@ -40,19 +40,19 @@ def update(self, attrs): elem["tenant"] = attrs["tenant"] break - return super().update(attrs) + return super().update(diffsync, attrs) - def delete(self): + def delete(self, diffsync: Adapter): """Update a Prefix record in IPAM B.""" network = self.prefix.split("/")[0] prefix_length = int(self.prefix.split("/")[1]) - for index, elem in enumerate(self.diffsync.data): + for index, elem in enumerate(diffsync.data): if elem["network"] == network and elem["prefix_length"] == prefix_length: - del self.diffsync.data[index] + del diffsync.data[index] break - return super().delete() + return super().delete(diffsync) class IpamB(Adapter):