diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 081537815d4d..d9a6177e1dac 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -18,6 +18,21 @@ # or zero if all commands in the pipeline exit successfully. set -eo pipefail +python3 -m pip install --require-hashes -r github/google-cloud-python/.kokoro/requirements-aoss.txt +python3 -m keyring --list-backends + +echo "[distutils] +index-servers = + aoss-1p-python +[aoss-1p-python] +repository: https://us-python.pkg.dev/cloud-aoss-1p/cloud-aoss-1p-python/" >> $HOME/.pypirc + +echo "[install] +index-url = https://us-python.pkg.dev/cloud-aoss-1p/cloud-aoss-1p-python/simple/ +trusted-host = us-python.pkg.dev" >> $HOME/pip.conf + +export PIP_CONFIG_FILE=$HOME/pip.conf + # Start the releasetool reporter python3 -m pip install --require-hashes -r github/google-cloud-python/.kokoro/requirements.txt python3 -m releasetool publish-reporter-script > /tmp/publisher-script; source /tmp/publisher-script diff --git a/.kokoro/requirements-aoss.in b/.kokoro/requirements-aoss.in new file mode 100644 index 000000000000..bd6769b591d5 --- /dev/null +++ b/.kokoro/requirements-aoss.in @@ -0,0 +1,2 @@ +keyring +keyrings.google-artifactregistry-auth diff --git a/.kokoro/requirements-aoss.txt b/.kokoro/requirements-aoss.txt new file mode 100644 index 000000000000..34b8f631e421 --- /dev/null +++ b/.kokoro/requirements-aoss.txt @@ -0,0 +1,277 @@ +# +# This file is autogenerated by pip-compile with Python 3.9 +# by the following command: +# +# pip-compile --allow-unsafe --generate-hashes requirements-aoss.in +# +backports-tarfile==1.2.0 \ + --hash=sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34 \ + --hash=sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991 + # via jaraco-context +cachetools==5.4.0 \ + --hash=sha256:3ae3b49a3d5e28a77a0be2b37dbcb89005058959cb2323858c2657c4a8cab474 \ + --hash=sha256:b8adc2e7c07f105ced7bc56dbb6dfbe7c4a00acce20e2227b3f355be89bc6827 + # via google-auth +certifi==2024.7.4 \ + --hash=sha256:5a1e7645bc0ec61a09e26c36f6106dd4cf40c6db3a1fb6352b0244e7fb057c7b \ + --hash=sha256:c198e21b1289c2ab85ee4e67bb4b4ef3ead0892059901a8d5b622f24a1101e90 + # via requests +cffi==1.16.0 \ + --hash=sha256:0c9ef6ff37e974b73c25eecc13952c55bceed9112be2d9d938ded8e856138bcc \ + --hash=sha256:131fd094d1065b19540c3d72594260f118b231090295d8c34e19a7bbcf2e860a \ + --hash=sha256:1b8ebc27c014c59692bb2664c7d13ce7a6e9a629be20e54e7271fa696ff2b417 \ + --hash=sha256:2c56b361916f390cd758a57f2e16233eb4f64bcbeee88a4881ea90fca14dc6ab \ + --hash=sha256:2d92b25dbf6cae33f65005baf472d2c245c050b1ce709cc4588cdcdd5495b520 \ + --hash=sha256:31d13b0f99e0836b7ff893d37af07366ebc90b678b6664c955b54561fc36ef36 \ + --hash=sha256:32c68ef735dbe5857c810328cb2481e24722a59a2003018885514d4c09af9743 \ + --hash=sha256:3686dffb02459559c74dd3d81748269ffb0eb027c39a6fc99502de37d501faa8 \ + --hash=sha256:582215a0e9adbe0e379761260553ba11c58943e4bbe9c36430c4ca6ac74b15ed \ + --hash=sha256:5b50bf3f55561dac5438f8e70bfcdfd74543fd60df5fa5f62d94e5867deca684 \ + --hash=sha256:5bf44d66cdf9e893637896c7faa22298baebcd18d1ddb6d2626a6e39793a1d56 \ + --hash=sha256:6602bc8dc6f3a9e02b6c22c4fc1e47aa50f8f8e6d3f78a5e16ac33ef5fefa324 \ + --hash=sha256:673739cb539f8cdaa07d92d02efa93c9ccf87e345b9a0b556e3ecc666718468d \ + --hash=sha256:68678abf380b42ce21a5f2abde8efee05c114c2fdb2e9eef2efdb0257fba1235 \ + --hash=sha256:68e7c44931cc171c54ccb702482e9fc723192e88d25a0e133edd7aff8fcd1f6e \ + --hash=sha256:6b3d6606d369fc1da4fd8c357d026317fbb9c9b75d36dc16e90e84c26854b088 \ + --hash=sha256:748dcd1e3d3d7cd5443ef03ce8685043294ad6bd7c02a38d1bd367cfd968e000 \ + --hash=sha256:7651c50c8c5ef7bdb41108b7b8c5a83013bfaa8a935590c5d74627c047a583c7 \ + --hash=sha256:7b78010e7b97fef4bee1e896df8a4bbb6712b7f05b7ef630f9d1da00f6444d2e \ + --hash=sha256:7e61e3e4fa664a8588aa25c883eab612a188c725755afff6289454d6362b9673 \ + --hash=sha256:80876338e19c951fdfed6198e70bc88f1c9758b94578d5a7c4c91a87af3cf31c \ + --hash=sha256:8895613bcc094d4a1b2dbe179d88d7fb4a15cee43c052e8885783fac397d91fe \ + --hash=sha256:88e2b3c14bdb32e440be531ade29d3c50a1a59cd4e51b1dd8b0865c54ea5d2e2 \ + --hash=sha256:8f8e709127c6c77446a8c0a8c8bf3c8ee706a06cd44b1e827c3e6a2ee6b8c098 \ + --hash=sha256:9cb4a35b3642fc5c005a6755a5d17c6c8b6bcb6981baf81cea8bfbc8903e8ba8 \ + --hash=sha256:9f90389693731ff1f659e55c7d1640e2ec43ff725cc61b04b2f9c6d8d017df6a \ + --hash=sha256:a09582f178759ee8128d9270cd1344154fd473bb77d94ce0aeb2a93ebf0feaf0 \ + --hash=sha256:a6a14b17d7e17fa0d207ac08642c8820f84f25ce17a442fd15e27ea18d67c59b \ + --hash=sha256:a72e8961a86d19bdb45851d8f1f08b041ea37d2bd8d4fd19903bc3083d80c896 \ + --hash=sha256:abd808f9c129ba2beda4cfc53bde801e5bcf9d6e0f22f095e45327c038bfe68e \ + --hash=sha256:ac0f5edd2360eea2f1daa9e26a41db02dd4b0451b48f7c318e217ee092a213e9 \ + --hash=sha256:b29ebffcf550f9da55bec9e02ad430c992a87e5f512cd63388abb76f1036d8d2 \ + --hash=sha256:b2ca4e77f9f47c55c194982e10f058db063937845bb2b7a86c84a6cfe0aefa8b \ + --hash=sha256:b7be2d771cdba2942e13215c4e340bfd76398e9227ad10402a8767ab1865d2e6 \ + --hash=sha256:b84834d0cf97e7d27dd5b7f3aca7b6e9263c56308ab9dc8aae9784abb774d404 \ + --hash=sha256:b86851a328eedc692acf81fb05444bdf1891747c25af7529e39ddafaf68a4f3f \ + --hash=sha256:bcb3ef43e58665bbda2fb198698fcae6776483e0c4a631aa5647806c25e02cc0 \ + --hash=sha256:c0f31130ebc2d37cdd8e44605fb5fa7ad59049298b3f745c74fa74c62fbfcfc4 \ + --hash=sha256:c6a164aa47843fb1b01e941d385aab7215563bb8816d80ff3a363a9f8448a8dc \ + --hash=sha256:d8a9d3ebe49f084ad71f9269834ceccbf398253c9fac910c4fd7053ff1386936 \ + --hash=sha256:db8e577c19c0fda0beb7e0d4e09e0ba74b1e4c092e0e40bfa12fe05b6f6d75ba \ + --hash=sha256:dc9b18bf40cc75f66f40a7379f6a9513244fe33c0e8aa72e2d56b0196a7ef872 \ + --hash=sha256:e09f3ff613345df5e8c3667da1d918f9149bd623cd9070c983c013792a9a62eb \ + --hash=sha256:e4108df7fe9b707191e55f33efbcb2d81928e10cea45527879a4749cbe472614 \ + --hash=sha256:e6024675e67af929088fda399b2094574609396b1decb609c55fa58b028a32a1 \ + --hash=sha256:e70f54f1796669ef691ca07d046cd81a29cb4deb1e5f942003f401c0c4a2695d \ + --hash=sha256:e715596e683d2ce000574bae5d07bd522c781a822866c20495e52520564f0969 \ + --hash=sha256:e760191dd42581e023a68b758769e2da259b5d52e3103c6060ddc02c9edb8d7b \ + --hash=sha256:ed86a35631f7bfbb28e108dd96773b9d5a6ce4811cf6ea468bb6a359b256b1e4 \ + --hash=sha256:ee07e47c12890ef248766a6e55bd38ebfb2bb8edd4142d56db91b21ea68b7627 \ + --hash=sha256:fa3a0128b152627161ce47201262d3140edb5a5c3da88d73a1b790a959126956 \ + --hash=sha256:fcc8eb6d5902bb1cf6dc4f187ee3ea80a1eba0a89aba40a5cb20a5087d961357 + # via cryptography +charset-normalizer==3.3.2 \ + --hash=sha256:06435b539f889b1f6f4ac1758871aae42dc3a8c0e24ac9e60c2384973ad73027 \ + --hash=sha256:06a81e93cd441c56a9b65d8e1d043daeb97a3d0856d177d5c90ba85acb3db087 \ + --hash=sha256:0a55554a2fa0d408816b3b5cedf0045f4b8e1a6065aec45849de2d6f3f8e9786 \ + --hash=sha256:0b2b64d2bb6d3fb9112bafa732def486049e63de9618b5843bcdd081d8144cd8 \ + --hash=sha256:10955842570876604d404661fbccbc9c7e684caf432c09c715ec38fbae45ae09 \ + --hash=sha256:122c7fa62b130ed55f8f285bfd56d5f4b4a5b503609d181f9ad85e55c89f4185 \ + --hash=sha256:1ceae2f17a9c33cb48e3263960dc5fc8005351ee19db217e9b1bb15d28c02574 \ + --hash=sha256:1d3193f4a680c64b4b6a9115943538edb896edc190f0b222e73761716519268e \ + --hash=sha256:1f79682fbe303db92bc2b1136016a38a42e835d932bab5b3b1bfcfbf0640e519 \ + --hash=sha256:2127566c664442652f024c837091890cb1942c30937add288223dc895793f898 \ + --hash=sha256:22afcb9f253dac0696b5a4be4a1c0f8762f8239e21b99680099abd9b2b1b2269 \ + --hash=sha256:25baf083bf6f6b341f4121c2f3c548875ee6f5339300e08be3f2b2ba1721cdd3 \ + --hash=sha256:2e81c7b9c8979ce92ed306c249d46894776a909505d8f5a4ba55b14206e3222f \ + --hash=sha256:3287761bc4ee9e33561a7e058c72ac0938c4f57fe49a09eae428fd88aafe7bb6 \ + --hash=sha256:34d1c8da1e78d2e001f363791c98a272bb734000fcef47a491c1e3b0505657a8 \ + --hash=sha256:37e55c8e51c236f95b033f6fb391d7d7970ba5fe7ff453dad675e88cf303377a \ + --hash=sha256:3d47fa203a7bd9c5b6cee4736ee84ca03b8ef23193c0d1ca99b5089f72645c73 \ + --hash=sha256:42cb296636fcc8b0644486d15c12376cb9fa75443e00fb25de0b8602e64c1714 \ + --hash=sha256:45485e01ff4d3630ec0d9617310448a8702f70e9c01906b0d0118bdf9d124cf2 \ + --hash=sha256:4a78b2b446bd7c934f5dcedc588903fb2f5eec172f3d29e52a9096a43722adfc \ + --hash=sha256:4ab2fe47fae9e0f9dee8c04187ce5d09f48eabe611be8259444906793ab7cbce \ + --hash=sha256:4d0d1650369165a14e14e1e47b372cfcb31d6ab44e6e33cb2d4e57265290044d \ + --hash=sha256:549a3a73da901d5bc3ce8d24e0600d1fa85524c10287f6004fbab87672bf3e1e \ + --hash=sha256:55086ee1064215781fff39a1af09518bc9255b50d6333f2e4c74ca09fac6a8f6 \ + --hash=sha256:572c3763a264ba47b3cf708a44ce965d98555f618ca42c926a9c1616d8f34269 \ + --hash=sha256:573f6eac48f4769d667c4442081b1794f52919e7edada77495aaed9236d13a96 \ + --hash=sha256:5b4c145409bef602a690e7cfad0a15a55c13320ff7a3ad7ca59c13bb8ba4d45d \ + --hash=sha256:6463effa3186ea09411d50efc7d85360b38d5f09b870c48e4600f63af490e56a \ + --hash=sha256:65f6f63034100ead094b8744b3b97965785388f308a64cf8d7c34f2f2e5be0c4 \ + --hash=sha256:663946639d296df6a2bb2aa51b60a2454ca1cb29835324c640dafb5ff2131a77 \ + --hash=sha256:6897af51655e3691ff853668779c7bad41579facacf5fd7253b0133308cf000d \ + --hash=sha256:68d1f8a9e9e37c1223b656399be5d6b448dea850bed7d0f87a8311f1ff3dabb0 \ + --hash=sha256:6ac7ffc7ad6d040517be39eb591cac5ff87416c2537df6ba3cba3bae290c0fed \ + --hash=sha256:6b3251890fff30ee142c44144871185dbe13b11bab478a88887a639655be1068 \ + --hash=sha256:6c4caeef8fa63d06bd437cd4bdcf3ffefe6738fb1b25951440d80dc7df8c03ac \ + --hash=sha256:6ef1d82a3af9d3eecdba2321dc1b3c238245d890843e040e41e470ffa64c3e25 \ + --hash=sha256:753f10e867343b4511128c6ed8c82f7bec3bd026875576dfd88483c5c73b2fd8 \ + --hash=sha256:7cd13a2e3ddeed6913a65e66e94b51d80a041145a026c27e6bb76c31a853c6ab \ + --hash=sha256:7ed9e526742851e8d5cc9e6cf41427dfc6068d4f5a3bb03659444b4cabf6bc26 \ + --hash=sha256:7f04c839ed0b6b98b1a7501a002144b76c18fb1c1850c8b98d458ac269e26ed2 \ + --hash=sha256:802fe99cca7457642125a8a88a084cef28ff0cf9407060f7b93dca5aa25480db \ + --hash=sha256:80402cd6ee291dcb72644d6eac93785fe2c8b9cb30893c1af5b8fdd753b9d40f \ + --hash=sha256:8465322196c8b4d7ab6d1e049e4c5cb460d0394da4a27d23cc242fbf0034b6b5 \ + --hash=sha256:86216b5cee4b06df986d214f664305142d9c76df9b6512be2738aa72a2048f99 \ + --hash=sha256:87d1351268731db79e0f8e745d92493ee2841c974128ef629dc518b937d9194c \ + --hash=sha256:8bdb58ff7ba23002a4c5808d608e4e6c687175724f54a5dade5fa8c67b604e4d \ + --hash=sha256:8c622a5fe39a48f78944a87d4fb8a53ee07344641b0562c540d840748571b811 \ + --hash=sha256:8d756e44e94489e49571086ef83b2bb8ce311e730092d2c34ca8f7d925cb20aa \ + --hash=sha256:8f4a014bc36d3c57402e2977dada34f9c12300af536839dc38c0beab8878f38a \ + --hash=sha256:9063e24fdb1e498ab71cb7419e24622516c4a04476b17a2dab57e8baa30d6e03 \ + --hash=sha256:90d558489962fd4918143277a773316e56c72da56ec7aa3dc3dbbe20fdfed15b \ + --hash=sha256:923c0c831b7cfcb071580d3f46c4baf50f174be571576556269530f4bbd79d04 \ + --hash=sha256:95f2a5796329323b8f0512e09dbb7a1860c46a39da62ecb2324f116fa8fdc85c \ + --hash=sha256:96b02a3dc4381e5494fad39be677abcb5e6634bf7b4fa83a6dd3112607547001 \ + --hash=sha256:9f96df6923e21816da7e0ad3fd47dd8f94b2a5ce594e00677c0013018b813458 \ + --hash=sha256:a10af20b82360ab00827f916a6058451b723b4e65030c5a18577c8b2de5b3389 \ + --hash=sha256:a50aebfa173e157099939b17f18600f72f84eed3049e743b68ad15bd69b6bf99 \ + --hash=sha256:a981a536974bbc7a512cf44ed14938cf01030a99e9b3a06dd59578882f06f985 \ + --hash=sha256:a9a8e9031d613fd2009c182b69c7b2c1ef8239a0efb1df3f7c8da66d5dd3d537 \ + --hash=sha256:ae5f4161f18c61806f411a13b0310bea87f987c7d2ecdbdaad0e94eb2e404238 \ + --hash=sha256:aed38f6e4fb3f5d6bf81bfa990a07806be9d83cf7bacef998ab1a9bd660a581f \ + --hash=sha256:b01b88d45a6fcb69667cd6d2f7a9aeb4bf53760d7fc536bf679ec94fe9f3ff3d \ + --hash=sha256:b261ccdec7821281dade748d088bb6e9b69e6d15b30652b74cbbac25e280b796 \ + --hash=sha256:b2b0a0c0517616b6869869f8c581d4eb2dd83a4d79e0ebcb7d373ef9956aeb0a \ + --hash=sha256:b4a23f61ce87adf89be746c8a8974fe1c823c891d8f86eb218bb957c924bb143 \ + --hash=sha256:b4d5f7e22c49087407533347e1d580336f05f6b97c032517da7b1c7bad1a296a \ + --hash=sha256:bd8f7df7d12c2db9fab40bdd87a7c09b1530128315d047a086fa3ae3435cb3a8 \ + --hash=sha256:beb58fe5cdb101e3a055192ac291b7a21e3b7ef4f67fa1d74e331a7f2124341c \ + --hash=sha256:c002b4ffc0be611f0d9da932eb0f704fe2602a9a949d1f738e4c34c75b0863d5 \ + --hash=sha256:c083af607d2515612056a31f0a8d9e0fcb5876b7bfc0abad3ecd275bc4ebc2d5 \ + --hash=sha256:c180f51afb394e165eafe4ac2936a14bee3eb10debc9d9e4db8958fe36afe711 \ + --hash=sha256:c235ebd9baae02f1b77bcea61bce332cb4331dc3617d254df3323aa01ab47bd4 \ + --hash=sha256:cd70574b12bb8a4d2aaa0094515df2463cb429d8536cfb6c7ce983246983e5a6 \ + --hash=sha256:d0eccceffcb53201b5bfebb52600a5fb483a20b61da9dbc885f8b103cbe7598c \ + --hash=sha256:d965bba47ddeec8cd560687584e88cf699fd28f192ceb452d1d7ee807c5597b7 \ + --hash=sha256:db364eca23f876da6f9e16c9da0df51aa4f104a972735574842618b8c6d999d4 \ + --hash=sha256:ddbb2551d7e0102e7252db79ba445cdab71b26640817ab1e3e3648dad515003b \ + --hash=sha256:deb6be0ac38ece9ba87dea880e438f25ca3eddfac8b002a2ec3d9183a454e8ae \ + --hash=sha256:e06ed3eb3218bc64786f7db41917d4e686cc4856944f53d5bdf83a6884432e12 \ + --hash=sha256:e27ad930a842b4c5eb8ac0016b0a54f5aebbe679340c26101df33424142c143c \ + --hash=sha256:e537484df0d8f426ce2afb2d0f8e1c3d0b114b83f8850e5f2fbea0e797bd82ae \ + --hash=sha256:eb00ed941194665c332bf8e078baf037d6c35d7c4f3102ea2d4f16ca94a26dc8 \ + --hash=sha256:eb6904c354526e758fda7167b33005998fb68c46fbc10e013ca97f21ca5c8887 \ + --hash=sha256:eb8821e09e916165e160797a6c17edda0679379a4be5c716c260e836e122f54b \ + --hash=sha256:efcb3f6676480691518c177e3b465bcddf57cea040302f9f4e6e191af91174d4 \ + --hash=sha256:f27273b60488abe721a075bcca6d7f3964f9f6f067c8c4c605743023d7d3944f \ + --hash=sha256:f30c3cb33b24454a82faecaf01b19c18562b1e89558fb6c56de4d9118a032fd5 \ + --hash=sha256:fb69256e180cb6c8a894fee62b3afebae785babc1ee98b81cdf68bbca1987f33 \ + --hash=sha256:fd1abc0d89e30cc4e02e4064dc67fcc51bd941eb395c502aac3ec19fab46b519 \ + --hash=sha256:ff8fa367d09b717b2a17a052544193ad76cd49979c805768879cb63d9ca50561 + # via requests +cryptography==43.0.0 \ + --hash=sha256:0663585d02f76929792470451a5ba64424acc3cd5227b03921dab0e2f27b1709 \ + --hash=sha256:08a24a7070b2b6804c1940ff0f910ff728932a9d0e80e7814234269f9d46d069 \ + --hash=sha256:232ce02943a579095a339ac4b390fbbe97f5b5d5d107f8a08260ea2768be8cc2 \ + --hash=sha256:2905ccf93a8a2a416f3ec01b1a7911c3fe4073ef35640e7ee5296754e30b762b \ + --hash=sha256:299d3da8e00b7e2b54bb02ef58d73cd5f55fb31f33ebbf33bd00d9aa6807df7e \ + --hash=sha256:2c6d112bf61c5ef44042c253e4859b3cbbb50df2f78fa8fae6747a7814484a70 \ + --hash=sha256:31e44a986ceccec3d0498e16f3d27b2ee5fdf69ce2ab89b52eaad1d2f33d8778 \ + --hash=sha256:3d9a1eca329405219b605fac09ecfc09ac09e595d6def650a437523fcd08dd22 \ + --hash=sha256:3dcdedae5c7710b9f97ac6bba7e1052b95c7083c9d0e9df96e02a1932e777895 \ + --hash=sha256:47ca71115e545954e6c1d207dd13461ab81f4eccfcb1345eac874828b5e3eaaf \ + --hash=sha256:4a997df8c1c2aae1e1e5ac49c2e4f610ad037fc5a3aadc7b64e39dea42249431 \ + --hash=sha256:51956cf8730665e2bdf8ddb8da0056f699c1a5715648c1b0144670c1ba00b48f \ + --hash=sha256:5bcb8a5620008a8034d39bce21dc3e23735dfdb6a33a06974739bfa04f853947 \ + --hash=sha256:64c3f16e2a4fc51c0d06af28441881f98c5d91009b8caaff40cf3548089e9c74 \ + --hash=sha256:6e2b11c55d260d03a8cf29ac9b5e0608d35f08077d8c087be96287f43af3ccdc \ + --hash=sha256:7b3f5fe74a5ca32d4d0f302ffe6680fcc5c28f8ef0dc0ae8f40c0f3a1b4fca66 \ + --hash=sha256:844b6d608374e7d08f4f6e6f9f7b951f9256db41421917dfb2d003dde4cd6b66 \ + --hash=sha256:9a8d6802e0825767476f62aafed40532bd435e8a5f7d23bd8b4f5fd04cc80ecf \ + --hash=sha256:aae4d918f6b180a8ab8bf6511a419473d107df4dbb4225c7b48c5c9602c38c7f \ + --hash=sha256:ac1955ce000cb29ab40def14fd1bbfa7af2017cca696ee696925615cafd0dce5 \ + --hash=sha256:b88075ada2d51aa9f18283532c9f60e72170041bba88d7f37e49cbb10275299e \ + --hash=sha256:cb013933d4c127349b3948aa8aaf2f12c0353ad0eccd715ca789c8a0f671646f \ + --hash=sha256:cc70b4b581f28d0a254d006f26949245e3657d40d8857066c2ae22a61222ef55 \ + --hash=sha256:e9c5266c432a1e23738d178e51c2c7a5e2ddf790f248be939448c0ba2021f9d1 \ + --hash=sha256:ea9e57f8ea880eeea38ab5abf9fbe39f923544d7884228ec67d666abd60f5a47 \ + --hash=sha256:ee0c405832ade84d4de74b9029bedb7b31200600fa524d218fc29bfa371e97f5 \ + --hash=sha256:fdcb265de28585de5b859ae13e3846a8e805268a823a12a4da2597f1f5afc9f0 + # via secretstorage +google-auth==2.32.0 \ + --hash=sha256:49315be72c55a6a37d62819e3573f6b416aca00721f7e3e31a008d928bf64022 \ + --hash=sha256:53326ea2ebec768070a94bee4e1b9194c9646ea0c2bd72422785bd0f9abfad7b + # via keyrings-google-artifactregistry-auth +idna==3.7 \ + --hash=sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc \ + --hash=sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0 + # via requests +importlib-metadata==8.2.0 \ + --hash=sha256:11901fa0c2f97919b288679932bb64febaeacf289d18ac84dd68cb2e74213369 \ + --hash=sha256:72e8d4399996132204f9a16dcc751af254a48f8d1b20b9ff0f98d4a8f901e73d + # via keyring +jaraco-classes==3.4.0 \ + --hash=sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd \ + --hash=sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790 + # via keyring +jaraco-context==5.3.0 \ + --hash=sha256:3e16388f7da43d384a1a7cd3452e72e14732ac9fe459678773a3608a812bf266 \ + --hash=sha256:c2f67165ce1f9be20f32f650f25d8edfc1646a8aeee48ae06fb35f90763576d2 + # via keyring +jaraco-functools==4.0.2 \ + --hash=sha256:3460c74cd0d32bf82b9576bbb3527c4364d5b27a21f5158a62aed6c4b42e23f5 \ + --hash=sha256:c9d16a3ed4ccb5a889ad8e0b7a343401ee5b2a71cee6ed192d3f68bc351e94e3 + # via keyring +jeepney==0.8.0 \ + --hash=sha256:5efe48d255973902f6badc3ce55e2aa6c5c3b3bc642059ef3a91247bcfcc5806 \ + --hash=sha256:c0a454ad016ca575060802ee4d590dd912e35c122fa04e70306de3d076cce755 + # via + # keyring + # secretstorage +keyring==25.2.1 \ + --hash=sha256:2458681cdefc0dbc0b7eb6cf75d0b98e59f9ad9b2d4edd319d18f68bdca95e50 \ + --hash=sha256:daaffd42dbda25ddafb1ad5fec4024e5bbcfe424597ca1ca452b299861e49f1b + # via + # -r requirements-aoss.in + # keyrings-google-artifactregistry-auth +keyrings-google-artifactregistry-auth==1.1.2 \ + --hash=sha256:bd6abb72740d2dfeb4a5c03c3b105c6f7dba169caa29dee3959694f1f02c77de \ + --hash=sha256:e3f18b50fa945c786593014dc225810d191671d4f5f8e12d9259e39bad3605a3 + # via -r requirements-aoss.in +more-itertools==10.3.0 \ + --hash=sha256:e5d93ef411224fbcef366a6e8ddc4c5781bc6359d43412a65dd5964e46111463 \ + --hash=sha256:ea6a02e24a9161e51faad17a8782b92a0df82c12c1c8886fec7f0c3fa1a1b320 + # via + # jaraco-classes + # jaraco-functools +pluggy==1.5.0 \ + --hash=sha256:2cffa88e94fdc978c4c574f15f9e59b7f4201d439195c3715ca9e2486f1d0cf1 \ + --hash=sha256:d5783d8a2575b1d2f22c03e92b0a2e18892b45eadc5a8e41625767aa5e6bcc52 + # via keyrings-google-artifactregistry-auth +pyasn1==0.6.0 \ + --hash=sha256:3a35ab2c4b5ef98e17dfdec8ab074046fbda76e281c5a706ccd82328cfc8f64c \ + --hash=sha256:cca4bb0f2df5504f02f6f8a775b6e416ff9b0b3b16f7ee80b5a3153d9b804473 + # via + # pyasn1-modules + # rsa +pyasn1-modules==0.4.0 \ + --hash=sha256:831dbcea1b177b28c9baddf4c6d1013c24c3accd14a1873fffaa6a2e905f17b6 \ + --hash=sha256:be04f15b66c206eed667e0bb5ab27e2b1855ea54a842e5037738099e8ca4ae0b + # via google-auth +pycparser==2.22 \ + --hash=sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6 \ + --hash=sha256:d47c5472466f7131bb482b7dd186918f73a2e087d05d2a50d88957a8498377e5 + # via cffi +requests==2.32.3 \ + --hash=sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760 \ + --hash=sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6 + # via keyrings-google-artifactregistry-auth +rsa==4.9 \ + --hash=sha256:bbe333816d27ed8355b433f85795665a1e9ecec1b7a022906ec6ab9d60bfcbef \ + --hash=sha256:e38464a49c6c85d7f1351b0126661487a7e0a14a50f1675ec50eb34d4f20ef21 + # via google-auth +secretstorage==3.3.3 \ + --hash=sha256:2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77 \ + --hash=sha256:7ef3a3c14fd6975684be05cf30cb13cc17936814b3bd02664b6ab8378aaf0c5b + # via keyring +urllib3==2.2.2 \ + --hash=sha256:a448b2f64d686155468037e1ace9f2d2199776e17f0a46610480d311f73e3472 \ + --hash=sha256:dd505485549a7a552833da5e6063639d0d177c04f23bc3864e41e5dc5f612168 + # via requests +zipp==3.19.2 \ + --hash=sha256:bf1dcf6450f873a13e952a29504887c89e6de7506209e5b1bcc3460135d4de19 \ + --hash=sha256:f091755f667055f2d02b32c53771a7a6c8b47e1fdbc4b72a8b9072b3eef8015c + # via importlib-metadata diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f41cb3e7650..83fb8b34b0f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,201 +2,201 @@ Please refer to each API's `CHANGELOG.md` file under the `packages/` directory Changelogs ----- -- [google-ads-admanager==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ads-admanager/CHANGELOG.md) -- [google-ai-generativelanguage==0.6.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/CHANGELOG.md) -- [google-analytics-admin==0.22.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin/CHANGELOG.md) -- [google-analytics-data==0.18.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-data/CHANGELOG.md) -- [google-apps-card==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card/CHANGELOG.md) -- [google-apps-chat==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat/CHANGELOG.md) -- [google-apps-events-subscriptions==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-events-subscriptions/CHANGELOG.md) -- [google-apps-meet==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-meet/CHANGELOG.md) -- [google-apps-script-type==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-script-type/CHANGELOG.md) -- [google-area120-tables==0.11.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-area120-tables/CHANGELOG.md) -- [google-cloud-access-approval==1.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-approval/CHANGELOG.md) -- [google-cloud-advisorynotifications==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-advisorynotifications/CHANGELOG.md) -- [google-cloud-alloydb-connectors==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb-connectors/CHANGELOG.md) -- [google-cloud-alloydb==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb/CHANGELOG.md) -- [google-cloud-api-gateway==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-gateway/CHANGELOG.md) -- [google-cloud-api-keys==0.5.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-keys/CHANGELOG.md) -- [google-cloud-apigee-connect==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-connect/CHANGELOG.md) -- [google-cloud-apigee-registry==0.6.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-registry/CHANGELOG.md) -- [google-cloud-appengine-admin==1.11.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-admin/CHANGELOG.md) -- [google-cloud-appengine-logging==1.4.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-logging/CHANGELOG.md) -- [google-cloud-apphub==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apphub/CHANGELOG.md) -- [google-cloud-artifact-registry==1.11.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-artifact-registry/CHANGELOG.md) -- [google-cloud-asset==3.26.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset/CHANGELOG.md) -- [google-cloud-assured-workloads==1.12.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-assured-workloads/CHANGELOG.md) -- [google-cloud-automl==2.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-automl/CHANGELOG.md) -- [google-cloud-backupdr==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-backupdr/CHANGELOG.md) -- [google-cloud-bare-metal-solution==1.7.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bare-metal-solution/CHANGELOG.md) -- [google-cloud-batch==0.17.22](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-batch/CHANGELOG.md) -- [google-cloud-beyondcorp-appconnections==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md) -- [google-cloud-beyondcorp-appconnectors==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md) -- [google-cloud-beyondcorp-appgateways==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md) -- [google-cloud-beyondcorp-clientconnectorservices==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md) -- [google-cloud-beyondcorp-clientgateways==0.4.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md) -- [google-cloud-bigquery-analyticshub==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md) -- [google-cloud-bigquery-biglake==0.4.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-biglake/CHANGELOG.md) -- [google-cloud-bigquery-connection==1.15.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-connection/CHANGELOG.md) -- [google-cloud-bigquery-data-exchange==0.5.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md) -- [google-cloud-bigquery-datapolicies==0.6.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md) -- [google-cloud-bigquery-datatransfer==3.15.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md) -- [google-cloud-bigquery-logging==1.4.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-logging/CHANGELOG.md) -- [google-cloud-bigquery-migration==0.11.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-migration/CHANGELOG.md) -- [google-cloud-bigquery-reservation==1.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-reservation/CHANGELOG.md) -- [google-cloud-billing-budgets==1.14.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing-budgets/CHANGELOG.md) -- [google-cloud-billing==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing/CHANGELOG.md) -- [google-cloud-binary-authorization==1.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization/CHANGELOG.md) -- [google-cloud-build==3.24.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-build/CHANGELOG.md) -- [google-cloud-certificate-manager==1.7.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-certificate-manager/CHANGELOG.md) -- [google-cloud-channel==1.18.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-channel/CHANGELOG.md) -- [google-cloud-cloudcontrolspartner==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md) -- [google-cloud-cloudquotas==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudquotas/CHANGELOG.md) -- [google-cloud-commerce-consumer-procurement==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md) -- [google-cloud-common==1.3.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-common/CHANGELOG.md) -- [google-cloud-compute==1.19.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-compute/CHANGELOG.md) -- [google-cloud-confidentialcomputing==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-confidentialcomputing/CHANGELOG.md) -- [google-cloud-config==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config/CHANGELOG.md) -- [google-cloud-contact-center-insights==1.17.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contact-center-insights/CHANGELOG.md) -- [google-cloud-container==2.49.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-container/CHANGELOG.md) -- [google-cloud-containeranalysis==2.14.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-containeranalysis/CHANGELOG.md) -- [google-cloud-contentwarehouse==0.7.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contentwarehouse/CHANGELOG.md) -- [google-cloud-data-fusion==1.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-fusion/CHANGELOG.md) -- [google-cloud-data-qna==0.10.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-qna/CHANGELOG.md) -- [google-cloud-datacatalog-lineage==0.3.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog-lineage/CHANGELOG.md) -- [google-cloud-datacatalog==3.19.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog/CHANGELOG.md) -- [google-cloud-dataflow-client==0.8.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataflow-client/CHANGELOG.md) -- [google-cloud-dataform==0.5.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataform/CHANGELOG.md) -- [google-cloud-datalabeling==1.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datalabeling/CHANGELOG.md) -- [google-cloud-dataplex==2.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataplex/CHANGELOG.md) -- [google-cloud-dataproc-metastore==1.15.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc-metastore/CHANGELOG.md) -- [google-cloud-dataproc==5.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc/CHANGELOG.md) -- [google-cloud-datastream==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datastream/CHANGELOG.md) -- [google-cloud-deploy==1.19.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-deploy/CHANGELOG.md) -- [google-cloud-developerconnect==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-developerconnect/CHANGELOG.md) -- [google-cloud-dialogflow-cx==1.34.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow-cx/CHANGELOG.md) -- [google-cloud-dialogflow==2.30.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow/CHANGELOG.md) -- [google-cloud-discoveryengine==0.11.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-discoveryengine/CHANGELOG.md) -- [google-cloud-dlp==3.18.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dlp/CHANGELOG.md) -- [google-cloud-dms==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dms/CHANGELOG.md) -- [google-cloud-documentai==2.29.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-documentai/CHANGELOG.md) -- [google-cloud-domains==1.7.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-domains/CHANGELOG.md) -- [google-cloud-edgecontainer==0.5.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer/CHANGELOG.md) -- [google-cloud-edgenetwork==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgenetwork/CHANGELOG.md) -- [google-cloud-enterpriseknowledgegraph==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md) -- [google-cloud-essential-contacts==1.7.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-essential-contacts/CHANGELOG.md) -- [google-cloud-eventarc-publishing==0.6.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc-publishing/CHANGELOG.md) -- [google-cloud-eventarc==1.11.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc/CHANGELOG.md) -- [google-cloud-filestore==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-filestore/CHANGELOG.md) -- [google-cloud-functions==1.16.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions/CHANGELOG.md) -- [google-cloud-gdchardwaremanagement==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gdchardwaremanagement/CHANGELOG.md) -- [google-cloud-gke-backup==0.5.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-backup/CHANGELOG.md) -- [google-cloud-gke-connect-gateway==0.8.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-connect-gateway/CHANGELOG.md) -- [google-cloud-gke-hub==1.14.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-hub/CHANGELOG.md) -- [google-cloud-gke-multicloud==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud/CHANGELOG.md) -- [google-cloud-gsuiteaddons==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gsuiteaddons/CHANGELOG.md) -- [google-cloud-iam-logging==1.3.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam-logging/CHANGELOG.md) -- [google-cloud-iam==2.15.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam/CHANGELOG.md) -- [google-cloud-iap==1.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iap/CHANGELOG.md) -- [google-cloud-ids==1.7.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ids/CHANGELOG.md) -- [google-cloud-kms-inventory==0.2.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms-inventory/CHANGELOG.md) -- [google-cloud-kms==2.24.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms/CHANGELOG.md) -- [google-cloud-language==2.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language/CHANGELOG.md) -- [google-cloud-life-sciences==0.9.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-life-sciences/CHANGELOG.md) -- [google-cloud-managed-identities==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managed-identities/CHANGELOG.md) -- [google-cloud-managedkafka==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managedkafka/CHANGELOG.md) -- [google-cloud-media-translation==0.11.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-media-translation/CHANGELOG.md) -- [google-cloud-memcache==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-memcache/CHANGELOG.md) -- [google-cloud-migrationcenter==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-migrationcenter/CHANGELOG.md) -- [google-cloud-monitoring-dashboards==2.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-dashboards/CHANGELOG.md) -- [google-cloud-monitoring-metrics-scopes==1.6.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md) -- [google-cloud-monitoring==2.22.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring/CHANGELOG.md) -- [google-cloud-netapp==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-netapp/CHANGELOG.md) -- [google-cloud-network-connectivity==2.4.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-connectivity/CHANGELOG.md) -- [google-cloud-network-management==1.17.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management/CHANGELOG.md) -- [google-cloud-network-security==0.9.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security/CHANGELOG.md) -- [google-cloud-network-services==0.5.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services/CHANGELOG.md) -- [google-cloud-notebooks==1.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-notebooks/CHANGELOG.md) -- [google-cloud-optimization==1.8.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-optimization/CHANGELOG.md) -- [google-cloud-orchestration-airflow==1.13.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-orchestration-airflow/CHANGELOG.md) -- [google-cloud-os-config==1.17.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-config/CHANGELOG.md) -- [google-cloud-os-login==2.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login/CHANGELOG.md) -- [google-cloud-parallelstore==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore/CHANGELOG.md) -- [google-cloud-phishing-protection==1.11.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection/CHANGELOG.md) -- [google-cloud-policy-troubleshooter==1.11.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter/CHANGELOG.md) -- [google-cloud-policysimulator==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator/CHANGELOG.md) -- [google-cloud-policytroubleshooter-iam==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md) -- [google-cloud-private-ca==1.12.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca/CHANGELOG.md) -- [google-cloud-private-catalog==0.9.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog/CHANGELOG.md) -- [google-cloud-privilegedaccessmanager==0.1.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-privilegedaccessmanager/CHANGELOG.md) -- [google-cloud-public-ca==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-public-ca/CHANGELOG.md) -- [google-cloud-rapidmigrationassessment==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md) -- [google-cloud-recaptcha-enterprise==1.21.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md) -- [google-cloud-recommendations-ai==0.10.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai/CHANGELOG.md) -- [google-cloud-recommender==2.15.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender/CHANGELOG.md) -- [google-cloud-redis-cluster==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster/CHANGELOG.md) -- [google-cloud-redis==2.15.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis/CHANGELOG.md) -- [google-cloud-resource-manager==1.12.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager/CHANGELOG.md) -- [google-cloud-resource-settings==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings/CHANGELOG.md) -- [google-cloud-retail==1.21.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail/CHANGELOG.md) -- [google-cloud-run==0.10.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run/CHANGELOG.md) -- [google-cloud-scheduler==2.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-scheduler/CHANGELOG.md) -- [google-cloud-secret-manager==2.20.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-secret-manager/CHANGELOG.md) -- [google-cloud-securesourcemanager==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securesourcemanager/CHANGELOG.md) -- [google-cloud-securitycenter==1.33.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter/CHANGELOG.md) -- [google-cloud-securitycentermanagement==0.1.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycentermanagement/CHANGELOG.md) -- [google-cloud-service-control==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-control/CHANGELOG.md) -- [google-cloud-service-directory==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-directory/CHANGELOG.md) -- [google-cloud-service-management==1.8.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management/CHANGELOG.md) -- [google-cloud-service-usage==1.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-usage/CHANGELOG.md) -- [google-cloud-servicehealth==0.1.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-servicehealth/CHANGELOG.md) -- [google-cloud-shell==1.9.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-shell/CHANGELOG.md) -- [google-cloud-source-context==1.5.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-source-context/CHANGELOG.md) -- [google-cloud-speech==2.26.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-speech/CHANGELOG.md) -- [google-cloud-storage-control==1.0.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-control/CHANGELOG.md) -- [google-cloud-storage-transfer==1.11.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer/CHANGELOG.md) -- [google-cloud-storageinsights==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/CHANGELOG.md) -- [google-cloud-support==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-support/CHANGELOG.md) -- [google-cloud-talent==2.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-talent/CHANGELOG.md) -- [google-cloud-tasks==2.16.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tasks/CHANGELOG.md) -- [google-cloud-telcoautomation==0.2.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-telcoautomation/CHANGELOG.md) -- [google-cloud-texttospeech==2.16.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/CHANGELOG.md) -- [google-cloud-tpu==1.18.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tpu/CHANGELOG.md) -- [google-cloud-trace==1.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-trace/CHANGELOG.md) -- [google-cloud-translate==3.15.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-translate/CHANGELOG.md) -- [google-cloud-video-live-stream==1.8.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-live-stream/CHANGELOG.md) -- [google-cloud-video-stitcher==0.7.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-stitcher/CHANGELOG.md) -- [google-cloud-video-transcoder==1.12.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-transcoder/CHANGELOG.md) -- [google-cloud-videointelligence==2.13.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-videointelligence/CHANGELOG.md) -- [google-cloud-vision==3.7.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision/CHANGELOG.md) -- [google-cloud-visionai==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-visionai/CHANGELOG.md) -- [google-cloud-vm-migration==1.8.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vm-migration/CHANGELOG.md) -- [google-cloud-vmwareengine==1.4.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vmwareengine/CHANGELOG.md) -- [google-cloud-vpc-access==1.10.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vpc-access/CHANGELOG.md) -- [google-cloud-webrisk==1.14.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-webrisk/CHANGELOG.md) -- [google-cloud-websecurityscanner==1.14.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-websecurityscanner/CHANGELOG.md) -- [google-cloud-workflows==1.14.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workflows/CHANGELOG.md) -- [google-cloud-workstations==0.5.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/CHANGELOG.md) -- [google-geo-type==0.3.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-geo-type/CHANGELOG.md) -- [google-maps-addressvalidation==0.3.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md) -- [google-maps-fleetengine-delivery==0.2.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery/CHANGELOG.md) -- [google-maps-fleetengine==0.2.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine/CHANGELOG.md) -- [google-maps-mapsplatformdatasets==0.4.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets/CHANGELOG.md) -- [google-maps-places==0.1.16](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places/CHANGELOG.md) -- [google-maps-routeoptimization==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization/CHANGELOG.md) -- [google-maps-routing==0.6.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing/CHANGELOG.md) -- [google-maps-solar==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-solar/CHANGELOG.md) -- [google-shopping-css==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-css/CHANGELOG.md) -- [google-shopping-merchant-accounts==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-accounts/CHANGELOG.md) -- [google-shopping-merchant-conversions==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-conversions/CHANGELOG.md) -- [google-shopping-merchant-datasources==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-datasources/CHANGELOG.md) -- [google-shopping-merchant-inventories==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories/CHANGELOG.md) -- [google-shopping-merchant-lfp==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-lfp/CHANGELOG.md) -- [google-shopping-merchant-notifications==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-notifications/CHANGELOG.md) -- [google-shopping-merchant-products==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-products/CHANGELOG.md) -- [google-shopping-merchant-promotions==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-promotions/CHANGELOG.md) -- [google-shopping-merchant-quota==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-quota/CHANGELOG.md) -- [google-shopping-merchant-reports==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports/CHANGELOG.md) -- [google-shopping-type==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-type/CHANGELOG.md) -- [grafeas==1.10.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas/CHANGELOG.md) +- [google-ads-admanager==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ads-admanager/CHANGELOG.md) +- [google-ai-generativelanguage==0.6.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/CHANGELOG.md) +- [google-analytics-admin==0.22.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin/CHANGELOG.md) +- [google-analytics-data==0.18.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-data/CHANGELOG.md) +- [google-apps-card==0.1.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-card/CHANGELOG.md) +- [google-apps-chat==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-chat/CHANGELOG.md) +- [google-apps-events-subscriptions==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-events-subscriptions/CHANGELOG.md) +- [google-apps-meet==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-meet/CHANGELOG.md) +- [google-apps-script-type==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-apps-script-type/CHANGELOG.md) +- [google-area120-tables==0.11.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-area120-tables/CHANGELOG.md) +- [google-cloud-access-approval==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-access-approval/CHANGELOG.md) +- [google-cloud-advisorynotifications==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-advisorynotifications/CHANGELOG.md) +- [google-cloud-alloydb-connectors==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb-connectors/CHANGELOG.md) +- [google-cloud-alloydb==0.3.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-alloydb/CHANGELOG.md) +- [google-cloud-api-gateway==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-gateway/CHANGELOG.md) +- [google-cloud-api-keys==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-api-keys/CHANGELOG.md) +- [google-cloud-apigee-connect==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-connect/CHANGELOG.md) +- [google-cloud-apigee-registry==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apigee-registry/CHANGELOG.md) +- [google-cloud-appengine-admin==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-admin/CHANGELOG.md) +- [google-cloud-appengine-logging==1.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-appengine-logging/CHANGELOG.md) +- [google-cloud-apphub==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-apphub/CHANGELOG.md) +- [google-cloud-artifact-registry==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-artifact-registry/CHANGELOG.md) +- [google-cloud-asset==3.26.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-asset/CHANGELOG.md) +- [google-cloud-assured-workloads==1.12.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-assured-workloads/CHANGELOG.md) +- [google-cloud-automl==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-automl/CHANGELOG.md) +- [google-cloud-backupdr==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-backupdr/CHANGELOG.md) +- [google-cloud-bare-metal-solution==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bare-metal-solution/CHANGELOG.md) +- [google-cloud-batch==0.17.23](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-batch/CHANGELOG.md) +- [google-cloud-beyondcorp-appconnections==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnections/CHANGELOG.md) +- [google-cloud-beyondcorp-appconnectors==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appconnectors/CHANGELOG.md) +- [google-cloud-beyondcorp-appgateways==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-appgateways/CHANGELOG.md) +- [google-cloud-beyondcorp-clientconnectorservices==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientconnectorservices/CHANGELOG.md) +- [google-cloud-beyondcorp-clientgateways==0.4.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-beyondcorp-clientgateways/CHANGELOG.md) +- [google-cloud-bigquery-analyticshub==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-analyticshub/CHANGELOG.md) +- [google-cloud-bigquery-biglake==0.4.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-biglake/CHANGELOG.md) +- [google-cloud-bigquery-connection==1.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-connection/CHANGELOG.md) +- [google-cloud-bigquery-data-exchange==0.5.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-data-exchange/CHANGELOG.md) +- [google-cloud-bigquery-datapolicies==0.6.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datapolicies/CHANGELOG.md) +- [google-cloud-bigquery-datatransfer==3.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-datatransfer/CHANGELOG.md) +- [google-cloud-bigquery-logging==1.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-logging/CHANGELOG.md) +- [google-cloud-bigquery-migration==0.11.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-migration/CHANGELOG.md) +- [google-cloud-bigquery-reservation==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-bigquery-reservation/CHANGELOG.md) +- [google-cloud-billing-budgets==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing-budgets/CHANGELOG.md) +- [google-cloud-billing==1.13.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-billing/CHANGELOG.md) +- [google-cloud-binary-authorization==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization/CHANGELOG.md) +- [google-cloud-build==3.24.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-build/CHANGELOG.md) +- [google-cloud-certificate-manager==1.7.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-certificate-manager/CHANGELOG.md) +- [google-cloud-channel==1.18.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-channel/CHANGELOG.md) +- [google-cloud-cloudcontrolspartner==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudcontrolspartner/CHANGELOG.md) +- [google-cloud-cloudquotas==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-cloudquotas/CHANGELOG.md) +- [google-cloud-commerce-consumer-procurement==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-commerce-consumer-procurement/CHANGELOG.md) +- [google-cloud-common==1.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-common/CHANGELOG.md) +- [google-cloud-compute==1.19.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-compute/CHANGELOG.md) +- [google-cloud-confidentialcomputing==0.4.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-confidentialcomputing/CHANGELOG.md) +- [google-cloud-config==0.1.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config/CHANGELOG.md) +- [google-cloud-contact-center-insights==1.17.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contact-center-insights/CHANGELOG.md) +- [google-cloud-container==2.50.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-container/CHANGELOG.md) +- [google-cloud-containeranalysis==2.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-containeranalysis/CHANGELOG.md) +- [google-cloud-contentwarehouse==0.7.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-contentwarehouse/CHANGELOG.md) +- [google-cloud-data-fusion==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-fusion/CHANGELOG.md) +- [google-cloud-data-qna==0.10.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-data-qna/CHANGELOG.md) +- [google-cloud-datacatalog-lineage==0.3.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog-lineage/CHANGELOG.md) +- [google-cloud-datacatalog==3.20.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datacatalog/CHANGELOG.md) +- [google-cloud-dataflow-client==0.8.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataflow-client/CHANGELOG.md) +- [google-cloud-dataform==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataform/CHANGELOG.md) +- [google-cloud-datalabeling==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datalabeling/CHANGELOG.md) +- [google-cloud-dataplex==2.2.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataplex/CHANGELOG.md) +- [google-cloud-dataproc-metastore==1.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc-metastore/CHANGELOG.md) +- [google-cloud-dataproc==5.10.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dataproc/CHANGELOG.md) +- [google-cloud-datastream==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-datastream/CHANGELOG.md) +- [google-cloud-deploy==2.0.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-deploy/CHANGELOG.md) +- [google-cloud-developerconnect==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-developerconnect/CHANGELOG.md) +- [google-cloud-dialogflow-cx==1.35.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow-cx/CHANGELOG.md) +- [google-cloud-dialogflow==2.30.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dialogflow/CHANGELOG.md) +- [google-cloud-discoveryengine==0.12.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-discoveryengine/CHANGELOG.md) +- [google-cloud-dlp==3.20.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dlp/CHANGELOG.md) +- [google-cloud-dms==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-dms/CHANGELOG.md) +- [google-cloud-documentai==2.30.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-documentai/CHANGELOG.md) +- [google-cloud-domains==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-domains/CHANGELOG.md) +- [google-cloud-edgecontainer==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer/CHANGELOG.md) +- [google-cloud-edgenetwork==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgenetwork/CHANGELOG.md) +- [google-cloud-enterpriseknowledgegraph==0.3.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-enterpriseknowledgegraph/CHANGELOG.md) +- [google-cloud-essential-contacts==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-essential-contacts/CHANGELOG.md) +- [google-cloud-eventarc-publishing==0.6.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc-publishing/CHANGELOG.md) +- [google-cloud-eventarc==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-eventarc/CHANGELOG.md) +- [google-cloud-filestore==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-filestore/CHANGELOG.md) +- [google-cloud-functions==1.16.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-functions/CHANGELOG.md) +- [google-cloud-gdchardwaremanagement==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gdchardwaremanagement/CHANGELOG.md) +- [google-cloud-gke-backup==0.5.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-backup/CHANGELOG.md) +- [google-cloud-gke-connect-gateway==0.8.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-connect-gateway/CHANGELOG.md) +- [google-cloud-gke-hub==1.14.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-hub/CHANGELOG.md) +- [google-cloud-gke-multicloud==0.6.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gke-multicloud/CHANGELOG.md) +- [google-cloud-gsuiteaddons==0.3.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-gsuiteaddons/CHANGELOG.md) +- [google-cloud-iam-logging==1.3.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam-logging/CHANGELOG.md) +- [google-cloud-iam==2.15.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam/CHANGELOG.md) +- [google-cloud-iap==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iap/CHANGELOG.md) +- [google-cloud-ids==1.7.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ids/CHANGELOG.md) +- [google-cloud-kms-inventory==0.2.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms-inventory/CHANGELOG.md) +- [google-cloud-kms==2.24.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms/CHANGELOG.md) +- [google-cloud-language==2.14.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-language/CHANGELOG.md) +- [google-cloud-life-sciences==0.9.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-life-sciences/CHANGELOG.md) +- [google-cloud-managed-identities==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managed-identities/CHANGELOG.md) +- [google-cloud-managedkafka==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-managedkafka/CHANGELOG.md) +- [google-cloud-media-translation==0.11.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-media-translation/CHANGELOG.md) +- [google-cloud-memcache==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-memcache/CHANGELOG.md) +- [google-cloud-migrationcenter==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-migrationcenter/CHANGELOG.md) +- [google-cloud-monitoring-dashboards==2.15.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-dashboards/CHANGELOG.md) +- [google-cloud-monitoring-metrics-scopes==1.6.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring-metrics-scopes/CHANGELOG.md) +- [google-cloud-monitoring==2.22.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring/CHANGELOG.md) +- [google-cloud-netapp==0.3.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-netapp/CHANGELOG.md) +- [google-cloud-network-connectivity==2.4.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-connectivity/CHANGELOG.md) +- [google-cloud-network-management==1.17.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-management/CHANGELOG.md) +- [google-cloud-network-security==0.9.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-security/CHANGELOG.md) +- [google-cloud-network-services==0.5.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-network-services/CHANGELOG.md) +- [google-cloud-notebooks==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-notebooks/CHANGELOG.md) +- [google-cloud-optimization==1.8.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-optimization/CHANGELOG.md) +- [google-cloud-orchestration-airflow==1.13.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-orchestration-airflow/CHANGELOG.md) +- [google-cloud-os-config==1.17.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-config/CHANGELOG.md) +- [google-cloud-os-login==2.14.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-os-login/CHANGELOG.md) +- [google-cloud-parallelstore==0.2.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-parallelstore/CHANGELOG.md) +- [google-cloud-phishing-protection==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-phishing-protection/CHANGELOG.md) +- [google-cloud-policy-troubleshooter==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policy-troubleshooter/CHANGELOG.md) +- [google-cloud-policysimulator==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policysimulator/CHANGELOG.md) +- [google-cloud-policytroubleshooter-iam==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-policytroubleshooter-iam/CHANGELOG.md) +- [google-cloud-private-ca==1.12.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-ca/CHANGELOG.md) +- [google-cloud-private-catalog==0.9.11](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-private-catalog/CHANGELOG.md) +- [google-cloud-privilegedaccessmanager==0.1.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-privilegedaccessmanager/CHANGELOG.md) +- [google-cloud-public-ca==0.3.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-public-ca/CHANGELOG.md) +- [google-cloud-rapidmigrationassessment==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-rapidmigrationassessment/CHANGELOG.md) +- [google-cloud-recaptcha-enterprise==1.21.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recaptcha-enterprise/CHANGELOG.md) +- [google-cloud-recommendations-ai==0.10.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommendations-ai/CHANGELOG.md) +- [google-cloud-recommender==2.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-recommender/CHANGELOG.md) +- [google-cloud-redis-cluster==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis-cluster/CHANGELOG.md) +- [google-cloud-redis==2.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-redis/CHANGELOG.md) +- [google-cloud-resource-manager==1.12.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-manager/CHANGELOG.md) +- [google-cloud-resource-settings==1.9.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-resource-settings/CHANGELOG.md) +- [google-cloud-retail==1.21.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-retail/CHANGELOG.md) +- [google-cloud-run==0.10.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-run/CHANGELOG.md) +- [google-cloud-scheduler==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-scheduler/CHANGELOG.md) +- [google-cloud-secret-manager==2.20.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-secret-manager/CHANGELOG.md) +- [google-cloud-securesourcemanager==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securesourcemanager/CHANGELOG.md) +- [google-cloud-securitycenter==1.33.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycenter/CHANGELOG.md) +- [google-cloud-securitycentermanagement==0.1.14](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-securitycentermanagement/CHANGELOG.md) +- [google-cloud-service-control==1.12.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-control/CHANGELOG.md) +- [google-cloud-service-directory==1.11.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-directory/CHANGELOG.md) +- [google-cloud-service-management==1.8.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management/CHANGELOG.md) +- [google-cloud-service-usage==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-usage/CHANGELOG.md) +- [google-cloud-servicehealth==0.1.6](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-servicehealth/CHANGELOG.md) +- [google-cloud-shell==1.9.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-shell/CHANGELOG.md) +- [google-cloud-source-context==1.5.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-source-context/CHANGELOG.md) +- [google-cloud-speech==2.27.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-speech/CHANGELOG.md) +- [google-cloud-storage-control==1.0.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-control/CHANGELOG.md) +- [google-cloud-storage-transfer==1.11.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storage-transfer/CHANGELOG.md) +- [google-cloud-storageinsights==0.1.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-storageinsights/CHANGELOG.md) +- [google-cloud-support==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-support/CHANGELOG.md) +- [google-cloud-talent==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-talent/CHANGELOG.md) +- [google-cloud-tasks==2.16.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tasks/CHANGELOG.md) +- [google-cloud-telcoautomation==0.2.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-telcoautomation/CHANGELOG.md) +- [google-cloud-texttospeech==2.16.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/CHANGELOG.md) +- [google-cloud-tpu==1.18.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-tpu/CHANGELOG.md) +- [google-cloud-trace==1.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-trace/CHANGELOG.md) +- [google-cloud-translate==3.15.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-translate/CHANGELOG.md) +- [google-cloud-video-live-stream==1.8.1](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-live-stream/CHANGELOG.md) +- [google-cloud-video-stitcher==0.7.12](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-stitcher/CHANGELOG.md) +- [google-cloud-video-transcoder==1.12.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-video-transcoder/CHANGELOG.md) +- [google-cloud-videointelligence==2.13.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-videointelligence/CHANGELOG.md) +- [google-cloud-vision==3.7.4](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vision/CHANGELOG.md) +- [google-cloud-visionai==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-visionai/CHANGELOG.md) +- [google-cloud-vm-migration==1.8.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vm-migration/CHANGELOG.md) +- [google-cloud-vmwareengine==1.5.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vmwareengine/CHANGELOG.md) +- [google-cloud-vpc-access==1.10.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-vpc-access/CHANGELOG.md) +- [google-cloud-webrisk==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-webrisk/CHANGELOG.md) +- [google-cloud-websecurityscanner==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-websecurityscanner/CHANGELOG.md) +- [google-cloud-workflows==1.14.5](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workflows/CHANGELOG.md) +- [google-cloud-workstations==0.5.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-workstations/CHANGELOG.md) +- [google-geo-type==0.3.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-geo-type/CHANGELOG.md) +- [google-maps-addressvalidation==0.3.13](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md) +- [google-maps-fleetengine-delivery==0.2.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine-delivery/CHANGELOG.md) +- [google-maps-fleetengine==0.2.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-fleetengine/CHANGELOG.md) +- [google-maps-mapsplatformdatasets==0.4.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-mapsplatformdatasets/CHANGELOG.md) +- [google-maps-places==0.1.17](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-places/CHANGELOG.md) +- [google-maps-routeoptimization==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization/CHANGELOG.md) +- [google-maps-routing==0.6.10](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routing/CHANGELOG.md) +- [google-maps-solar==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-solar/CHANGELOG.md) +- [google-shopping-css==0.1.7](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-css/CHANGELOG.md) +- [google-shopping-merchant-accounts==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-accounts/CHANGELOG.md) +- [google-shopping-merchant-conversions==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-conversions/CHANGELOG.md) +- [google-shopping-merchant-datasources==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-datasources/CHANGELOG.md) +- [google-shopping-merchant-inventories==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-inventories/CHANGELOG.md) +- [google-shopping-merchant-lfp==0.1.3](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-lfp/CHANGELOG.md) +- [google-shopping-merchant-notifications==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-notifications/CHANGELOG.md) +- [google-shopping-merchant-products==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-products/CHANGELOG.md) +- [google-shopping-merchant-promotions==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-promotions/CHANGELOG.md) +- [google-shopping-merchant-quota==0.1.2](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-quota/CHANGELOG.md) +- [google-shopping-merchant-reports==0.1.9](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-merchant-reports/CHANGELOG.md) +- [google-shopping-type==0.1.8](https://github.com/googleapis/google-cloud-python/tree/main/packages/google-shopping-type/CHANGELOG.md) +- [grafeas==1.11.0](https://github.com/googleapis/google-cloud-python/tree/main/packages/grafeas/CHANGELOG.md) diff --git a/packages/google-analytics-admin/google/analytics/admin/__init__.py b/packages/google-analytics-admin/google/analytics/admin/__init__.py index 59a76ba72c0d..9bb3ffa15f32 100644 --- a/packages/google-analytics-admin/google/analytics/admin/__init__.py +++ b/packages/google-analytics-admin/google/analytics/admin/__init__.py @@ -64,6 +64,7 @@ CreateAccessBindingRequest, CreateAdSenseLinkRequest, CreateAudienceRequest, + CreateBigQueryLinkRequest, CreateCalculatedMetricRequest, CreateChannelGroupRequest, CreateConnectedSiteTagRequest, @@ -75,9 +76,11 @@ CreateDisplayVideo360AdvertiserLinkProposalRequest, CreateDisplayVideo360AdvertiserLinkRequest, CreateEventCreateRuleRequest, + CreateEventEditRuleRequest, CreateExpandedDataSetRequest, CreateFirebaseLinkRequest, CreateGoogleAdsLinkRequest, + CreateKeyEventRequest, CreateMeasurementProtocolSecretRequest, CreatePropertyRequest, CreateRollupPropertyRequest, @@ -86,11 +89,10 @@ CreateSearchAds360LinkRequest, CreateSKAdNetworkConversionValueSchemaRequest, CreateSubpropertyEventFilterRequest, - CreateSubpropertyRequest, - CreateSubpropertyResponse, DeleteAccessBindingRequest, DeleteAccountRequest, DeleteAdSenseLinkRequest, + DeleteBigQueryLinkRequest, DeleteCalculatedMetricRequest, DeleteChannelGroupRequest, DeleteConnectedSiteTagRequest, @@ -99,9 +101,11 @@ DeleteDisplayVideo360AdvertiserLinkProposalRequest, DeleteDisplayVideo360AdvertiserLinkRequest, DeleteEventCreateRuleRequest, + DeleteEventEditRuleRequest, DeleteExpandedDataSetRequest, DeleteFirebaseLinkRequest, DeleteGoogleAdsLinkRequest, + DeleteKeyEventRequest, DeleteMeasurementProtocolSecretRequest, DeletePropertyRequest, DeleteRollupPropertySourceLinkRequest, @@ -131,9 +135,11 @@ GetDisplayVideo360AdvertiserLinkRequest, GetEnhancedMeasurementSettingsRequest, GetEventCreateRuleRequest, + GetEventEditRuleRequest, GetExpandedDataSetRequest, GetGlobalSiteTagRequest, GetGoogleSignalsSettingsRequest, + GetKeyEventRequest, GetMeasurementProtocolSecretRequest, GetPropertyRequest, GetRollupPropertySourceLinkRequest, @@ -172,12 +178,16 @@ ListDisplayVideo360AdvertiserLinksResponse, ListEventCreateRulesRequest, ListEventCreateRulesResponse, + ListEventEditRulesRequest, + ListEventEditRulesResponse, ListExpandedDataSetsRequest, ListExpandedDataSetsResponse, ListFirebaseLinksRequest, ListFirebaseLinksResponse, ListGoogleAdsLinksRequest, ListGoogleAdsLinksResponse, + ListKeyEventsRequest, + ListKeyEventsResponse, ListMeasurementProtocolSecretsRequest, ListMeasurementProtocolSecretsResponse, ListPropertiesRequest, @@ -192,6 +202,9 @@ ListSubpropertyEventFiltersResponse, ProvisionAccountTicketRequest, ProvisionAccountTicketResponse, + ProvisionSubpropertyRequest, + ProvisionSubpropertyResponse, + ReorderEventEditRulesRequest, RunAccessReportRequest, RunAccessReportResponse, SearchChangeHistoryEventsRequest, @@ -202,6 +215,7 @@ UpdateAccountRequest, UpdateAttributionSettingsRequest, UpdateAudienceRequest, + UpdateBigQueryLinkRequest, UpdateCalculatedMetricRequest, UpdateChannelGroupRequest, UpdateConversionEventRequest, @@ -213,9 +227,11 @@ UpdateDisplayVideo360AdvertiserLinkRequest, UpdateEnhancedMeasurementSettingsRequest, UpdateEventCreateRuleRequest, + UpdateEventEditRuleRequest, UpdateExpandedDataSetRequest, UpdateGoogleAdsLinkRequest, UpdateGoogleSignalsSettingsRequest, + UpdateKeyEventRequest, UpdateMeasurementProtocolSecretRequest, UpdatePropertyRequest, UpdateSearchAds360LinkRequest, @@ -243,6 +259,7 @@ ) from google.analytics.admin_v1alpha.types.event_create_and_edit import ( EventCreateRule, + EventEditRule, MatchingCondition, ParameterMutation, ) @@ -286,6 +303,7 @@ GoogleSignalsSettings, GoogleSignalsState, IndustryCategory, + KeyEvent, LinkProposalInitiatingProduct, LinkProposalState, LinkProposalStatusDetails, @@ -347,6 +365,7 @@ "CreateAccessBindingRequest", "CreateAdSenseLinkRequest", "CreateAudienceRequest", + "CreateBigQueryLinkRequest", "CreateCalculatedMetricRequest", "CreateChannelGroupRequest", "CreateConnectedSiteTagRequest", @@ -358,9 +377,11 @@ "CreateDisplayVideo360AdvertiserLinkProposalRequest", "CreateDisplayVideo360AdvertiserLinkRequest", "CreateEventCreateRuleRequest", + "CreateEventEditRuleRequest", "CreateExpandedDataSetRequest", "CreateFirebaseLinkRequest", "CreateGoogleAdsLinkRequest", + "CreateKeyEventRequest", "CreateMeasurementProtocolSecretRequest", "CreatePropertyRequest", "CreateRollupPropertyRequest", @@ -369,11 +390,10 @@ "CreateSearchAds360LinkRequest", "CreateSKAdNetworkConversionValueSchemaRequest", "CreateSubpropertyEventFilterRequest", - "CreateSubpropertyRequest", - "CreateSubpropertyResponse", "DeleteAccessBindingRequest", "DeleteAccountRequest", "DeleteAdSenseLinkRequest", + "DeleteBigQueryLinkRequest", "DeleteCalculatedMetricRequest", "DeleteChannelGroupRequest", "DeleteConnectedSiteTagRequest", @@ -382,9 +402,11 @@ "DeleteDisplayVideo360AdvertiserLinkProposalRequest", "DeleteDisplayVideo360AdvertiserLinkRequest", "DeleteEventCreateRuleRequest", + "DeleteEventEditRuleRequest", "DeleteExpandedDataSetRequest", "DeleteFirebaseLinkRequest", "DeleteGoogleAdsLinkRequest", + "DeleteKeyEventRequest", "DeleteMeasurementProtocolSecretRequest", "DeletePropertyRequest", "DeleteRollupPropertySourceLinkRequest", @@ -414,9 +436,11 @@ "GetDisplayVideo360AdvertiserLinkRequest", "GetEnhancedMeasurementSettingsRequest", "GetEventCreateRuleRequest", + "GetEventEditRuleRequest", "GetExpandedDataSetRequest", "GetGlobalSiteTagRequest", "GetGoogleSignalsSettingsRequest", + "GetKeyEventRequest", "GetMeasurementProtocolSecretRequest", "GetPropertyRequest", "GetRollupPropertySourceLinkRequest", @@ -455,12 +479,16 @@ "ListDisplayVideo360AdvertiserLinksResponse", "ListEventCreateRulesRequest", "ListEventCreateRulesResponse", + "ListEventEditRulesRequest", + "ListEventEditRulesResponse", "ListExpandedDataSetsRequest", "ListExpandedDataSetsResponse", "ListFirebaseLinksRequest", "ListFirebaseLinksResponse", "ListGoogleAdsLinksRequest", "ListGoogleAdsLinksResponse", + "ListKeyEventsRequest", + "ListKeyEventsResponse", "ListMeasurementProtocolSecretsRequest", "ListMeasurementProtocolSecretsResponse", "ListPropertiesRequest", @@ -475,6 +503,9 @@ "ListSubpropertyEventFiltersResponse", "ProvisionAccountTicketRequest", "ProvisionAccountTicketResponse", + "ProvisionSubpropertyRequest", + "ProvisionSubpropertyResponse", + "ReorderEventEditRulesRequest", "RunAccessReportRequest", "RunAccessReportResponse", "SearchChangeHistoryEventsRequest", @@ -485,6 +516,7 @@ "UpdateAccountRequest", "UpdateAttributionSettingsRequest", "UpdateAudienceRequest", + "UpdateBigQueryLinkRequest", "UpdateCalculatedMetricRequest", "UpdateChannelGroupRequest", "UpdateConversionEventRequest", @@ -496,9 +528,11 @@ "UpdateDisplayVideo360AdvertiserLinkRequest", "UpdateEnhancedMeasurementSettingsRequest", "UpdateEventCreateRuleRequest", + "UpdateEventEditRuleRequest", "UpdateExpandedDataSetRequest", "UpdateGoogleAdsLinkRequest", "UpdateGoogleSignalsSettingsRequest", + "UpdateKeyEventRequest", "UpdateMeasurementProtocolSecretRequest", "UpdatePropertyRequest", "UpdateSearchAds360LinkRequest", @@ -520,6 +554,7 @@ "ChannelGroupFilterExpressionList", "GroupingRule", "EventCreateRule", + "EventEditRule", "MatchingCondition", "ParameterMutation", "ExpandedDataSet", @@ -552,6 +587,7 @@ "GlobalSiteTag", "GoogleAdsLink", "GoogleSignalsSettings", + "KeyEvent", "LinkProposalStatusDetails", "MeasurementProtocolSecret", "PostbackWindow", diff --git a/packages/google-analytics-admin/google/analytics/admin/gapic_version.py b/packages/google-analytics-admin/google/analytics/admin/gapic_version.py index f56358e27bf1..558c8aab67c5 100644 --- a/packages/google-analytics-admin/google/analytics/admin/gapic_version.py +++ b/packages/google-analytics-admin/google/analytics/admin/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.22.9" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/__init__.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/__init__.py index a3eb8f302be4..6231a2bcad0d 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/__init__.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/__init__.py @@ -62,6 +62,7 @@ CreateAccessBindingRequest, CreateAdSenseLinkRequest, CreateAudienceRequest, + CreateBigQueryLinkRequest, CreateCalculatedMetricRequest, CreateChannelGroupRequest, CreateConnectedSiteTagRequest, @@ -73,9 +74,11 @@ CreateDisplayVideo360AdvertiserLinkProposalRequest, CreateDisplayVideo360AdvertiserLinkRequest, CreateEventCreateRuleRequest, + CreateEventEditRuleRequest, CreateExpandedDataSetRequest, CreateFirebaseLinkRequest, CreateGoogleAdsLinkRequest, + CreateKeyEventRequest, CreateMeasurementProtocolSecretRequest, CreatePropertyRequest, CreateRollupPropertyRequest, @@ -84,11 +87,10 @@ CreateSearchAds360LinkRequest, CreateSKAdNetworkConversionValueSchemaRequest, CreateSubpropertyEventFilterRequest, - CreateSubpropertyRequest, - CreateSubpropertyResponse, DeleteAccessBindingRequest, DeleteAccountRequest, DeleteAdSenseLinkRequest, + DeleteBigQueryLinkRequest, DeleteCalculatedMetricRequest, DeleteChannelGroupRequest, DeleteConnectedSiteTagRequest, @@ -97,9 +99,11 @@ DeleteDisplayVideo360AdvertiserLinkProposalRequest, DeleteDisplayVideo360AdvertiserLinkRequest, DeleteEventCreateRuleRequest, + DeleteEventEditRuleRequest, DeleteExpandedDataSetRequest, DeleteFirebaseLinkRequest, DeleteGoogleAdsLinkRequest, + DeleteKeyEventRequest, DeleteMeasurementProtocolSecretRequest, DeletePropertyRequest, DeleteRollupPropertySourceLinkRequest, @@ -129,9 +133,11 @@ GetDisplayVideo360AdvertiserLinkRequest, GetEnhancedMeasurementSettingsRequest, GetEventCreateRuleRequest, + GetEventEditRuleRequest, GetExpandedDataSetRequest, GetGlobalSiteTagRequest, GetGoogleSignalsSettingsRequest, + GetKeyEventRequest, GetMeasurementProtocolSecretRequest, GetPropertyRequest, GetRollupPropertySourceLinkRequest, @@ -170,12 +176,16 @@ ListDisplayVideo360AdvertiserLinksResponse, ListEventCreateRulesRequest, ListEventCreateRulesResponse, + ListEventEditRulesRequest, + ListEventEditRulesResponse, ListExpandedDataSetsRequest, ListExpandedDataSetsResponse, ListFirebaseLinksRequest, ListFirebaseLinksResponse, ListGoogleAdsLinksRequest, ListGoogleAdsLinksResponse, + ListKeyEventsRequest, + ListKeyEventsResponse, ListMeasurementProtocolSecretsRequest, ListMeasurementProtocolSecretsResponse, ListPropertiesRequest, @@ -190,6 +200,9 @@ ListSubpropertyEventFiltersResponse, ProvisionAccountTicketRequest, ProvisionAccountTicketResponse, + ProvisionSubpropertyRequest, + ProvisionSubpropertyResponse, + ReorderEventEditRulesRequest, RunAccessReportRequest, RunAccessReportResponse, SearchChangeHistoryEventsRequest, @@ -200,6 +213,7 @@ UpdateAccountRequest, UpdateAttributionSettingsRequest, UpdateAudienceRequest, + UpdateBigQueryLinkRequest, UpdateCalculatedMetricRequest, UpdateChannelGroupRequest, UpdateConversionEventRequest, @@ -211,9 +225,11 @@ UpdateDisplayVideo360AdvertiserLinkRequest, UpdateEnhancedMeasurementSettingsRequest, UpdateEventCreateRuleRequest, + UpdateEventEditRuleRequest, UpdateExpandedDataSetRequest, UpdateGoogleAdsLinkRequest, UpdateGoogleSignalsSettingsRequest, + UpdateKeyEventRequest, UpdateMeasurementProtocolSecretRequest, UpdatePropertyRequest, UpdateSearchAds360LinkRequest, @@ -241,6 +257,7 @@ ) from .types.event_create_and_edit import ( EventCreateRule, + EventEditRule, MatchingCondition, ParameterMutation, ) @@ -284,6 +301,7 @@ GoogleSignalsSettings, GoogleSignalsState, IndustryCategory, + KeyEvent, LinkProposalInitiatingProduct, LinkProposalState, LinkProposalStatusDetails, @@ -374,6 +392,7 @@ "CreateAccessBindingRequest", "CreateAdSenseLinkRequest", "CreateAudienceRequest", + "CreateBigQueryLinkRequest", "CreateCalculatedMetricRequest", "CreateChannelGroupRequest", "CreateConnectedSiteTagRequest", @@ -385,9 +404,11 @@ "CreateDisplayVideo360AdvertiserLinkProposalRequest", "CreateDisplayVideo360AdvertiserLinkRequest", "CreateEventCreateRuleRequest", + "CreateEventEditRuleRequest", "CreateExpandedDataSetRequest", "CreateFirebaseLinkRequest", "CreateGoogleAdsLinkRequest", + "CreateKeyEventRequest", "CreateMeasurementProtocolSecretRequest", "CreatePropertyRequest", "CreateRollupPropertyRequest", @@ -396,8 +417,6 @@ "CreateSKAdNetworkConversionValueSchemaRequest", "CreateSearchAds360LinkRequest", "CreateSubpropertyEventFilterRequest", - "CreateSubpropertyRequest", - "CreateSubpropertyResponse", "CustomDimension", "CustomMetric", "DataRedactionSettings", @@ -407,6 +426,7 @@ "DeleteAccessBindingRequest", "DeleteAccountRequest", "DeleteAdSenseLinkRequest", + "DeleteBigQueryLinkRequest", "DeleteCalculatedMetricRequest", "DeleteChannelGroupRequest", "DeleteConnectedSiteTagRequest", @@ -415,9 +435,11 @@ "DeleteDisplayVideo360AdvertiserLinkProposalRequest", "DeleteDisplayVideo360AdvertiserLinkRequest", "DeleteEventCreateRuleRequest", + "DeleteEventEditRuleRequest", "DeleteExpandedDataSetRequest", "DeleteFirebaseLinkRequest", "DeleteGoogleAdsLinkRequest", + "DeleteKeyEventRequest", "DeleteMeasurementProtocolSecretRequest", "DeletePropertyRequest", "DeleteRollupPropertySourceLinkRequest", @@ -428,6 +450,7 @@ "DisplayVideo360AdvertiserLinkProposal", "EnhancedMeasurementSettings", "EventCreateRule", + "EventEditRule", "EventMapping", "ExpandedDataSet", "ExpandedDataSetFilter", @@ -457,9 +480,11 @@ "GetDisplayVideo360AdvertiserLinkRequest", "GetEnhancedMeasurementSettingsRequest", "GetEventCreateRuleRequest", + "GetEventEditRuleRequest", "GetExpandedDataSetRequest", "GetGlobalSiteTagRequest", "GetGoogleSignalsSettingsRequest", + "GetKeyEventRequest", "GetMeasurementProtocolSecretRequest", "GetPropertyRequest", "GetRollupPropertySourceLinkRequest", @@ -473,6 +498,7 @@ "GoogleSignalsState", "GroupingRule", "IndustryCategory", + "KeyEvent", "LinkProposalInitiatingProduct", "LinkProposalState", "LinkProposalStatusDetails", @@ -508,12 +534,16 @@ "ListDisplayVideo360AdvertiserLinksResponse", "ListEventCreateRulesRequest", "ListEventCreateRulesResponse", + "ListEventEditRulesRequest", + "ListEventEditRulesResponse", "ListExpandedDataSetsRequest", "ListExpandedDataSetsResponse", "ListFirebaseLinksRequest", "ListFirebaseLinksResponse", "ListGoogleAdsLinksRequest", "ListGoogleAdsLinksResponse", + "ListKeyEventsRequest", + "ListKeyEventsResponse", "ListMeasurementProtocolSecretsRequest", "ListMeasurementProtocolSecretsResponse", "ListPropertiesRequest", @@ -536,6 +566,9 @@ "PropertyType", "ProvisionAccountTicketRequest", "ProvisionAccountTicketResponse", + "ProvisionSubpropertyRequest", + "ProvisionSubpropertyResponse", + "ReorderEventEditRulesRequest", "RollupPropertySourceLink", "RunAccessReportRequest", "RunAccessReportResponse", @@ -555,6 +588,7 @@ "UpdateAccountRequest", "UpdateAttributionSettingsRequest", "UpdateAudienceRequest", + "UpdateBigQueryLinkRequest", "UpdateCalculatedMetricRequest", "UpdateChannelGroupRequest", "UpdateConversionEventRequest", @@ -566,9 +600,11 @@ "UpdateDisplayVideo360AdvertiserLinkRequest", "UpdateEnhancedMeasurementSettingsRequest", "UpdateEventCreateRuleRequest", + "UpdateEventEditRuleRequest", "UpdateExpandedDataSetRequest", "UpdateGoogleAdsLinkRequest", "UpdateGoogleSignalsSettingsRequest", + "UpdateKeyEventRequest", "UpdateMeasurementProtocolSecretRequest", "UpdatePropertyRequest", "UpdateSKAdNetworkConversionValueSchemaRequest", diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_metadata.json b/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_metadata.json index a6360caf93cd..d379bf7a5952 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_metadata.json +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_metadata.json @@ -75,6 +75,11 @@ "create_audience" ] }, + "CreateBigQueryLink": { + "methods": [ + "create_big_query_link" + ] + }, "CreateCalculatedMetric": { "methods": [ "create_calculated_metric" @@ -125,6 +130,11 @@ "create_event_create_rule" ] }, + "CreateEventEditRule": { + "methods": [ + "create_event_edit_rule" + ] + }, "CreateExpandedDataSet": { "methods": [ "create_expanded_data_set" @@ -140,6 +150,11 @@ "create_google_ads_link" ] }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, "CreateMeasurementProtocolSecret": { "methods": [ "create_measurement_protocol_secret" @@ -170,11 +185,6 @@ "create_search_ads360_link" ] }, - "CreateSubproperty": { - "methods": [ - "create_subproperty" - ] - }, "CreateSubpropertyEventFilter": { "methods": [ "create_subproperty_event_filter" @@ -195,6 +205,11 @@ "delete_ad_sense_link" ] }, + "DeleteBigQueryLink": { + "methods": [ + "delete_big_query_link" + ] + }, "DeleteCalculatedMetric": { "methods": [ "delete_calculated_metric" @@ -235,6 +250,11 @@ "delete_event_create_rule" ] }, + "DeleteEventEditRule": { + "methods": [ + "delete_event_edit_rule" + ] + }, "DeleteExpandedDataSet": { "methods": [ "delete_expanded_data_set" @@ -250,6 +270,11 @@ "delete_google_ads_link" ] }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, "DeleteMeasurementProtocolSecret": { "methods": [ "delete_measurement_protocol_secret" @@ -385,6 +410,11 @@ "get_event_create_rule" ] }, + "GetEventEditRule": { + "methods": [ + "get_event_edit_rule" + ] + }, "GetExpandedDataSet": { "methods": [ "get_expanded_data_set" @@ -400,6 +430,11 @@ "get_google_signals_settings" ] }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, "GetMeasurementProtocolSecret": { "methods": [ "get_measurement_protocol_secret" @@ -510,6 +545,11 @@ "list_event_create_rules" ] }, + "ListEventEditRules": { + "methods": [ + "list_event_edit_rules" + ] + }, "ListExpandedDataSets": { "methods": [ "list_expanded_data_sets" @@ -525,6 +565,11 @@ "list_google_ads_links" ] }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, "ListMeasurementProtocolSecrets": { "methods": [ "list_measurement_protocol_secrets" @@ -560,6 +605,16 @@ "provision_account_ticket" ] }, + "ProvisionSubproperty": { + "methods": [ + "provision_subproperty" + ] + }, + "ReorderEventEditRules": { + "methods": [ + "reorder_event_edit_rules" + ] + }, "RunAccessReport": { "methods": [ "run_access_report" @@ -595,6 +650,11 @@ "update_audience" ] }, + "UpdateBigQueryLink": { + "methods": [ + "update_big_query_link" + ] + }, "UpdateCalculatedMetric": { "methods": [ "update_calculated_metric" @@ -650,6 +710,11 @@ "update_event_create_rule" ] }, + "UpdateEventEditRule": { + "methods": [ + "update_event_edit_rule" + ] + }, "UpdateExpandedDataSet": { "methods": [ "update_expanded_data_set" @@ -665,6 +730,11 @@ "update_google_signals_settings" ] }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, "UpdateMeasurementProtocolSecret": { "methods": [ "update_measurement_protocol_secret" @@ -760,6 +830,11 @@ "create_audience" ] }, + "CreateBigQueryLink": { + "methods": [ + "create_big_query_link" + ] + }, "CreateCalculatedMetric": { "methods": [ "create_calculated_metric" @@ -810,6 +885,11 @@ "create_event_create_rule" ] }, + "CreateEventEditRule": { + "methods": [ + "create_event_edit_rule" + ] + }, "CreateExpandedDataSet": { "methods": [ "create_expanded_data_set" @@ -825,6 +905,11 @@ "create_google_ads_link" ] }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, "CreateMeasurementProtocolSecret": { "methods": [ "create_measurement_protocol_secret" @@ -855,11 +940,6 @@ "create_search_ads360_link" ] }, - "CreateSubproperty": { - "methods": [ - "create_subproperty" - ] - }, "CreateSubpropertyEventFilter": { "methods": [ "create_subproperty_event_filter" @@ -880,6 +960,11 @@ "delete_ad_sense_link" ] }, + "DeleteBigQueryLink": { + "methods": [ + "delete_big_query_link" + ] + }, "DeleteCalculatedMetric": { "methods": [ "delete_calculated_metric" @@ -920,6 +1005,11 @@ "delete_event_create_rule" ] }, + "DeleteEventEditRule": { + "methods": [ + "delete_event_edit_rule" + ] + }, "DeleteExpandedDataSet": { "methods": [ "delete_expanded_data_set" @@ -935,6 +1025,11 @@ "delete_google_ads_link" ] }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, "DeleteMeasurementProtocolSecret": { "methods": [ "delete_measurement_protocol_secret" @@ -1070,6 +1165,11 @@ "get_event_create_rule" ] }, + "GetEventEditRule": { + "methods": [ + "get_event_edit_rule" + ] + }, "GetExpandedDataSet": { "methods": [ "get_expanded_data_set" @@ -1085,6 +1185,11 @@ "get_google_signals_settings" ] }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, "GetMeasurementProtocolSecret": { "methods": [ "get_measurement_protocol_secret" @@ -1195,6 +1300,11 @@ "list_event_create_rules" ] }, + "ListEventEditRules": { + "methods": [ + "list_event_edit_rules" + ] + }, "ListExpandedDataSets": { "methods": [ "list_expanded_data_sets" @@ -1210,6 +1320,11 @@ "list_google_ads_links" ] }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, "ListMeasurementProtocolSecrets": { "methods": [ "list_measurement_protocol_secrets" @@ -1245,6 +1360,16 @@ "provision_account_ticket" ] }, + "ProvisionSubproperty": { + "methods": [ + "provision_subproperty" + ] + }, + "ReorderEventEditRules": { + "methods": [ + "reorder_event_edit_rules" + ] + }, "RunAccessReport": { "methods": [ "run_access_report" @@ -1280,6 +1405,11 @@ "update_audience" ] }, + "UpdateBigQueryLink": { + "methods": [ + "update_big_query_link" + ] + }, "UpdateCalculatedMetric": { "methods": [ "update_calculated_metric" @@ -1335,6 +1465,11 @@ "update_event_create_rule" ] }, + "UpdateEventEditRule": { + "methods": [ + "update_event_edit_rule" + ] + }, "UpdateExpandedDataSet": { "methods": [ "update_expanded_data_set" @@ -1350,6 +1485,11 @@ "update_google_signals_settings" ] }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, "UpdateMeasurementProtocolSecret": { "methods": [ "update_measurement_protocol_secret" @@ -1445,6 +1585,11 @@ "create_audience" ] }, + "CreateBigQueryLink": { + "methods": [ + "create_big_query_link" + ] + }, "CreateCalculatedMetric": { "methods": [ "create_calculated_metric" @@ -1495,6 +1640,11 @@ "create_event_create_rule" ] }, + "CreateEventEditRule": { + "methods": [ + "create_event_edit_rule" + ] + }, "CreateExpandedDataSet": { "methods": [ "create_expanded_data_set" @@ -1510,6 +1660,11 @@ "create_google_ads_link" ] }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, "CreateMeasurementProtocolSecret": { "methods": [ "create_measurement_protocol_secret" @@ -1540,11 +1695,6 @@ "create_search_ads360_link" ] }, - "CreateSubproperty": { - "methods": [ - "create_subproperty" - ] - }, "CreateSubpropertyEventFilter": { "methods": [ "create_subproperty_event_filter" @@ -1565,6 +1715,11 @@ "delete_ad_sense_link" ] }, + "DeleteBigQueryLink": { + "methods": [ + "delete_big_query_link" + ] + }, "DeleteCalculatedMetric": { "methods": [ "delete_calculated_metric" @@ -1605,6 +1760,11 @@ "delete_event_create_rule" ] }, + "DeleteEventEditRule": { + "methods": [ + "delete_event_edit_rule" + ] + }, "DeleteExpandedDataSet": { "methods": [ "delete_expanded_data_set" @@ -1620,6 +1780,11 @@ "delete_google_ads_link" ] }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, "DeleteMeasurementProtocolSecret": { "methods": [ "delete_measurement_protocol_secret" @@ -1755,6 +1920,11 @@ "get_event_create_rule" ] }, + "GetEventEditRule": { + "methods": [ + "get_event_edit_rule" + ] + }, "GetExpandedDataSet": { "methods": [ "get_expanded_data_set" @@ -1770,6 +1940,11 @@ "get_google_signals_settings" ] }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, "GetMeasurementProtocolSecret": { "methods": [ "get_measurement_protocol_secret" @@ -1880,6 +2055,11 @@ "list_event_create_rules" ] }, + "ListEventEditRules": { + "methods": [ + "list_event_edit_rules" + ] + }, "ListExpandedDataSets": { "methods": [ "list_expanded_data_sets" @@ -1895,6 +2075,11 @@ "list_google_ads_links" ] }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, "ListMeasurementProtocolSecrets": { "methods": [ "list_measurement_protocol_secrets" @@ -1930,6 +2115,16 @@ "provision_account_ticket" ] }, + "ProvisionSubproperty": { + "methods": [ + "provision_subproperty" + ] + }, + "ReorderEventEditRules": { + "methods": [ + "reorder_event_edit_rules" + ] + }, "RunAccessReport": { "methods": [ "run_access_report" @@ -1965,6 +2160,11 @@ "update_audience" ] }, + "UpdateBigQueryLink": { + "methods": [ + "update_big_query_link" + ] + }, "UpdateCalculatedMetric": { "methods": [ "update_calculated_metric" @@ -2020,6 +2220,11 @@ "update_event_create_rule" ] }, + "UpdateEventEditRule": { + "methods": [ + "update_event_edit_rule" + ] + }, "UpdateExpandedDataSet": { "methods": [ "update_expanded_data_set" @@ -2035,6 +2240,11 @@ "update_google_signals_settings" ] }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, "UpdateMeasurementProtocolSecret": { "methods": [ "update_measurement_protocol_secret" diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py index f56358e27bf1..558c8aab67c5 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.22.9" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py index 5375c8fec5f5..4a62059a32b7 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py @@ -28,6 +28,7 @@ Type, Union, ) +import warnings from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -181,6 +182,12 @@ class AnalyticsAdminServiceAsyncClient: parse_event_create_rule_path = staticmethod( AnalyticsAdminServiceClient.parse_event_create_rule_path ) + event_edit_rule_path = staticmethod( + AnalyticsAdminServiceClient.event_edit_rule_path + ) + parse_event_edit_rule_path = staticmethod( + AnalyticsAdminServiceClient.parse_event_edit_rule_path + ) expanded_data_set_path = staticmethod( AnalyticsAdminServiceClient.expanded_data_set_path ) @@ -209,12 +216,20 @@ class AnalyticsAdminServiceAsyncClient: parse_google_signals_settings_path = staticmethod( AnalyticsAdminServiceClient.parse_google_signals_settings_path ) + key_event_path = staticmethod(AnalyticsAdminServiceClient.key_event_path) + parse_key_event_path = staticmethod( + AnalyticsAdminServiceClient.parse_key_event_path + ) measurement_protocol_secret_path = staticmethod( AnalyticsAdminServiceClient.measurement_protocol_secret_path ) parse_measurement_protocol_secret_path = staticmethod( AnalyticsAdminServiceClient.parse_measurement_protocol_secret_path ) + organization_path = staticmethod(AnalyticsAdminServiceClient.organization_path) + parse_organization_path = staticmethod( + AnalyticsAdminServiceClient.parse_organization_path + ) property_path = staticmethod(AnalyticsAdminServiceClient.property_path) parse_property_path = staticmethod(AnalyticsAdminServiceClient.parse_property_path) rollup_property_source_link_path = staticmethod( @@ -1330,8 +1345,9 @@ async def create_firebase_link( The request object. Request message for CreateFirebaseLink RPC parent (:class:`str`): - Required. Format: properties/{property_id} Example: - properties/1234 + Required. Format: properties/{property_id} + + Example: ``properties/1234`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1423,7 +1439,8 @@ async def delete_firebase_link( name (:class:`str`): Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} - Example: properties/1234/firebaseLinks/5678 + + Example: ``properties/1234/firebaseLinks/5678`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1494,8 +1511,9 @@ async def list_firebase_links( The request object. Request message for ListFirebaseLinks RPC parent (:class:`str`): - Required. Format: properties/{property_id} Example: - properties/1234 + Required. Format: properties/{property_id} + + Example: ``properties/1234`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -1593,7 +1611,9 @@ async def get_global_site_tag( site tags are singletons and do not have unique IDs. Format: properties/{property_id}/dataStreams/{stream_id}/globalSiteTag - Example: "properties/123/dataStreams/456/globalSiteTag" + + Example: + ``properties/123/dataStreams/456/globalSiteTag`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2033,11 +2053,10 @@ async def get_data_sharing_settings( The request object. Request message for GetDataSharingSettings RPC. name (:class:`str`): - Required. The name of the settings to - lookup. Format: + Required. The name of the settings to lookup. Format: accounts/{account}/dataSharingSettings - Example: - "accounts/1000/dataSharingSettings" + + Example: ``accounts/1000/dataSharingSettings`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -3385,8 +3404,8 @@ async def create_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.ConversionEvent: - r"""Creates a conversion event with the specified - attributes. + r"""Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. Args: request (Optional[Union[google.analytics.admin_v1alpha.types.CreateConversionEventRequest, dict]]): @@ -3420,6 +3439,11 @@ async def create_conversion_event( Analytics property. """ + warnings.warn( + "AnalyticsAdminServiceAsyncClient.create_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -3480,8 +3504,8 @@ async def update_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.ConversionEvent: - r"""Updates a conversion event with the specified - attributes. + r"""Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. Args: request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateConversionEventRequest, dict]]): @@ -3516,6 +3540,11 @@ async def update_conversion_event( Analytics property. """ + warnings.warn( + "AnalyticsAdminServiceAsyncClient.update_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -3577,7 +3606,8 @@ async def get_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.ConversionEvent: - r"""Retrieve a single conversion event. + r"""Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. Args: request (Optional[Union[google.analytics.admin_v1alpha.types.GetConversionEventRequest, dict]]): @@ -3604,6 +3634,11 @@ async def get_conversion_event( Analytics property. """ + warnings.warn( + "AnalyticsAdminServiceAsyncClient.get_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -3661,7 +3696,8 @@ async def delete_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a conversion event in a property. + r"""Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. Args: request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteConversionEventRequest, dict]]): @@ -3682,6 +3718,11 @@ async def delete_conversion_event( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ + warnings.warn( + "AnalyticsAdminServiceAsyncClient.delete_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -3736,8 +3777,9 @@ async def list_conversion_events( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListConversionEventsAsyncPager: - r"""Returns a list of conversion events in the specified - parent property. + r"""Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + Returns an empty list if no conversion events are found. Args: @@ -3767,6 +3809,11 @@ async def list_conversion_events( automatically. """ + warnings.warn( + "AnalyticsAdminServiceAsyncClient.list_conversion_events is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -3824,30 +3871,33 @@ async def list_conversion_events( # Done; return the response. return response - async def get_display_video360_advertiser_link( + async def create_key_event( self, - request: Optional[ - Union[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.CreateKeyEventRequest, dict]] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLink: - r"""Look up a single DisplayVideo360AdvertiserLink + ) -> resources.KeyEvent: + r"""Creates a Key Event. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkRequest, dict]]): - The request object. Request message for - GetDisplayVideo360AdvertiserLink RPC. - name (:class:`str`): - Required. The name of the - DisplayVideo360AdvertiserLink to get. - Example format: - properties/1234/displayVideo360AdvertiserLink/5678 + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateKeyEventRequest, dict]]): + The request object. Request message for CreateKeyEvent + RPC + parent (:class:`str`): + Required. The resource name of the + parent property where this Key Event + will be created. Format: properties/123 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_event (:class:`google.analytics.admin_v1alpha.types.KeyEvent`): + Required. The Key Event to create. + This corresponds to the ``key_event`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -3857,15 +3907,15 @@ async def get_display_video360_advertiser_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: - A link between a GA4 property and a - Display & Video 360 advertiser. + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, key_event]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3874,26 +3924,26 @@ async def get_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.GetDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(request) + if not isinstance(request, analytics_admin.CreateKeyEventRequest): + request = analytics_admin.CreateKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if key_event is not None: + request.key_event = key_event # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_display_video360_advertiser_link + self._client._transport.create_key_event ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -3910,29 +3960,37 @@ async def get_display_video360_advertiser_link( # Done; return the response. return response - async def list_display_video360_advertiser_links( + async def update_key_event( self, - request: Optional[ - Union[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.UpdateKeyEventRequest, dict]] = None, *, - parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDisplayVideo360AdvertiserLinksAsyncPager: - r"""Lists all DisplayVideo360AdvertiserLinks on a - property. + ) -> resources.KeyEvent: + r"""Updates a Key Event. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest, dict]]): - The request object. Request message for - ListDisplayVideo360AdvertiserLinks RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateKeyEventRequest, dict]]): + The request object. Request message for UpdateKeyEvent + RPC + key_event (:class:`google.analytics.admin_v1alpha.types.KeyEvent`): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. - This corresponds to the ``parent`` field + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -3942,18 +4000,15 @@ async def list_display_video360_advertiser_links( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinksAsyncPager: - Response message for - ListDisplayVideo360AdvertiserLinks RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([key_event, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -3962,26 +4017,28 @@ async def list_display_video360_advertiser_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.ListDisplayVideo360AdvertiserLinksRequest - ): - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) + if not isinstance(request, analytics_admin.UpdateKeyEventRequest): + request = analytics_admin.UpdateKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if key_event is not None: + request.key_event = key_event + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_display_video360_advertiser_links + self._client._transport.update_key_event ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("key_event.name", request.key_event.name),) + ), ) # Validate the universe domain. @@ -3995,57 +4052,30 @@ async def list_display_video360_advertiser_links( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDisplayVideo360AdvertiserLinksAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - async def create_display_video360_advertiser_link( + async def get_key_event( self, - request: Optional[ - Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetKeyEventRequest, dict]] = None, *, - parent: Optional[str] = None, - display_video_360_advertiser_link: Optional[ - resources.DisplayVideo360AdvertiserLink - ] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLink: - r"""Creates a DisplayVideo360AdvertiserLink. - This can only be utilized by users who have proper - authorization both on the Google Analytics property and - on the Display & Video 360 advertiser. Users who do not - have access to the Display & Video 360 advertiser should - instead seek to create a DisplayVideo360LinkProposal. + ) -> resources.KeyEvent: + r"""Retrieve a single Key Event. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkRequest, dict]]): - The request object. Request message for - CreateDisplayVideo360AdvertiserLink RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - display_video_360_advertiser_link (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink`): - Required. The - DisplayVideo360AdvertiserLink to create. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetKeyEventRequest, dict]]): + The request object. Request message for GetKeyEvent RPC + name (:class:`str`): + Required. The resource name of the Key Event to + retrieve. Format: + properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456" - This corresponds to the ``display_video_360_advertiser_link`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -4055,15 +4085,15 @@ async def create_display_video360_advertiser_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: - A link between a GA4 property and a - Display & Video 360 advertiser. + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, display_video_360_advertiser_link]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4072,32 +4102,24 @@ async def create_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( - request - ) + if not isinstance(request, analytics_admin.GetKeyEventRequest): + request = analytics_admin.GetKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent - if display_video_360_advertiser_link is not None: - request.display_video_360_advertiser_link = ( - display_video_360_advertiser_link - ) + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_display_video360_advertiser_link + self._client._transport.get_key_event ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4114,29 +4136,25 @@ async def create_display_video360_advertiser_link( # Done; return the response. return response - async def delete_display_video360_advertiser_link( + async def delete_key_event( self, - request: Optional[ - Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.DeleteKeyEventRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a DisplayVideo360AdvertiserLink on a - property. + r"""Deletes a Key Event. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkRequest, dict]]): - The request object. Request message for - DeleteDisplayVideo360AdvertiserLink RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteKeyEventRequest, dict]]): + The request object. Request message for DeleteKeyEvent + RPC name (:class:`str`): - Required. The name of the - DisplayVideo360AdvertiserLink to delete. - Example format: - properties/1234/displayVideo360AdvertiserLinks/5678 + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} + Example: "properties/123/keyEvents/456" This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -4159,12 +4177,8 @@ async def delete_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( - request - ) + if not isinstance(request, analytics_admin.DeleteKeyEventRequest): + request = analytics_admin.DeleteKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -4174,7 +4188,7 @@ async def delete_display_video360_advertiser_link( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_display_video360_advertiser_link + self._client._transport.delete_key_event ] # Certain fields should be provided within the metadata header; @@ -4194,41 +4208,28 @@ async def delete_display_video360_advertiser_link( metadata=metadata, ) - async def update_display_video360_advertiser_link( + async def list_key_events( self, - request: Optional[ - Union[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListKeyEventsRequest, dict]] = None, *, - display_video_360_advertiser_link: Optional[ - resources.DisplayVideo360AdvertiserLink - ] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLink: - r"""Updates a DisplayVideo360AdvertiserLink on a - property. + ) -> pagers.ListKeyEventsAsyncPager: + r"""Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDisplayVideo360AdvertiserLinkRequest, dict]]): - The request object. Request message for - UpdateDisplayVideo360AdvertiserLink RPC. - display_video_360_advertiser_link (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink`): - The DisplayVideo360AdvertiserLink to - update - - This corresponds to the ``display_video_360_advertiser_link`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListKeyEventsRequest, dict]]): + The request object. Request message for ListKeyEvents RPC + parent (:class:`str`): + Required. The resource name of the + parent property. Example: + 'properties/123' - This corresponds to the ``update_mask`` field + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -4238,15 +4239,18 @@ async def update_display_video360_advertiser_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: - A link between a GA4 property and a - Display & Video 360 advertiser. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListKeyEventsAsyncPager: + Response message for ListKeyEvents + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([display_video_360_advertiser_link, update_mask]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4255,39 +4259,24 @@ async def update_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest( - request - ) + if not isinstance(request, analytics_admin.ListKeyEventsRequest): + request = analytics_admin.ListKeyEventsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if display_video_360_advertiser_link is not None: - request.display_video_360_advertiser_link = ( - display_video_360_advertiser_link - ) - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_display_video360_advertiser_link + self._client._transport.list_key_events ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - ( - ( - "display_video_360_advertiser_link.name", - request.display_video_360_advertiser_link.name, - ), - ) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4301,33 +4290,42 @@ async def update_display_video360_advertiser_link( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKeyEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def get_display_video360_advertiser_link_proposal( + async def get_display_video360_advertiser_link( self, request: Optional[ - Union[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, dict] + Union[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLinkProposal: - r"""Lookup for a single - DisplayVideo360AdvertiserLinkProposal. + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Look up a single DisplayVideo360AdvertiserLink Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkRequest, dict]]): The request object. Request message for - GetDisplayVideo360AdvertiserLinkProposal - RPC. + GetDisplayVideo360AdvertiserLink RPC. name (:class:`str`): Required. The name of the - DisplayVideo360AdvertiserLinkProposal to - get. Example format: - properties/1234/displayVideo360AdvertiserLinkProposals/5678 + DisplayVideo360AdvertiserLink to get. + Example format: + properties/1234/displayVideo360AdvertiserLink/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -4339,17 +4337,9 @@ async def get_display_video360_advertiser_link_proposal( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: - A proposal for a link between a GA4 - property and a Display & Video 360 - advertiser. - - A proposal is converted to a - DisplayVideo360AdvertiserLink once - approved. Google Analytics admins - approve inbound proposals while Display - & Video 360 admins approve outbound - proposals. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. """ # Create or coerce a protobuf request object. @@ -4365,11 +4355,9 @@ async def get_display_video360_advertiser_link_proposal( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.GetDisplayVideo360AdvertiserLinkRequest ): - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -4379,7 +4367,7 @@ async def get_display_video360_advertiser_link_proposal( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_display_video360_advertiser_link_proposal + self._client._transport.get_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; @@ -4402,27 +4390,24 @@ async def get_display_video360_advertiser_link_proposal( # Done; return the response. return response - async def list_display_video360_advertiser_link_proposals( + async def list_display_video360_advertiser_links( self, request: Optional[ - Union[ - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict - ] + Union[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, dict] ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: - r"""Lists DisplayVideo360AdvertiserLinkProposals on a + ) -> pagers.ListDisplayVideo360AdvertiserLinksAsyncPager: + r"""Lists all DisplayVideo360AdvertiserLinks on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest, dict]]): The request object. Request message for - ListDisplayVideo360AdvertiserLinkProposals - RPC. + ListDisplayVideo360AdvertiserLinks RPC. parent (:class:`str`): Required. Example format: properties/1234 @@ -4437,12 +4422,12 @@ async def list_display_video360_advertiser_link_proposals( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinksAsyncPager: Response message for - ListDisplayVideo360AdvertiserLinkProposals - RPC. Iterating over this object will - yield results and resolve additional - pages automatically. + ListDisplayVideo360AdvertiserLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. @@ -4458,11 +4443,9 @@ async def list_display_video360_advertiser_link_proposals( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest + request, analytics_admin.ListDisplayVideo360AdvertiserLinksRequest ): - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( - request - ) + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -4472,7 +4455,7 @@ async def list_display_video360_advertiser_link_proposals( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_display_video360_advertiser_link_proposals + self._client._transport.list_display_video360_advertiser_links ] # Certain fields should be provided within the metadata header; @@ -4494,7 +4477,7 @@ async def list_display_video360_advertiser_link_proposals( # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. - response = pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager( + response = pagers.ListDisplayVideo360AdvertiserLinksAsyncPager( method=rpc, request=request, response=response, @@ -4506,29 +4489,31 @@ async def list_display_video360_advertiser_link_proposals( # Done; return the response. return response - async def create_display_video360_advertiser_link_proposal( + async def create_display_video360_advertiser_link( self, request: Optional[ - Union[ - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict - ] + Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, parent: Optional[str] = None, - display_video_360_advertiser_link_proposal: Optional[ - resources.DisplayVideo360AdvertiserLinkProposal + display_video_360_advertiser_link: Optional[ + resources.DisplayVideo360AdvertiserLink ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLinkProposal: - r"""Creates a DisplayVideo360AdvertiserLinkProposal. + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Creates a DisplayVideo360AdvertiserLink. + This can only be utilized by users who have proper + authorization both on the Google Analytics property and + on the Display & Video 360 advertiser. Users who do not + have access to the Display & Video 360 advertiser should + instead seek to create a DisplayVideo360LinkProposal. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkRequest, dict]]): The request object. Request message for - CreateDisplayVideo360AdvertiserLinkProposal - RPC. + CreateDisplayVideo360AdvertiserLink RPC. parent (:class:`str`): Required. Example format: properties/1234 @@ -4536,12 +4521,11 @@ async def create_display_video360_advertiser_link_proposal( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - display_video_360_advertiser_link_proposal (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal`): + display_video_360_advertiser_link (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink`): Required. The - DisplayVideo360AdvertiserLinkProposal to - create. + DisplayVideo360AdvertiserLink to create. - This corresponds to the ``display_video_360_advertiser_link_proposal`` field + This corresponds to the ``display_video_360_advertiser_link`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -4551,23 +4535,15 @@ async def create_display_video360_advertiser_link_proposal( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: - A proposal for a link between a GA4 - property and a Display & Video 360 - advertiser. - - A proposal is converted to a - DisplayVideo360AdvertiserLink once - approved. Google Analytics admins - approve inbound proposals while Display - & Video 360 admins approve outbound - proposals. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, display_video_360_advertiser_link_proposal]) + has_flattened_params = any([parent, display_video_360_advertiser_link]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4577,27 +4553,25 @@ async def create_display_video360_advertiser_link_proposal( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest ): - request = ( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( + request ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if display_video_360_advertiser_link_proposal is not None: - request.display_video_360_advertiser_link_proposal = ( - display_video_360_advertiser_link_proposal + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = ( + display_video_360_advertiser_link ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_display_video360_advertiser_link_proposal + self._client._transport.create_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; @@ -4620,12 +4594,10 @@ async def create_display_video360_advertiser_link_proposal( # Done; return the response. return response - async def delete_display_video360_advertiser_link_proposal( + async def delete_display_video360_advertiser_link( self, request: Optional[ - Union[ - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict - ] + Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, name: Optional[str] = None, @@ -4633,19 +4605,18 @@ async def delete_display_video360_advertiser_link_proposal( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a DisplayVideo360AdvertiserLinkProposal on a - property. This can only be used on cancelled proposals. + r"""Deletes a DisplayVideo360AdvertiserLink on a + property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkRequest, dict]]): The request object. Request message for - DeleteDisplayVideo360AdvertiserLinkProposal - RPC. + DeleteDisplayVideo360AdvertiserLink RPC. name (:class:`str`): Required. The name of the - DisplayVideo360AdvertiserLinkProposal to - delete. Example format: - properties/1234/displayVideo360AdvertiserLinkProposals/5678 + DisplayVideo360AdvertiserLink to delete. + Example format: + properties/1234/displayVideo360AdvertiserLinks/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -4669,12 +4640,10 @@ async def delete_display_video360_advertiser_link_proposal( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest ): - request = ( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( + request ) # If we have keyword arguments corresponding to fields on the @@ -4685,7 +4654,7 @@ async def delete_display_video360_advertiser_link_proposal( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_display_video360_advertiser_link_proposal + self._client._transport.delete_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; @@ -4705,29 +4674,43 @@ async def delete_display_video360_advertiser_link_proposal( metadata=metadata, ) - async def approve_display_video360_advertiser_link_proposal( + async def update_display_video360_advertiser_link( self, request: Optional[ - Union[ - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, - dict, - ] + Union[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, + display_video_360_advertiser_link: Optional[ + resources.DisplayVideo360AdvertiserLink + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: - r"""Approves a DisplayVideo360AdvertiserLinkProposal. - The DisplayVideo360AdvertiserLinkProposal will be - deleted and a new DisplayVideo360AdvertiserLink will be - created. + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Updates a DisplayVideo360AdvertiserLink on a + property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDisplayVideo360AdvertiserLinkRequest, dict]]): The request object. Request message for - ApproveDisplayVideo360AdvertiserLinkProposal - RPC. + UpdateDisplayVideo360AdvertiserLink RPC. + display_video_360_advertiser_link (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink`): + The DisplayVideo360AdvertiserLink to + update + + This corresponds to the ``display_video_360_advertiser_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4735,34 +4718,56 @@ async def approve_display_video360_advertiser_link_proposal( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalResponse: - Response message for - ApproveDisplayVideo360AdvertiserLinkProposal - RPC. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([display_video_360_advertiser_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest ): - request = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = ( + display_video_360_advertiser_link ) + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.approve_display_video360_advertiser_link_proposal + self._client._transport.update_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "display_video_360_advertiser_link.name", + request.display_video_360_advertiser_link.name, + ), + ) + ), ) # Validate the universe domain. @@ -4779,32 +4784,34 @@ async def approve_display_video360_advertiser_link_proposal( # Done; return the response. return response - async def cancel_display_video360_advertiser_link_proposal( + async def get_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[ - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict - ] + Union[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, dict] ] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.DisplayVideo360AdvertiserLinkProposal: - r"""Cancels a DisplayVideo360AdvertiserLinkProposal. - Cancelling can mean either: - - - Declining a proposal initiated from Display & Video - 360 - - Withdrawing a proposal initiated from Google Analytics - After being cancelled, a proposal will eventually be - deleted automatically. + r"""Lookup for a single + DisplayVideo360AdvertiserLinkProposal. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkProposalRequest, dict]]): The request object. Request message for - CancelDisplayVideo360AdvertiserLinkProposal + GetDisplayVideo360AdvertiserLinkProposal RPC. + name (:class:`str`): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + get. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4826,21 +4833,33 @@ async def cancel_display_video360_advertiser_link_proposal( """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest ): - request = ( - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( + request ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.cancel_display_video360_advertiser_link_proposal + self._client._transport.get_display_video360_advertiser_link_proposal ] # Certain fields should be provided within the metadata header; @@ -4863,24 +4882,27 @@ async def cancel_display_video360_advertiser_link_proposal( # Done; return the response. return response - async def create_custom_dimension( + async def list_display_video360_advertiser_link_proposals( self, request: Optional[ - Union[analytics_admin.CreateCustomDimensionRequest, dict] + Union[ + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict + ] ] = None, *, parent: Optional[str] = None, - custom_dimension: Optional[resources.CustomDimension] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomDimension: - r"""Creates a CustomDimension. + ) -> pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: + r"""Lists DisplayVideo360AdvertiserLinkProposals on a + property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCustomDimensionRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict]]): The request object. Request message for - CreateCustomDimension RPC. + ListDisplayVideo360AdvertiserLinkProposals + RPC. parent (:class:`str`): Required. Example format: properties/1234 @@ -4888,13 +4910,6 @@ async def create_custom_dimension( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - custom_dimension (:class:`google.analytics.admin_v1alpha.types.CustomDimension`): - Required. The CustomDimension to - create. - - This corresponds to the ``custom_dimension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4902,13 +4917,18 @@ async def create_custom_dimension( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomDimension: - A definition for a CustomDimension. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: + Response message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. Iterating over this object will + yield results and resolve additional + pages automatically. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, custom_dimension]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4917,20 +4937,22 @@ async def create_custom_dimension( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): - request = analytics_admin.CreateCustomDimensionRequest(request) + if not isinstance( + request, analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest + ): + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if custom_dimension is not None: - request.custom_dimension = custom_dimension # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_custom_dimension + self._client._transport.list_display_video360_advertiser_link_proposals ] # Certain fields should be provided within the metadata header; @@ -4950,39 +4972,56 @@ async def create_custom_dimension( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def update_custom_dimension( + async def create_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.UpdateCustomDimensionRequest, dict] + Union[ + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict + ] ] = None, *, - custom_dimension: Optional[resources.CustomDimension] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, + display_video_360_advertiser_link_proposal: Optional[ + resources.DisplayVideo360AdvertiserLinkProposal + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomDimension: - r"""Updates a CustomDimension on a property. + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Creates a DisplayVideo360AdvertiserLinkProposal. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCustomDimensionRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]]): The request object. Request message for - UpdateCustomDimension RPC. - custom_dimension (:class:`google.analytics.admin_v1alpha.types.CustomDimension`): - The CustomDimension to update - This corresponds to the ``custom_dimension`` field + CreateDisplayVideo360AdvertiserLinkProposal + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + display_video_360_advertiser_link_proposal (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal`): + Required. The + DisplayVideo360AdvertiserLinkProposal to + create. - This corresponds to the ``update_mask`` field + This corresponds to the ``display_video_360_advertiser_link_proposal`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -4992,13 +5031,23 @@ async def update_custom_dimension( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomDimension: - A definition for a CustomDimension. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([custom_dimension, update_mask]) + has_flattened_params = any([parent, display_video_360_advertiser_link_proposal]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5007,28 +5056,34 @@ async def update_custom_dimension( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): - request = analytics_admin.UpdateCustomDimensionRequest(request) + if not isinstance( + request, analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if custom_dimension is not None: - request.custom_dimension = custom_dimension - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent + if display_video_360_advertiser_link_proposal is not None: + request.display_video_360_advertiser_link_proposal = ( + display_video_360_advertiser_link_proposal + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_custom_dimension + self._client._transport.create_display_video360_advertiser_link_proposal ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("custom_dimension.name", request.custom_dimension.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5045,28 +5100,34 @@ async def update_custom_dimension( # Done; return the response. return response - async def list_custom_dimensions( + async def delete_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.ListCustomDimensionsRequest, dict] + Union[ + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict + ] ] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCustomDimensionsAsyncPager: - r"""Lists CustomDimensions on a property. + ) -> None: + r"""Deletes a DisplayVideo360AdvertiserLinkProposal on a + property. This can only be used on cancelled proposals. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict]]): The request object. Request message for - ListCustomDimensions RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 + DeleteDisplayVideo360AdvertiserLinkProposal + RPC. + name (:class:`str`): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + delete. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 - This corresponds to the ``parent`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -5074,20 +5135,11 @@ async def list_custom_dimensions( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomDimensionsAsyncPager: - Response message for - ListCustomDimensions RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5096,107 +5148,95 @@ async def list_custom_dimensions( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): - request = analytics_admin.ListCustomDimensionsRequest(request) + if not isinstance( + request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_custom_dimensions + self._client._transport.delete_display_video360_advertiser_link_proposal ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCustomDimensionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def archive_custom_dimension( + async def approve_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.ArchiveCustomDimensionRequest, dict] + Union[ + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + dict, + ] ] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Archives a CustomDimension on a property. + ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + r"""Approves a DisplayVideo360AdvertiserLinkProposal. + The DisplayVideo360AdvertiserLinkProposal will be + deleted and a new DisplayVideo360AdvertiserLink will be + created. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveCustomDimensionRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]]): The request object. Request message for - ArchiveCustomDimension RPC. - name (:class:`str`): - Required. The name of the - CustomDimension to archive. Example - format: - properties/1234/customDimensions/5678 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + Response message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): - request = analytics_admin.ArchiveCustomDimensionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance( + request, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.archive_custom_dimension + self._client._transport.approve_display_video360_advertiser_link_proposal ] # Certain fields should be provided within the metadata header; @@ -5209,38 +5249,42 @@ async def archive_custom_dimension( self._client._validate_universe_domain() # Send the request. - await rpc( + response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - async def get_custom_dimension( + # Done; return the response. + return response + + async def cancel_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.GetCustomDimensionRequest, dict] + Union[ + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict + ] ] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomDimension: - r"""Lookup for a single CustomDimension. + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Cancels a DisplayVideo360AdvertiserLinkProposal. + Cancelling can mean either: + + - Declining a proposal initiated from Display & Video + 360 + - Withdrawing a proposal initiated from Google Analytics + After being cancelled, a proposal will eventually be + deleted automatically. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetCustomDimensionRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]]): The request object. Request message for - GetCustomDimension RPC. - name (:class:`str`): - Required. The name of the - CustomDimension to get. Example format: - properties/1234/customDimensions/5678 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + CancelDisplayVideo360AdvertiserLinkProposal + RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5248,33 +5292,35 @@ async def get_custom_dimension( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomDimension: - A definition for a CustomDimension. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetCustomDimensionRequest): - request = analytics_admin.GetCustomDimensionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance( + request, analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_custom_dimension + self._client._transport.cancel_display_video360_advertiser_link_proposal ] # Certain fields should be provided within the metadata header; @@ -5297,24 +5343,24 @@ async def get_custom_dimension( # Done; return the response. return response - async def create_custom_metric( + async def create_custom_dimension( self, request: Optional[ - Union[analytics_admin.CreateCustomMetricRequest, dict] + Union[analytics_admin.CreateCustomDimensionRequest, dict] ] = None, *, parent: Optional[str] = None, - custom_metric: Optional[resources.CustomMetric] = None, + custom_dimension: Optional[resources.CustomDimension] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomMetric: - r"""Creates a CustomMetric. + ) -> resources.CustomDimension: + r"""Creates a CustomDimension. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCustomMetricRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCustomDimensionRequest, dict]]): The request object. Request message for - CreateCustomMetric RPC. + CreateCustomDimension RPC. parent (:class:`str`): Required. Example format: properties/1234 @@ -5322,9 +5368,11 @@ async def create_custom_metric( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - custom_metric (:class:`google.analytics.admin_v1alpha.types.CustomMetric`): - Required. The CustomMetric to create. - This corresponds to the ``custom_metric`` field + custom_dimension (:class:`google.analytics.admin_v1alpha.types.CustomDimension`): + Required. The CustomDimension to + create. + + This corresponds to the ``custom_dimension`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -5334,13 +5382,13 @@ async def create_custom_metric( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomMetric: - A definition for a custom metric. + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, custom_metric]) + has_flattened_params = any([parent, custom_dimension]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5349,20 +5397,20 @@ async def create_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateCustomMetricRequest): - request = analytics_admin.CreateCustomMetricRequest(request) + if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): + request = analytics_admin.CreateCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if custom_metric is not None: - request.custom_metric = custom_metric + if custom_dimension is not None: + request.custom_dimension = custom_dimension # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_custom_metric + self._client._transport.create_custom_dimension ] # Certain fields should be provided within the metadata header; @@ -5385,27 +5433,27 @@ async def create_custom_metric( # Done; return the response. return response - async def update_custom_metric( + async def update_custom_dimension( self, request: Optional[ - Union[analytics_admin.UpdateCustomMetricRequest, dict] + Union[analytics_admin.UpdateCustomDimensionRequest, dict] ] = None, *, - custom_metric: Optional[resources.CustomMetric] = None, + custom_dimension: Optional[resources.CustomDimension] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomMetric: - r"""Updates a CustomMetric on a property. + ) -> resources.CustomDimension: + r"""Updates a CustomDimension on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCustomMetricRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCustomDimensionRequest, dict]]): The request object. Request message for - UpdateCustomMetric RPC. - custom_metric (:class:`google.analytics.admin_v1alpha.types.CustomMetric`): - The CustomMetric to update - This corresponds to the ``custom_metric`` field + UpdateCustomDimension RPC. + custom_dimension (:class:`google.analytics.admin_v1alpha.types.CustomDimension`): + The CustomDimension to update + This corresponds to the ``custom_dimension`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): @@ -5424,13 +5472,13 @@ async def update_custom_metric( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomMetric: - A definition for a custom metric. + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([custom_metric, update_mask]) + has_flattened_params = any([custom_dimension, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5439,27 +5487,27 @@ async def update_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): - request = analytics_admin.UpdateCustomMetricRequest(request) + if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): + request = analytics_admin.UpdateCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if custom_metric is not None: - request.custom_metric = custom_metric + if custom_dimension is not None: + request.custom_dimension = custom_dimension if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_custom_metric + self._client._transport.update_custom_dimension ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("custom_metric.name", request.custom_metric.name),) + (("custom_dimension.name", request.custom_dimension.name),) ), ) @@ -5477,21 +5525,23 @@ async def update_custom_metric( # Done; return the response. return response - async def list_custom_metrics( + async def list_custom_dimensions( self, - request: Optional[Union[analytics_admin.ListCustomMetricsRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ListCustomDimensionsRequest, dict] + ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCustomMetricsAsyncPager: - r"""Lists CustomMetrics on a property. + ) -> pagers.ListCustomDimensionsAsyncPager: + r"""Lists CustomDimensions on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListCustomMetricsRequest, dict]]): - The request object. Request message for ListCustomMetrics - RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest, dict]]): + The request object. Request message for + ListCustomDimensions RPC. parent (:class:`str`): Required. Example format: properties/1234 @@ -5506,9 +5556,9 @@ async def list_custom_metrics( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomMetricsAsyncPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomDimensionsAsyncPager: Response message for - ListCustomMetrics RPC. + ListCustomDimensions RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -5526,8 +5576,8 @@ async def list_custom_metrics( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListCustomMetricsRequest): - request = analytics_admin.ListCustomMetricsRequest(request) + if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): + request = analytics_admin.ListCustomDimensionsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -5537,7 +5587,7 @@ async def list_custom_metrics( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_custom_metrics + self._client._transport.list_custom_dimensions ] # Certain fields should be provided within the metadata header; @@ -5559,7 +5609,7 @@ async def list_custom_metrics( # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. - response = pagers.ListCustomMetricsAsyncPager( + response = pagers.ListCustomDimensionsAsyncPager( method=rpc, request=request, response=response, @@ -5571,10 +5621,10 @@ async def list_custom_metrics( # Done; return the response. return response - async def archive_custom_metric( + async def archive_custom_dimension( self, request: Optional[ - Union[analytics_admin.ArchiveCustomMetricRequest, dict] + Union[analytics_admin.ArchiveCustomDimensionRequest, dict] ] = None, *, name: Optional[str] = None, @@ -5582,16 +5632,17 @@ async def archive_custom_metric( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Archives a CustomMetric on a property. + r"""Archives a CustomDimension on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveCustomMetricRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveCustomDimensionRequest, dict]]): The request object. Request message for - ArchiveCustomMetric RPC. + ArchiveCustomDimension RPC. name (:class:`str`): Required. The name of the - CustomMetric to archive. Example format: - properties/1234/customMetrics/5678 + CustomDimension to archive. Example + format: + properties/1234/customDimensions/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -5614,8 +5665,8 @@ async def archive_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): - request = analytics_admin.ArchiveCustomMetricRequest(request) + if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): + request = analytics_admin.ArchiveCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -5625,7 +5676,7 @@ async def archive_custom_metric( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.archive_custom_metric + self._client._transport.archive_custom_dimension ] # Certain fields should be provided within the metadata header; @@ -5645,25 +5696,27 @@ async def archive_custom_metric( metadata=metadata, ) - async def get_custom_metric( + async def get_custom_dimension( self, - request: Optional[Union[analytics_admin.GetCustomMetricRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.GetCustomDimensionRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomMetric: - r"""Lookup for a single CustomMetric. + ) -> resources.CustomDimension: + r"""Lookup for a single CustomDimension. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetCustomMetricRequest, dict]]): - The request object. Request message for GetCustomMetric - RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetCustomDimensionRequest, dict]]): + The request object. Request message for + GetCustomDimension RPC. name (:class:`str`): Required. The name of the - CustomMetric to get. Example format: - properties/1234/customMetrics/5678 + CustomDimension to get. Example format: + properties/1234/customDimensions/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -5675,8 +5728,8 @@ async def get_custom_metric( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomMetric: - A definition for a custom metric. + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -5690,8 +5743,8 @@ async def get_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetCustomMetricRequest): - request = analytics_admin.GetCustomMetricRequest(request) + if not isinstance(request, analytics_admin.GetCustomDimensionRequest): + request = analytics_admin.GetCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -5701,7 +5754,7 @@ async def get_custom_metric( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_custom_metric + self._client._transport.get_custom_dimension ] # Certain fields should be provided within the metadata header; @@ -5724,33 +5777,34 @@ async def get_custom_metric( # Done; return the response. return response - async def get_data_retention_settings( + async def create_custom_metric( self, request: Optional[ - Union[analytics_admin.GetDataRetentionSettingsRequest, dict] + Union[analytics_admin.CreateCustomMetricRequest, dict] ] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + custom_metric: Optional[resources.CustomMetric] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataRetentionSettings: - r"""Returns the singleton data retention settings for - this property. + ) -> resources.CustomMetric: + r"""Creates a CustomMetric. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataRetentionSettingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCustomMetricRequest, dict]]): The request object. Request message for - GetDataRetentionSettings RPC. - name (:class:`str`): - Required. The name of the settings to - lookup. Format: - - properties/{property}/dataRetentionSettings - Example: - "properties/1000/dataRetentionSettings" + CreateCustomMetric RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_metric (:class:`google.analytics.admin_v1alpha.types.CustomMetric`): + Required. The CustomMetric to create. + This corresponds to the ``custom_metric`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -5760,15 +5814,13 @@ async def get_data_retention_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataRetentionSettings: - Settings values for data retention. - This is a singleton resource. - + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, custom_metric]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5777,24 +5829,26 @@ async def get_data_retention_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): - request = analytics_admin.GetDataRetentionSettingsRequest(request) + if not isinstance(request, analytics_admin.CreateCustomMetricRequest): + request = analytics_admin.CreateCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if custom_metric is not None: + request.custom_metric = custom_metric # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_data_retention_settings + self._client._transport.create_custom_metric ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5811,35 +5865,31 @@ async def get_data_retention_settings( # Done; return the response. return response - async def update_data_retention_settings( + async def update_custom_metric( self, request: Optional[ - Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict] + Union[analytics_admin.UpdateCustomMetricRequest, dict] ] = None, *, - data_retention_settings: Optional[resources.DataRetentionSettings] = None, + custom_metric: Optional[resources.CustomMetric] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataRetentionSettings: - r"""Updates the singleton data retention settings for - this property. + ) -> resources.CustomMetric: + r"""Updates a CustomMetric on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataRetentionSettingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCustomMetricRequest, dict]]): The request object. Request message for - UpdateDataRetentionSettings RPC. - data_retention_settings (:class:`google.analytics.admin_v1alpha.types.DataRetentionSettings`): - Required. The settings to update. The ``name`` field is - used to identify the settings to be updated. - - This corresponds to the ``data_retention_settings`` field + UpdateCustomMetric RPC. + custom_metric (:class:`google.analytics.admin_v1alpha.types.CustomMetric`): + The CustomMetric to update + This corresponds to the ``custom_metric`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted + Required. The list of fields to be updated. Omitted fields will not be updated. To replace the entire entity, use one path with the string "*" to match all fields. @@ -5854,15 +5904,13 @@ async def update_data_retention_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataRetentionSettings: - Settings values for data retention. - This is a singleton resource. - + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([data_retention_settings, update_mask]) + has_flattened_params = any([custom_metric, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5871,32 +5919,27 @@ async def update_data_retention_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): - request = analytics_admin.UpdateDataRetentionSettingsRequest(request) + if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): + request = analytics_admin.UpdateCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if data_retention_settings is not None: - request.data_retention_settings = data_retention_settings + if custom_metric is not None: + request.custom_metric = custom_metric if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_data_retention_settings + self._client._transport.update_custom_metric ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - ( - ( - "data_retention_settings.name", - request.data_retention_settings.name, - ), - ) + (("custom_metric.name", request.custom_metric.name),) ), ) @@ -5914,21 +5957,20 @@ async def update_data_retention_settings( # Done; return the response. return response - async def create_data_stream( + async def list_custom_metrics( self, - request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, + request: Optional[Union[analytics_admin.ListCustomMetricsRequest, dict]] = None, *, parent: Optional[str] = None, - data_stream: Optional[resources.DataStream] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataStream: - r"""Creates a DataStream. + ) -> pagers.ListCustomMetricsAsyncPager: + r"""Lists CustomMetrics on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDataStreamRequest, dict]]): - The request object. Request message for CreateDataStream + request (Optional[Union[google.analytics.admin_v1alpha.types.ListCustomMetricsRequest, dict]]): + The request object. Request message for ListCustomMetrics RPC. parent (:class:`str`): Required. Example format: @@ -5937,11 +5979,6 @@ async def create_data_stream( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - data_stream (:class:`google.analytics.admin_v1alpha.types.DataStream`): - Required. The DataStream to create. - This corresponds to the ``data_stream`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5949,15 +5986,18 @@ async def create_data_stream( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataStream: - A resource message representing a - data stream. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomMetricsAsyncPager: + Response message for + ListCustomMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, data_stream]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5966,20 +6006,18 @@ async def create_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateDataStreamRequest): - request = analytics_admin.CreateDataStreamRequest(request) + if not isinstance(request, analytics_admin.ListCustomMetricsRequest): + request = analytics_admin.ListCustomMetricsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if data_stream is not None: - request.data_stream = data_stream # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_data_stream + self._client._transport.list_custom_metrics ] # Certain fields should be provided within the metadata header; @@ -5999,28 +6037,41 @@ async def create_data_stream( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCustomMetricsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def delete_data_stream( + async def archive_custom_metric( self, - request: Optional[Union[analytics_admin.DeleteDataStreamRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ArchiveCustomMetricRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a DataStream on a property. + r"""Archives a CustomMetric on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDataStreamRequest, dict]]): - The request object. Request message for DeleteDataStream - RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveCustomMetricRequest, dict]]): + The request object. Request message for + ArchiveCustomMetric RPC. name (:class:`str`): - Required. The name of the DataStream - to delete. Example format: - properties/1234/dataStreams/5678 + Required. The name of the + CustomMetric to archive. Example format: + properties/1234/customMetrics/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -6043,8 +6094,8 @@ async def delete_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteDataStreamRequest): - request = analytics_admin.DeleteDataStreamRequest(request) + if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): + request = analytics_admin.ArchiveCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -6054,7 +6105,7 @@ async def delete_data_stream( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_data_stream + self._client._transport.archive_custom_metric ] # Certain fields should be provided within the metadata header; @@ -6074,34 +6125,27 @@ async def delete_data_stream( metadata=metadata, ) - async def update_data_stream( + async def get_custom_metric( self, - request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, + request: Optional[Union[analytics_admin.GetCustomMetricRequest, dict]] = None, *, - data_stream: Optional[resources.DataStream] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataStream: - r"""Updates a DataStream on a property. + ) -> resources.CustomMetric: + r"""Lookup for a single CustomMetric. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataStreamRequest, dict]]): - The request object. Request message for UpdateDataStream + request (Optional[Union[google.analytics.admin_v1alpha.types.GetCustomMetricRequest, dict]]): + The request object. Request message for GetCustomMetric RPC. - data_stream (:class:`google.analytics.admin_v1alpha.types.DataStream`): - The DataStream to update - This corresponds to the ``data_stream`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + name (:class:`str`): + Required. The name of the + CustomMetric to get. Example format: + properties/1234/customMetrics/5678 - This corresponds to the ``update_mask`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6111,15 +6155,13 @@ async def update_data_stream( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataStream: - A resource message representing a - data stream. - + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([data_stream, update_mask]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6128,28 +6170,24 @@ async def update_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateDataStreamRequest): - request = analytics_admin.UpdateDataStreamRequest(request) + if not isinstance(request, analytics_admin.GetCustomMetricRequest): + request = analytics_admin.GetCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if data_stream is not None: - request.data_stream = data_stream - if update_mask is not None: - request.update_mask = update_mask + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_data_stream + self._client._transport.get_custom_metric ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("data_stream.name", request.data_stream.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -6166,26 +6204,33 @@ async def update_data_stream( # Done; return the response. return response - async def list_data_streams( + async def get_data_retention_settings( self, - request: Optional[Union[analytics_admin.ListDataStreamsRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.GetDataRetentionSettingsRequest, dict] + ] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataStreamsAsyncPager: - r"""Lists DataStreams on a property. + ) -> resources.DataRetentionSettings: + r"""Returns the singleton data retention settings for + this property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListDataStreamsRequest, dict]]): - The request object. Request message for ListDataStreams - RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataRetentionSettingsRequest, dict]]): + The request object. Request message for + GetDataRetentionSettings RPC. + name (:class:`str`): + Required. The name of the settings to + lookup. Format: - This corresponds to the ``parent`` field + properties/{property}/dataRetentionSettings + Example: + "properties/1000/dataRetentionSettings" + + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6195,18 +6240,15 @@ async def list_data_streams( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDataStreamsAsyncPager: - Response message for ListDataStreams - RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6215,24 +6257,24 @@ async def list_data_streams( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListDataStreamsRequest): - request = analytics_admin.ListDataStreamsRequest(request) + if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): + request = analytics_admin.GetDataRetentionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_data_streams + self._client._transport.get_data_retention_settings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -6246,41 +6288,43 @@ async def list_data_streams( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDataStreamsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - async def get_data_stream( + async def update_data_retention_settings( self, - request: Optional[Union[analytics_admin.GetDataStreamRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict] + ] = None, *, - name: Optional[str] = None, + data_retention_settings: Optional[resources.DataRetentionSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataStream: - r"""Lookup for a single DataStream. + ) -> resources.DataRetentionSettings: + r"""Updates the singleton data retention settings for + this property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataStreamRequest, dict]]): - The request object. Request message for GetDataStream - RPC. - name (:class:`str`): - Required. The name of the DataStream - to get. Example format: - properties/1234/dataStreams/5678 + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataRetentionSettingsRequest, dict]]): + The request object. Request message for + UpdateDataRetentionSettings RPC. + data_retention_settings (:class:`google.analytics.admin_v1alpha.types.DataRetentionSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. - This corresponds to the ``name`` field + This corresponds to the ``data_retention_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6290,15 +6334,15 @@ async def get_data_stream( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataStream: - A resource message representing a - data stream. + google.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([data_retention_settings, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6307,24 +6351,33 @@ async def get_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetDataStreamRequest): - request = analytics_admin.GetDataStreamRequest(request) + if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): + request = analytics_admin.UpdateDataRetentionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if data_retention_settings is not None: + request.data_retention_settings = data_retention_settings + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_data_stream + self._client._transport.update_data_retention_settings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "data_retention_settings.name", + request.data_retention_settings.name, + ), + ) + ), ) # Validate the universe domain. @@ -6341,28 +6394,32 @@ async def get_data_stream( # Done; return the response. return response - async def get_audience( + async def create_data_stream( self, - request: Optional[Union[analytics_admin.GetAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + data_stream: Optional[resources.DataStream] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> audience.Audience: - r"""Lookup for a single Audience. - Audiences created before 2020 may not be supported. - Default audiences will not show filter definitions. + ) -> resources.DataStream: + r"""Creates a DataStream. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetAudienceRequest, dict]]): - The request object. Request message for GetAudience RPC. - name (:class:`str`): - Required. The name of the Audience to - get. Example format: - properties/1234/audiences/5678 + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDataStreamRequest, dict]]): + The request object. Request message for CreateDataStream + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_stream (:class:`google.analytics.admin_v1alpha.types.DataStream`): + Required. The DataStream to create. + This corresponds to the ``data_stream`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6372,15 +6429,15 @@ async def get_audience( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.Audience: - A resource message representing a GA4 - Audience. + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, data_stream]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6389,24 +6446,26 @@ async def get_audience( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAudienceRequest): - request = analytics_admin.GetAudienceRequest(request) + if not isinstance(request, analytics_admin.CreateDataStreamRequest): + request = analytics_admin.CreateDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if data_stream is not None: + request.data_stream = data_stream # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_audience + self._client._transport.create_data_stream ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -6423,28 +6482,27 @@ async def get_audience( # Done; return the response. return response - async def list_audiences( + async def delete_data_stream( self, - request: Optional[Union[analytics_admin.ListAudiencesRequest, dict]] = None, + request: Optional[Union[analytics_admin.DeleteDataStreamRequest, dict]] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAudiencesAsyncPager: - r"""Lists Audiences on a property. - Audiences created before 2020 may not be supported. - Default audiences will not show filter definitions. + ) -> None: + r"""Deletes a DataStream on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListAudiencesRequest, dict]]): - The request object. Request message for ListAudiences + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDataStreamRequest, dict]]): + The request object. Request message for DeleteDataStream RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 + name (:class:`str`): + Required. The name of the DataStream + to delete. Example format: + properties/1234/dataStreams/5678 - This corresponds to the ``parent`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6452,20 +6510,11 @@ async def list_audiences( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAudiencesAsyncPager: - Response message for ListAudiences - RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6474,77 +6523,65 @@ async def list_audiences( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListAudiencesRequest): - request = analytics_admin.ListAudiencesRequest(request) + if not isinstance(request, analytics_admin.DeleteDataStreamRequest): + request = analytics_admin.DeleteDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_audiences + self._client._transport.delete_data_stream ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAudiencesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_audience( + async def update_data_stream( self, - request: Optional[Union[analytics_admin.CreateAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, *, - parent: Optional[str] = None, - audience: Optional[gaa_audience.Audience] = None, + data_stream: Optional[resources.DataStream] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_audience.Audience: - r"""Creates an Audience. + ) -> resources.DataStream: + r"""Updates a DataStream on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAudienceRequest, dict]]): - The request object. Request message for CreateAudience + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataStreamRequest, dict]]): + The request object. Request message for UpdateDataStream RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 - - This corresponds to the ``parent`` field + data_stream (:class:`google.analytics.admin_v1alpha.types.DataStream`): + The DataStream to update + This corresponds to the ``data_stream`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - audience (:class:`google.analytics.admin_v1alpha.types.Audience`): - Required. The audience to create. - This corresponds to the ``audience`` field + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6554,15 +6591,15 @@ async def create_audience( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.Audience: - A resource message representing a GA4 - Audience. + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, audience]) + has_flattened_params = any([data_stream, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6571,26 +6608,28 @@ async def create_audience( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateAudienceRequest): - request = analytics_admin.CreateAudienceRequest(request) + if not isinstance(request, analytics_admin.UpdateDataStreamRequest): + request = analytics_admin.UpdateDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent - if audience is not None: - request.audience = audience + if data_stream is not None: + request.data_stream = data_stream + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_audience + self._client._transport.update_data_stream ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("data_stream.name", request.data_stream.name),) + ), ) # Validate the universe domain. @@ -6607,38 +6646,26 @@ async def create_audience( # Done; return the response. return response - async def update_audience( + async def list_data_streams( self, - request: Optional[Union[analytics_admin.UpdateAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.ListDataStreamsRequest, dict]] = None, *, - audience: Optional[gaa_audience.Audience] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_audience.Audience: - r"""Updates an Audience on a property. + ) -> pagers.ListDataStreamsAsyncPager: + r"""Lists DataStreams on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAudienceRequest, dict]]): - The request object. Request message for UpdateAudience + request (Optional[Union[google.analytics.admin_v1alpha.types.ListDataStreamsRequest, dict]]): + The request object. Request message for ListDataStreams RPC. - audience (:class:`google.analytics.admin_v1alpha.types.Audience`): - Required. The audience to update. The audience's - ``name`` field is used to identify the audience to be - updated. - - This corresponds to the ``audience`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + parent (:class:`str`): + Required. Example format: + properties/1234 - This corresponds to the ``update_mask`` field + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6648,15 +6675,18 @@ async def update_audience( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.Audience: - A resource message representing a GA4 - Audience. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDataStreamsAsyncPager: + Response message for ListDataStreams + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([audience, update_mask]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6665,28 +6695,24 @@ async def update_audience( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateAudienceRequest): - request = analytics_admin.UpdateAudienceRequest(request) + if not isinstance(request, analytics_admin.ListDataStreamsRequest): + request = analytics_admin.ListDataStreamsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if audience is not None: - request.audience = audience - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_audience + self._client._transport.list_data_streams ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("audience.name", request.audience.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -6700,79 +6726,39 @@ async def update_audience( metadata=metadata, ) - # Done; return the response. - return response - - async def archive_audience( - self, - request: Optional[Union[analytics_admin.ArchiveAudienceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Archives an Audience on a property. - - Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveAudienceRequest, dict]]): - The request object. Request message for ArchiveAudience - RPC. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ArchiveAudienceRequest): - request = analytics_admin.ArchiveAudienceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[ - self._client._transport.archive_audience - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc( - request, + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataStreamsAsyncPager( + method=rpc, + request=request, + response=response, retry=retry, timeout=timeout, metadata=metadata, ) - async def get_search_ads360_link( + # Done; return the response. + return response + + async def get_data_stream( self, - request: Optional[ - Union[analytics_admin.GetSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetDataStreamRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.SearchAds360Link: - r"""Look up a single SearchAds360Link + ) -> resources.DataStream: + r"""Lookup for a single DataStream. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetSearchAds360LinkRequest, dict]]): - The request object. Request message for - GetSearchAds360Link RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataStreamRequest, dict]]): + The request object. Request message for GetDataStream + RPC. name (:class:`str`): - Required. The name of the - SearchAds360Link to get. Example format: - properties/1234/SearchAds360Link/5678 + Required. The name of the DataStream + to get. Example format: + properties/1234/dataStreams/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -6784,9 +6770,9 @@ async def get_search_ads360_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SearchAds360Link: - A link between a GA4 property and a - Search Ads 360 entity. + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. """ # Create or coerce a protobuf request object. @@ -6801,8 +6787,8 @@ async def get_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetSearchAds360LinkRequest): - request = analytics_admin.GetSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.GetDataStreamRequest): + request = analytics_admin.GetDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -6812,7 +6798,7 @@ async def get_search_ads360_link( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_search_ads360_link + self._client._transport.get_data_stream ] # Certain fields should be provided within the metadata header; @@ -6835,28 +6821,28 @@ async def get_search_ads360_link( # Done; return the response. return response - async def list_search_ads360_links( + async def get_audience( self, - request: Optional[ - Union[analytics_admin.ListSearchAds360LinksRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetAudienceRequest, dict]] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSearchAds360LinksAsyncPager: - r"""Lists all SearchAds360Links on a property. + ) -> audience.Audience: + r"""Lookup for a single Audience. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest, dict]]): - The request object. Request message for - ListSearchAds360Links RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAudienceRequest, dict]]): + The request object. Request message for GetAudience RPC. + name (:class:`str`): + Required. The name of the Audience to + get. Example format: + properties/1234/audiences/5678 - This corresponds to the ``parent`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -6866,18 +6852,15 @@ async def list_search_ads360_links( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSearchAds360LinksAsyncPager: - Response message for - ListSearchAds360Links RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6886,24 +6869,24 @@ async def list_search_ads360_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListSearchAds360LinksRequest): - request = analytics_admin.ListSearchAds360LinksRequest(request) + if not isinstance(request, analytics_admin.GetAudienceRequest): + request = analytics_admin.GetAudienceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_search_ads360_links + self._client._transport.get_audience ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -6917,38 +6900,26 @@ async def list_search_ads360_links( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSearchAds360LinksAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - async def create_search_ads360_link( + async def list_audiences( self, - request: Optional[ - Union[analytics_admin.CreateSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListAudiencesRequest, dict]] = None, *, parent: Optional[str] = None, - search_ads_360_link: Optional[resources.SearchAds360Link] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.SearchAds360Link: - r"""Creates a SearchAds360Link. + ) -> pagers.ListAudiencesAsyncPager: + r"""Lists Audiences on a property. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateSearchAds360LinkRequest, dict]]): - The request object. Request message for - CreateSearchAds360Link RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAudiencesRequest, dict]]): + The request object. Request message for ListAudiences + RPC. parent (:class:`str`): Required. Example format: properties/1234 @@ -6956,13 +6927,6 @@ async def create_search_ads360_link( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - search_ads_360_link (:class:`google.analytics.admin_v1alpha.types.SearchAds360Link`): - Required. The SearchAds360Link to - create. - - This corresponds to the ``search_ads_360_link`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6970,15 +6934,18 @@ async def create_search_ads360_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SearchAds360Link: - A link between a GA4 property and a - Search Ads 360 entity. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAudiencesAsyncPager: + Response message for ListAudiences + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, search_ads_360_link]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6987,20 +6954,18 @@ async def create_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateSearchAds360LinkRequest): - request = analytics_admin.CreateSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.ListAudiencesRequest): + request = analytics_admin.ListAudiencesRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if search_ads_360_link is not None: - request.search_ads_360_link = search_ads_360_link # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_search_ads360_link + self._client._transport.list_audiences ] # Certain fields should be provided within the metadata header; @@ -7020,33 +6985,46 @@ async def create_search_ads360_link( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAudiencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def delete_search_ads360_link( + async def create_audience( self, - request: Optional[ - Union[analytics_admin.DeleteSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.CreateAudienceRequest, dict]] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + audience: Optional[gaa_audience.Audience] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a SearchAds360Link on a property. + ) -> gaa_audience.Audience: + r"""Creates an Audience. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteSearchAds360LinkRequest, dict]]): - The request object. Request message for - DeleteSearchAds360Link RPC. - name (:class:`str`): - Required. The name of the - SearchAds360Link to delete. Example - format: - properties/1234/SearchAds360Links/5678 + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAudienceRequest, dict]]): + The request object. Request message for CreateAudience + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audience (:class:`google.analytics.admin_v1alpha.types.Audience`): + Required. The audience to create. + This corresponds to the ``audience`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -7054,11 +7032,17 @@ async def delete_search_ads360_link( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, audience]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7067,62 +7051,69 @@ async def delete_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteSearchAds360LinkRequest): - request = analytics_admin.DeleteSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.CreateAudienceRequest): + request = analytics_admin.CreateAudienceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if audience is not None: + request.audience = audience # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_search_ads360_link + self._client._transport.create_audience ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc( + response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - async def update_search_ads360_link( + # Done; return the response. + return response + + async def update_audience( self, - request: Optional[ - Union[analytics_admin.UpdateSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.UpdateAudienceRequest, dict]] = None, *, - search_ads_360_link: Optional[resources.SearchAds360Link] = None, + audience: Optional[gaa_audience.Audience] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.SearchAds360Link: - r"""Updates a SearchAds360Link on a property. + ) -> gaa_audience.Audience: + r"""Updates an Audience on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateSearchAds360LinkRequest, dict]]): - The request object. Request message for - UpdateSearchAds360Link RPC. - search_ads_360_link (:class:`google.analytics.admin_v1alpha.types.SearchAds360Link`): - The SearchAds360Link to update - This corresponds to the ``search_ads_360_link`` field + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAudienceRequest, dict]]): + The request object. Request message for UpdateAudience + RPC. + audience (:class:`google.analytics.admin_v1alpha.types.Audience`): + Required. The audience to update. The audience's + ``name`` field is used to identify the audience to be + updated. + + This corresponds to the ``audience`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Omitted + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted fields will not be updated. To replace the entire entity, use one path with the string "*" to match all fields. @@ -7137,15 +7128,15 @@ async def update_search_ads360_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SearchAds360Link: - A link between a GA4 property and a - Search Ads 360 entity. + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([search_ads_360_link, update_mask]) + has_flattened_params = any([audience, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7154,27 +7145,27 @@ async def update_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateSearchAds360LinkRequest): - request = analytics_admin.UpdateSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.UpdateAudienceRequest): + request = analytics_admin.UpdateAudienceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if search_ads_360_link is not None: - request.search_ads_360_link = search_ads_360_link + if audience is not None: + request.audience = audience if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_search_ads360_link + self._client._transport.update_audience ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("search_ads_360_link.name", request.search_ads_360_link.name),) + (("audience.name", request.audience.name),) ), ) @@ -7192,68 +7183,36 @@ async def update_search_ads360_link( # Done; return the response. return response - async def get_attribution_settings( + async def archive_audience( self, - request: Optional[ - Union[analytics_admin.GetAttributionSettingsRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ArchiveAudienceRequest, dict]] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AttributionSettings: - r"""Lookup for a AttributionSettings singleton. + ) -> None: + r"""Archives an Audience on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetAttributionSettingsRequest, dict]]): - The request object. Request message for - GetAttributionSettings RPC. - name (:class:`str`): - Required. The name of the attribution - settings to retrieve. Format: - properties/{property}/attributionSettings - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveAudienceRequest, dict]]): + The request object. Request message for ArchiveAudience + RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.AttributionSettings: - The attribution settings used for a - given property. This is a singleton - resource. - """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAttributionSettingsRequest): - request = analytics_admin.GetAttributionSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance(request, analytics_admin.ArchiveAudienceRequest): + request = analytics_admin.ArchiveAudienceRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_attribution_settings + self._client._transport.archive_audience ] # Certain fields should be provided within the metadata header; @@ -7266,50 +7225,36 @@ async def get_attribution_settings( self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - async def update_attribution_settings( + async def get_search_ads360_link( self, request: Optional[ - Union[analytics_admin.UpdateAttributionSettingsRequest, dict] + Union[analytics_admin.GetSearchAds360LinkRequest, dict] ] = None, *, - attribution_settings: Optional[resources.AttributionSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AttributionSettings: - r"""Updates attribution settings on a property. + ) -> resources.SearchAds360Link: + r"""Look up a single SearchAds360Link Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAttributionSettingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.GetSearchAds360LinkRequest, dict]]): The request object. Request message for - UpdateAttributionSettings RPC - attribution_settings (:class:`google.analytics.admin_v1alpha.types.AttributionSettings`): - Required. The attribution settings to update. The - ``name`` field is used to identify the settings to be - updated. - - This corresponds to the ``attribution_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + GetSearchAds360Link RPC. + name (:class:`str`): + Required. The name of the + SearchAds360Link to get. Example format: + properties/1234/SearchAds360Link/5678 - This corresponds to the ``update_mask`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -7319,16 +7264,15 @@ async def update_attribution_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AttributionSettings: - The attribution settings used for a - given property. This is a singleton - resource. + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([attribution_settings, update_mask]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7337,28 +7281,24 @@ async def update_attribution_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateAttributionSettingsRequest): - request = analytics_admin.UpdateAttributionSettingsRequest(request) + if not isinstance(request, analytics_admin.GetSearchAds360LinkRequest): + request = analytics_admin.GetSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if attribution_settings is not None: - request.attribution_settings = attribution_settings - if update_mask is not None: - request.update_mask = update_mask + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_attribution_settings + self._client._transport.get_search_ads360_link ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("attribution_settings.name", request.attribution_settings.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -7375,35 +7315,30 @@ async def update_attribution_settings( # Done; return the response. return response - async def run_access_report( + async def list_search_ads360_links( self, - request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ListSearchAds360LinksRequest, dict] + ] = None, *, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.RunAccessReportResponse: - r"""Returns a customized report of data access records. The report - provides records of each time a user reads Google Analytics - reporting data. Access records are retained for up to 2 years. - - Data Access Reports can be requested for a property. Reports may - be requested for any property, but dimensions that aren't - related to quota can only be requested on Google Analytics 360 - properties. This method is only available to Administrators. - - These data access records include GA4 UI Reporting, GA4 UI - Explorations, GA4 Data API, and other products like Firebase & - Admob that can retrieve data from Google Analytics through a - linkage. These records don't include property configuration - changes like adding a stream or changing a property's time zone. - For configuration change history, see - `searchChangeHistoryEvents `__. + ) -> pagers.ListSearchAds360LinksAsyncPager: + r"""Lists all SearchAds360Links on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.RunAccessReportRequest, dict]]): - The request object. The request for a Data Access Record - Report. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest, dict]]): + The request object. Request message for + ListSearchAds360Links RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7411,27 +7346,44 @@ async def run_access_report( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.RunAccessReportResponse: - The customized Data Access Record - Report response. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSearchAds360LinksAsyncPager: + Response message for + ListSearchAds360Links RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.RunAccessReportRequest): - request = analytics_admin.RunAccessReportRequest(request) + if not isinstance(request, analytics_admin.ListSearchAds360LinksRequest): + request = analytics_admin.ListSearchAds360LinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.run_access_report + self._client._transport.list_search_ads360_links ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("entity", request.entity),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -7445,41 +7397,50 @@ async def run_access_report( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSearchAds360LinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def create_access_binding( + async def create_search_ads360_link( self, request: Optional[ - Union[analytics_admin.CreateAccessBindingRequest, dict] + Union[analytics_admin.CreateSearchAds360LinkRequest, dict] ] = None, *, parent: Optional[str] = None, - access_binding: Optional[resources.AccessBinding] = None, + search_ads_360_link: Optional[resources.SearchAds360Link] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AccessBinding: - r"""Creates an access binding on an account or property. + ) -> resources.SearchAds360Link: + r"""Creates a SearchAds360Link. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateSearchAds360LinkRequest, dict]]): The request object. Request message for - CreateAccessBinding RPC. + CreateSearchAds360Link RPC. parent (:class:`str`): - Required. Formats: - - - accounts/{account} - - properties/{property} + Required. Example format: + properties/1234 This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - access_binding (:class:`google.analytics.admin_v1alpha.types.AccessBinding`): - Required. The access binding to + search_ads_360_link (:class:`google.analytics.admin_v1alpha.types.SearchAds360Link`): + Required. The SearchAds360Link to create. - This corresponds to the ``access_binding`` field + This corresponds to the ``search_ads_360_link`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -7489,15 +7450,15 @@ async def create_access_binding( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AccessBinding: - A binding of a user to a set of - roles. + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, access_binding]) + has_flattened_params = any([parent, search_ads_360_link]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7506,20 +7467,20 @@ async def create_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateAccessBindingRequest): - request = analytics_admin.CreateAccessBindingRequest(request) + if not isinstance(request, analytics_admin.CreateSearchAds360LinkRequest): + request = analytics_admin.CreateSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if access_binding is not None: - request.access_binding = access_binding + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_access_binding + self._client._transport.create_search_ads360_link ] # Certain fields should be provided within the metadata header; @@ -7542,29 +7503,28 @@ async def create_access_binding( # Done; return the response. return response - async def get_access_binding( + async def delete_search_ads360_link( self, - request: Optional[Union[analytics_admin.GetAccessBindingRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.DeleteSearchAds360LinkRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AccessBinding: - r"""Gets information about an access binding. + ) -> None: + r"""Deletes a SearchAds360Link on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetAccessBindingRequest, dict]]): - The request object. Request message for GetAccessBinding - RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteSearchAds360LinkRequest, dict]]): + The request object. Request message for + DeleteSearchAds360Link RPC. name (:class:`str`): - Required. The name of the access - binding to retrieve. Formats: - - - - accounts/{account}/accessBindings/{accessBinding} - - - properties/{property}/accessBindings/{accessBinding} + Required. The name of the + SearchAds360Link to delete. Example + format: + properties/1234/SearchAds360Links/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -7574,12 +7534,6 @@ async def get_access_binding( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.AccessBinding: - A binding of a user to a set of - roles. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -7593,8 +7547,8 @@ async def get_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAccessBindingRequest): - request = analytics_admin.GetAccessBindingRequest(request) + if not isinstance(request, analytics_admin.DeleteSearchAds360LinkRequest): + request = analytics_admin.DeleteSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -7604,7 +7558,7 @@ async def get_access_binding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_access_binding + self._client._transport.delete_search_ads360_link ] # Certain fields should be provided within the metadata header; @@ -7617,38 +7571,43 @@ async def get_access_binding( self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - async def update_access_binding( + async def update_search_ads360_link( self, request: Optional[ - Union[analytics_admin.UpdateAccessBindingRequest, dict] + Union[analytics_admin.UpdateSearchAds360LinkRequest, dict] ] = None, *, - access_binding: Optional[resources.AccessBinding] = None, + search_ads_360_link: Optional[resources.SearchAds360Link] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AccessBinding: - r"""Updates an access binding on an account or property. + ) -> resources.SearchAds360Link: + r"""Updates a SearchAds360Link on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateSearchAds360LinkRequest, dict]]): The request object. Request message for - UpdateAccessBinding RPC. - access_binding (:class:`google.analytics.admin_v1alpha.types.AccessBinding`): - Required. The access binding to - update. + UpdateSearchAds360Link RPC. + search_ads_360_link (:class:`google.analytics.admin_v1alpha.types.SearchAds360Link`): + The SearchAds360Link to update + This corresponds to the ``search_ads_360_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. - This corresponds to the ``access_binding`` field + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -7658,15 +7617,15 @@ async def update_access_binding( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AccessBinding: - A binding of a user to a set of - roles. + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([access_binding]) + has_flattened_params = any([search_ads_360_link, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7675,25 +7634,27 @@ async def update_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateAccessBindingRequest): - request = analytics_admin.UpdateAccessBindingRequest(request) + if not isinstance(request, analytics_admin.UpdateSearchAds360LinkRequest): + request = analytics_admin.UpdateSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if access_binding is not None: - request.access_binding = access_binding + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_access_binding + self._client._transport.update_search_ads360_link ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("access_binding.name", request.access_binding.name),) + (("search_ads_360_link.name", request.search_ads_360_link.name),) ), ) @@ -7711,30 +7672,27 @@ async def update_access_binding( # Done; return the response. return response - async def delete_access_binding( + async def get_attribution_settings( self, request: Optional[ - Union[analytics_admin.DeleteAccessBindingRequest, dict] + Union[analytics_admin.GetAttributionSettingsRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an access binding on an account or property. + ) -> resources.AttributionSettings: + r"""Lookup for a AttributionSettings singleton. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAttributionSettingsRequest, dict]]): The request object. Request message for - DeleteAccessBinding RPC. + GetAttributionSettings RPC. name (:class:`str`): - Required. Formats: - - - - accounts/{account}/accessBindings/{accessBinding} - - - properties/{property}/accessBindings/{accessBinding} + Required. The name of the attribution + settings to retrieve. Format: + properties/{property}/attributionSettings This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -7744,6 +7702,13 @@ async def delete_access_binding( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -7757,8 +7722,8 @@ async def delete_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteAccessBindingRequest): - request = analytics_admin.DeleteAccessBindingRequest(request) + if not isinstance(request, analytics_admin.GetAttributionSettingsRequest): + request = analytics_admin.GetAttributionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -7768,7 +7733,7 @@ async def delete_access_binding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_access_binding + self._client._transport.get_attribution_settings ] # Certain fields should be provided within the metadata header; @@ -7781,37 +7746,50 @@ async def delete_access_binding( self._client._validate_universe_domain() # Send the request. - await rpc( + response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - async def list_access_bindings( + # Done; return the response. + return response + + async def update_attribution_settings( self, request: Optional[ - Union[analytics_admin.ListAccessBindingsRequest, dict] + Union[analytics_admin.UpdateAttributionSettingsRequest, dict] ] = None, *, - parent: Optional[str] = None, + attribution_settings: Optional[resources.AttributionSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAccessBindingsAsyncPager: - r"""Lists all access bindings on an account or property. + ) -> resources.AttributionSettings: + r"""Updates attribution settings on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListAccessBindingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAttributionSettingsRequest, dict]]): The request object. Request message for - ListAccessBindings RPC. - parent (:class:`str`): - Required. Formats: + UpdateAttributionSettings RPC + attribution_settings (:class:`google.analytics.admin_v1alpha.types.AttributionSettings`): + Required. The attribution settings to update. The + ``name`` field is used to identify the settings to be + updated. - - accounts/{account} - - properties/{property} + This corresponds to the ``attribution_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. - This corresponds to the ``parent`` field + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -7821,18 +7799,16 @@ async def list_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccessBindingsAsyncPager: - Response message for - ListAccessBindings RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([attribution_settings, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7841,24 +7817,28 @@ async def list_access_bindings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListAccessBindingsRequest): - request = analytics_admin.ListAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.UpdateAttributionSettingsRequest): + request = analytics_admin.UpdateAttributionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if attribution_settings is not None: + request.attribution_settings = attribution_settings + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_access_bindings + self._client._transport.update_attribution_settings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("attribution_settings.name", request.attribution_settings.name),) + ), ) # Validate the universe domain. @@ -7872,41 +7852,38 @@ async def list_access_bindings( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAccessBindingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - async def batch_create_access_bindings( + async def run_access_report( self, - request: Optional[ - Union[analytics_admin.BatchCreateAccessBindingsRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.BatchCreateAccessBindingsResponse: - r"""Creates information about multiple access bindings to - an account or property. + ) -> analytics_admin.RunAccessReportResponse: + r"""Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. - This method is transactional. If any AccessBinding - cannot be created, none of the AccessBindings will be - created. + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsRequest, dict]]): - The request object. Request message for - BatchCreateAccessBindings RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.RunAccessReportRequest, dict]]): + The request object. The request for a Data Access Record + Report. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7914,27 +7891,27 @@ async def batch_create_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsResponse: - Response message for - BatchCreateAccessBindings RPC. + google.analytics.admin_v1alpha.types.RunAccessReportResponse: + The customized Data Access Record + Report response. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchCreateAccessBindingsRequest): - request = analytics_admin.BatchCreateAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.RunAccessReportRequest): + request = analytics_admin.RunAccessReportRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_create_access_bindings + self._client._transport.run_access_report ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("entity", request.entity),)), ) # Validate the universe domain. @@ -7951,23 +7928,40 @@ async def batch_create_access_bindings( # Done; return the response. return response - async def batch_get_access_bindings( + async def create_access_binding( self, request: Optional[ - Union[analytics_admin.BatchGetAccessBindingsRequest, dict] + Union[analytics_admin.CreateAccessBindingRequest, dict] ] = None, *, + parent: Optional[str] = None, + access_binding: Optional[resources.AccessBinding] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.BatchGetAccessBindingsResponse: - r"""Gets information about multiple access bindings to an - account or property. + ) -> resources.AccessBinding: + r"""Creates an access binding on an account or property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.BatchGetAccessBindingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest, dict]]): The request object. Request message for - BatchGetAccessBindings RPC. + CreateAccessBinding RPC. + parent (:class:`str`): + Required. Formats: + + - accounts/{account} + - properties/{property} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + access_binding (:class:`google.analytics.admin_v1alpha.types.AccessBinding`): + Required. The access binding to + create. + + This corresponds to the ``access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7975,21 +7969,37 @@ async def batch_get_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BatchGetAccessBindingsResponse: - Response message for - BatchGetAccessBindings RPC. + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. """ # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchGetAccessBindingsRequest): - request = analytics_admin.BatchGetAccessBindingsRequest(request) + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, access_binding]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAccessBindingRequest): + request = analytics_admin.CreateAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if access_binding is not None: + request.access_binding = access_binding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_get_access_bindings + self._client._transport.create_access_binding ] # Certain fields should be provided within the metadata header; @@ -8012,23 +8022,33 @@ async def batch_get_access_bindings( # Done; return the response. return response - async def batch_update_access_bindings( + async def get_access_binding( self, - request: Optional[ - Union[analytics_admin.BatchUpdateAccessBindingsRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetAccessBindingRequest, dict]] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.BatchUpdateAccessBindingsResponse: - r"""Updates information about multiple access bindings to - an account or property. + ) -> resources.AccessBinding: + r"""Gets information about an access binding. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsRequest, dict]]): - The request object. Request message for - BatchUpdateAccessBindings RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAccessBindingRequest, dict]]): + The request object. Request message for GetAccessBinding + RPC. + name (:class:`str`): + Required. The name of the access + binding to retrieve. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8036,27 +8056,41 @@ async def batch_update_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsResponse: - Response message for - BatchUpdateAccessBindings RPC. + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchUpdateAccessBindingsRequest): - request = analytics_admin.BatchUpdateAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.GetAccessBindingRequest): + request = analytics_admin.GetAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_update_access_bindings + self._client._transport.get_access_binding ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -8073,79 +8107,114 @@ async def batch_update_access_bindings( # Done; return the response. return response - async def batch_delete_access_bindings( + async def update_access_binding( self, request: Optional[ - Union[analytics_admin.BatchDeleteAccessBindingsRequest, dict] + Union[analytics_admin.UpdateAccessBindingRequest, dict] ] = None, *, + access_binding: Optional[resources.AccessBinding] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes information about multiple users' links to an - account or property. + ) -> resources.AccessBinding: + r"""Updates an access binding on an account or property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.BatchDeleteAccessBindingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest, dict]]): The request object. Request message for - BatchDeleteAccessBindings RPC. + UpdateAccessBinding RPC. + access_binding (:class:`google.analytics.admin_v1alpha.types.AccessBinding`): + Required. The access binding to + update. + + This corresponds to the ``access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([access_binding]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchDeleteAccessBindingsRequest): - request = analytics_admin.BatchDeleteAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.UpdateAccessBindingRequest): + request = analytics_admin.UpdateAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if access_binding is not None: + request.access_binding = access_binding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.batch_delete_access_bindings + self._client._transport.update_access_binding ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("access_binding.name", request.access_binding.name),) + ), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc( + response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - async def get_expanded_data_set( + # Done; return the response. + return response + + async def delete_access_binding( self, request: Optional[ - Union[analytics_admin.GetExpandedDataSetRequest, dict] + Union[analytics_admin.DeleteAccessBindingRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> expanded_data_set.ExpandedDataSet: - r"""Lookup for a single ExpandedDataSet. + ) -> None: + r"""Deletes an access binding on an account or property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetExpandedDataSetRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest, dict]]): The request object. Request message for - GetExpandedDataSet RPC. + DeleteAccessBinding RPC. name (:class:`str`): - Required. The name of the - ExpandedDataSet to get. Example format: - properties/1234/expandedDataSets/5678 + Required. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -8155,12 +8224,6 @@ async def get_expanded_data_set( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.ExpandedDataSet: - A resource message representing a GA4 - ExpandedDataSet. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -8174,8 +8237,8 @@ async def get_expanded_data_set( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetExpandedDataSetRequest): - request = analytics_admin.GetExpandedDataSetRequest(request) + if not isinstance(request, analytics_admin.DeleteAccessBindingRequest): + request = analytics_admin.DeleteAccessBindingRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -8185,7 +8248,7 @@ async def get_expanded_data_set( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_expanded_data_set + self._client._transport.delete_access_binding ] # Certain fields should be provided within the metadata header; @@ -8198,36 +8261,35 @@ async def get_expanded_data_set( self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - async def list_expanded_data_sets( + async def list_access_bindings( self, request: Optional[ - Union[analytics_admin.ListExpandedDataSetsRequest, dict] + Union[analytics_admin.ListAccessBindingsRequest, dict] ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExpandedDataSetsAsyncPager: - r"""Lists ExpandedDataSets on a property. + ) -> pagers.ListAccessBindingsAsyncPager: + r"""Lists all access bindings on an account or property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAccessBindingsRequest, dict]]): The request object. Request message for - ListExpandedDataSets RPC. + ListAccessBindings RPC. parent (:class:`str`): - Required. Example format: - properties/1234 + Required. Formats: + + - accounts/{account} + - properties/{property} This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -8239,9 +8301,9 @@ async def list_expanded_data_sets( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListExpandedDataSetsAsyncPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccessBindingsAsyncPager: Response message for - ListExpandedDataSets RPC. + ListAccessBindings RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -8259,8 +8321,8 @@ async def list_expanded_data_sets( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListExpandedDataSetsRequest): - request = analytics_admin.ListExpandedDataSetsRequest(request) + if not isinstance(request, analytics_admin.ListAccessBindingsRequest): + request = analytics_admin.ListAccessBindingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -8270,7 +8332,7 @@ async def list_expanded_data_sets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_expanded_data_sets + self._client._transport.list_access_bindings ] # Certain fields should be provided within the metadata header; @@ -8292,7 +8354,7 @@ async def list_expanded_data_sets( # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. - response = pagers.ListExpandedDataSetsAsyncPager( + response = pagers.ListAccessBindingsAsyncPager( method=rpc, request=request, response=response, @@ -8304,38 +8366,27 @@ async def list_expanded_data_sets( # Done; return the response. return response - async def create_expanded_data_set( + async def batch_create_access_bindings( self, request: Optional[ - Union[analytics_admin.CreateExpandedDataSetRequest, dict] + Union[analytics_admin.BatchCreateAccessBindingsRequest, dict] ] = None, *, - parent: Optional[str] = None, - expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_expanded_data_set.ExpandedDataSet: - r"""Creates a ExpandedDataSet. + ) -> analytics_admin.BatchCreateAccessBindingsResponse: + r"""Creates information about multiple access bindings to + an account or property. + + This method is transactional. If any AccessBinding + cannot be created, none of the AccessBindings will be + created. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateExpandedDataSetRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsRequest, dict]]): The request object. Request message for - CreateExpandedDataSet RPC. - parent (:class:`str`): - Required. Example format: - properties/1234 - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - expanded_data_set (:class:`google.analytics.admin_v1alpha.types.ExpandedDataSet`): - Required. The ExpandedDataSet to - create. - - This corresponds to the ``expanded_data_set`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + BatchCreateAccessBindings RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8343,37 +8394,21 @@ async def create_expanded_data_set( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ExpandedDataSet: - A resource message representing a GA4 - ExpandedDataSet. + google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsResponse: + Response message for + BatchCreateAccessBindings RPC. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, expanded_data_set]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateExpandedDataSetRequest): - request = analytics_admin.CreateExpandedDataSetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if expanded_data_set is not None: - request.expanded_data_set = expanded_data_set + if not isinstance(request, analytics_admin.BatchCreateAccessBindingsRequest): + request = analytics_admin.BatchCreateAccessBindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_expanded_data_set + self._client._transport.batch_create_access_bindings ] # Certain fields should be provided within the metadata header; @@ -8396,42 +8431,84 @@ async def create_expanded_data_set( # Done; return the response. return response - async def update_expanded_data_set( + async def batch_get_access_bindings( self, request: Optional[ - Union[analytics_admin.UpdateExpandedDataSetRequest, dict] + Union[analytics_admin.BatchGetAccessBindingsRequest, dict] ] = None, *, - expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_expanded_data_set.ExpandedDataSet: - r"""Updates a ExpandedDataSet on a property. + ) -> analytics_admin.BatchGetAccessBindingsResponse: + r"""Gets information about multiple access bindings to an + account or property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateExpandedDataSetRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchGetAccessBindingsRequest, dict]]): The request object. Request message for - UpdateExpandedDataSet RPC. - expanded_data_set (:class:`google.analytics.admin_v1alpha.types.ExpandedDataSet`): - Required. The ExpandedDataSet to update. The resource's - ``name`` field is used to identify the ExpandedDataSet - to be updated. + BatchGetAccessBindings RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - This corresponds to the ``expanded_data_set`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + Returns: + google.analytics.admin_v1alpha.types.BatchGetAccessBindingsResponse: + Response message for + BatchGetAccessBindings RPC. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchGetAccessBindingsRequest): + request = analytics_admin.BatchGetAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_get_access_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_update_access_bindings( + self, + request: Optional[ + Union[analytics_admin.BatchUpdateAccessBindingsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchUpdateAccessBindingsResponse: + r"""Updates information about multiple access bindings to + an account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsRequest, dict]]): + The request object. Request message for + BatchUpdateAccessBindings RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8439,45 +8516,27 @@ async def update_expanded_data_set( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ExpandedDataSet: - A resource message representing a GA4 - ExpandedDataSet. + google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsResponse: + Response message for + BatchUpdateAccessBindings RPC. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([expanded_data_set, update_mask]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateExpandedDataSetRequest): - request = analytics_admin.UpdateExpandedDataSetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if expanded_data_set is not None: - request.expanded_data_set = expanded_data_set - if update_mask is not None: - request.update_mask = update_mask + if not isinstance(request, analytics_admin.BatchUpdateAccessBindingsRequest): + request = analytics_admin.BatchUpdateAccessBindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_expanded_data_set + self._client._transport.batch_update_access_bindings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("expanded_data_set.name", request.expanded_data_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -8494,30 +8553,23 @@ async def update_expanded_data_set( # Done; return the response. return response - async def delete_expanded_data_set( + async def batch_delete_access_bindings( self, request: Optional[ - Union[analytics_admin.DeleteExpandedDataSetRequest, dict] + Union[analytics_admin.BatchDeleteAccessBindingsRequest, dict] ] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a ExpandedDataSet on a property. + r"""Deletes information about multiple users' links to an + account or property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteExpandedDataSetRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchDeleteAccessBindingsRequest, dict]]): The request object. Request message for - DeleteExpandedDataSet RPC. - name (:class:`str`): - Required. Example format: - properties/1234/expandedDataSets/5678 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + BatchDeleteAccessBindings RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8525,35 +8577,21 @@ async def delete_expanded_data_set( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteExpandedDataSetRequest): - request = analytics_admin.DeleteExpandedDataSetRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance(request, analytics_admin.BatchDeleteAccessBindingsRequest): + request = analytics_admin.BatchDeleteAccessBindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_expanded_data_set + self._client._transport.batch_delete_access_bindings ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -8567,25 +8605,27 @@ async def delete_expanded_data_set( metadata=metadata, ) - async def get_channel_group( + async def get_expanded_data_set( self, - request: Optional[Union[analytics_admin.GetChannelGroupRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.GetExpandedDataSetRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> channel_group.ChannelGroup: - r"""Lookup for a single ChannelGroup. + ) -> expanded_data_set.ExpandedDataSet: + r"""Lookup for a single ExpandedDataSet. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetChannelGroupRequest, dict]]): - The request object. Request message for GetChannelGroup - RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetExpandedDataSetRequest, dict]]): + The request object. Request message for + GetExpandedDataSet RPC. name (:class:`str`): - Required. The ChannelGroup to get. - Example format: - properties/1234/channelGroups/5678 + Required. The name of the + ExpandedDataSet to get. Example format: + properties/1234/expandedDataSets/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -8597,9 +8637,9 @@ async def get_channel_group( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ChannelGroup: - A resource message representing a - Channel Group. + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. """ # Create or coerce a protobuf request object. @@ -8614,8 +8654,8 @@ async def get_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetChannelGroupRequest): - request = analytics_admin.GetChannelGroupRequest(request) + if not isinstance(request, analytics_admin.GetExpandedDataSetRequest): + request = analytics_admin.GetExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -8625,7 +8665,7 @@ async def get_channel_group( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_channel_group + self._client._transport.get_expanded_data_set ] # Certain fields should be provided within the metadata header; @@ -8648,24 +8688,25 @@ async def get_channel_group( # Done; return the response. return response - async def list_channel_groups( + async def list_expanded_data_sets( self, - request: Optional[Union[analytics_admin.ListChannelGroupsRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ListExpandedDataSetsRequest, dict] + ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListChannelGroupsAsyncPager: - r"""Lists ChannelGroups on a property. + ) -> pagers.ListExpandedDataSetsAsyncPager: + r"""Lists ExpandedDataSets on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListChannelGroupsRequest, dict]]): - The request object. Request message for ListChannelGroups - RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest, dict]]): + The request object. Request message for + ListExpandedDataSets RPC. parent (:class:`str`): - Required. The property for which to - list ChannelGroups. Example format: + Required. Example format: properties/1234 This corresponds to the ``parent`` field @@ -8678,9 +8719,9 @@ async def list_channel_groups( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListChannelGroupsAsyncPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListExpandedDataSetsAsyncPager: Response message for - ListChannelGroups RPC. + ListExpandedDataSets RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -8698,8 +8739,8 @@ async def list_channel_groups( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListChannelGroupsRequest): - request = analytics_admin.ListChannelGroupsRequest(request) + if not isinstance(request, analytics_admin.ListExpandedDataSetsRequest): + request = analytics_admin.ListExpandedDataSetsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -8709,7 +8750,7 @@ async def list_channel_groups( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_channel_groups + self._client._transport.list_expanded_data_sets ] # Certain fields should be provided within the metadata header; @@ -8731,7 +8772,7 @@ async def list_channel_groups( # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. - response = pagers.ListChannelGroupsAsyncPager( + response = pagers.ListExpandedDataSetsAsyncPager( method=rpc, request=request, response=response, @@ -8743,35 +8784,36 @@ async def list_channel_groups( # Done; return the response. return response - async def create_channel_group( + async def create_expanded_data_set( self, request: Optional[ - Union[analytics_admin.CreateChannelGroupRequest, dict] + Union[analytics_admin.CreateExpandedDataSetRequest, dict] ] = None, *, parent: Optional[str] = None, - channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_channel_group.ChannelGroup: - r"""Creates a ChannelGroup. + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Creates a ExpandedDataSet. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateChannelGroupRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateExpandedDataSetRequest, dict]]): The request object. Request message for - CreateChannelGroup RPC. + CreateExpandedDataSet RPC. parent (:class:`str`): - Required. The property for which to - create a ChannelGroup. Example format: + Required. Example format: properties/1234 This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - channel_group (:class:`google.analytics.admin_v1alpha.types.ChannelGroup`): - Required. The ChannelGroup to create. - This corresponds to the ``channel_group`` field + expanded_data_set (:class:`google.analytics.admin_v1alpha.types.ExpandedDataSet`): + Required. The ExpandedDataSet to + create. + + This corresponds to the ``expanded_data_set`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -8781,15 +8823,15 @@ async def create_channel_group( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ChannelGroup: - A resource message representing a - Channel Group. + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, channel_group]) + has_flattened_params = any([parent, expanded_data_set]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -8798,20 +8840,20 @@ async def create_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateChannelGroupRequest): - request = analytics_admin.CreateChannelGroupRequest(request) + if not isinstance(request, analytics_admin.CreateExpandedDataSetRequest): + request = analytics_admin.CreateExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if channel_group is not None: - request.channel_group = channel_group + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_channel_group + self._client._transport.create_expanded_data_set ] # Certain fields should be provided within the metadata header; @@ -8834,30 +8876,30 @@ async def create_channel_group( # Done; return the response. return response - async def update_channel_group( + async def update_expanded_data_set( self, request: Optional[ - Union[analytics_admin.UpdateChannelGroupRequest, dict] + Union[analytics_admin.UpdateExpandedDataSetRequest, dict] ] = None, *, - channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_channel_group.ChannelGroup: - r"""Updates a ChannelGroup. + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Updates a ExpandedDataSet on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateChannelGroupRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateExpandedDataSetRequest, dict]]): The request object. Request message for - UpdateChannelGroup RPC. - channel_group (:class:`google.analytics.admin_v1alpha.types.ChannelGroup`): - Required. The ChannelGroup to update. The resource's - ``name`` field is used to identify the ChannelGroup to - be updated. + UpdateExpandedDataSet RPC. + expanded_data_set (:class:`google.analytics.admin_v1alpha.types.ExpandedDataSet`): + Required. The ExpandedDataSet to update. The resource's + ``name`` field is used to identify the ExpandedDataSet + to be updated. - This corresponds to the ``channel_group`` field + This corresponds to the ``expanded_data_set`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): @@ -8877,15 +8919,15 @@ async def update_channel_group( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ChannelGroup: - A resource message representing a - Channel Group. + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([channel_group, update_mask]) + has_flattened_params = any([expanded_data_set, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -8894,27 +8936,27 @@ async def update_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateChannelGroupRequest): - request = analytics_admin.UpdateChannelGroupRequest(request) + if not isinstance(request, analytics_admin.UpdateExpandedDataSetRequest): + request = analytics_admin.UpdateExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if channel_group is not None: - request.channel_group = channel_group + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_channel_group + self._client._transport.update_expanded_data_set ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("channel_group.name", request.channel_group.name),) + (("expanded_data_set.name", request.expanded_data_set.name),) ), ) @@ -8932,10 +8974,10 @@ async def update_channel_group( # Done; return the response. return response - async def delete_channel_group( + async def delete_expanded_data_set( self, request: Optional[ - Union[analytics_admin.DeleteChannelGroupRequest, dict] + Union[analytics_admin.DeleteExpandedDataSetRequest, dict] ] = None, *, name: Optional[str] = None, @@ -8943,16 +8985,15 @@ async def delete_channel_group( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a ChannelGroup on a property. + r"""Deletes a ExpandedDataSet on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteChannelGroupRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteExpandedDataSetRequest, dict]]): The request object. Request message for - DeleteChannelGroup RPC. + DeleteExpandedDataSet RPC. name (:class:`str`): - Required. The ChannelGroup to delete. - Example format: - properties/1234/channelGroups/5678 + Required. Example format: + properties/1234/expandedDataSets/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -8975,8 +9016,8 @@ async def delete_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteChannelGroupRequest): - request = analytics_admin.DeleteChannelGroupRequest(request) + if not isinstance(request, analytics_admin.DeleteExpandedDataSetRequest): + request = analytics_admin.DeleteExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -8986,7 +9027,7 @@ async def delete_channel_group( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_channel_group + self._client._transport.delete_expanded_data_set ] # Certain fields should be provided within the metadata header; @@ -9006,25 +9047,29 @@ async def delete_channel_group( metadata=metadata, ) - async def set_automated_ga4_configuration_opt_out( + async def get_channel_group( self, - request: Optional[ - Union[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetChannelGroupRequest, dict]] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: - r"""Sets the opt out status for the automated GA4 setup - process for a UA property. - Note: this has no effect on GA4 property. + ) -> channel_group.ChannelGroup: + r"""Lookup for a single ChannelGroup. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutRequest, dict]]): - The request object. Request for setting the opt out - status for the automated GA4 setup - process. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetChannelGroupRequest, dict]]): + The request object. Request message for GetChannelGroup + RPC. + name (:class:`str`): + Required. The ChannelGroup to get. + Example format: + properties/1234/channelGroups/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9032,26 +9077,43 @@ async def set_automated_ga4_configuration_opt_out( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutResponse: - Response message for setting the opt - out status for the automated GA4 setup - process. + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest - ): - request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest(request) + if not isinstance(request, analytics_admin.GetChannelGroupRequest): + request = analytics_admin.GetChannelGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.set_automated_ga4_configuration_opt_out + self._client._transport.get_channel_group ] + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + # Validate the universe domain. self._client._validate_universe_domain() @@ -9066,25 +9128,29 @@ async def set_automated_ga4_configuration_opt_out( # Done; return the response. return response - async def fetch_automated_ga4_configuration_opt_out( + async def list_channel_groups( self, - request: Optional[ - Union[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListChannelGroupsRequest, dict]] = None, *, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: - r"""Fetches the opt out status for the automated GA4 - setup process for a UA property. - Note: this has no effect on GA4 property. + ) -> pagers.ListChannelGroupsAsyncPager: + r"""Lists ChannelGroups on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutRequest, dict]]): - The request object. Request for fetching the opt out - status for the automated GA4 setup - process. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListChannelGroupsRequest, dict]]): + The request object. Request message for ListChannelGroups + RPC. + parent (:class:`str`): + Required. The property for which to + list ChannelGroups. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9092,28 +9158,46 @@ async def fetch_automated_ga4_configuration_opt_out( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutResponse: - Response message for fetching the opt - out status for the automated GA4 setup - process. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListChannelGroupsAsyncPager: + Response message for + ListChannelGroups RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest - ): - request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( - request - ) + if not isinstance(request, analytics_admin.ListChannelGroupsRequest): + request = analytics_admin.ListChannelGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.fetch_automated_ga4_configuration_opt_out + self._client._transport.list_channel_groups ] + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + # Validate the universe domain. self._client._validate_universe_domain() @@ -9125,33 +9209,51 @@ async def fetch_automated_ga4_configuration_opt_out( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListChannelGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def get_big_query_link( + async def create_channel_group( self, - request: Optional[Union[analytics_admin.GetBigQueryLinkRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.CreateChannelGroupRequest, dict] + ] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + channel_group: Optional[gaa_channel_group.ChannelGroup] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.BigQueryLink: - r"""Lookup for a single BigQuery Link. + ) -> gaa_channel_group.ChannelGroup: + r"""Creates a ChannelGroup. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetBigQueryLinkRequest, dict]]): - The request object. Request message for GetBigQueryLink - RPC. - name (:class:`str`): - Required. The name of the BigQuery link to lookup. - Format: - properties/{property_id}/bigQueryLinks/{bigquery_link_id} - Example: properties/123/bigQueryLinks/456 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateChannelGroupRequest, dict]]): + The request object. Request message for + CreateChannelGroup RPC. + parent (:class:`str`): + Required. The property for which to + create a ChannelGroup. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_group (:class:`google.analytics.admin_v1alpha.types.ChannelGroup`): + Required. The ChannelGroup to create. + This corresponds to the ``channel_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9159,15 +9261,15 @@ async def get_big_query_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BigQueryLink: - A link between a GA4 Property and - BigQuery project. + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, channel_group]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9176,24 +9278,26 @@ async def get_big_query_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetBigQueryLinkRequest): - request = analytics_admin.GetBigQueryLinkRequest(request) + if not isinstance(request, analytics_admin.CreateChannelGroupRequest): + request = analytics_admin.CreateChannelGroupRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if channel_group is not None: + request.channel_group = channel_group # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_big_query_link + self._client._transport.create_channel_group ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -9210,27 +9314,40 @@ async def get_big_query_link( # Done; return the response. return response - async def list_big_query_links( + async def update_channel_group( self, - request: Optional[Union[analytics_admin.ListBigQueryLinksRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.UpdateChannelGroupRequest, dict] + ] = None, *, - parent: Optional[str] = None, + channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBigQueryLinksAsyncPager: - r"""Lists BigQuery Links on a property. + ) -> gaa_channel_group.ChannelGroup: + r"""Updates a ChannelGroup. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest, dict]]): - The request object. Request message for ListBigQueryLinks - RPC. - parent (:class:`str`): - Required. The name of the property to list BigQuery - links under. Format: properties/{property_id} Example: - properties/1234 + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateChannelGroupRequest, dict]]): + The request object. Request message for + UpdateChannelGroup RPC. + channel_group (:class:`google.analytics.admin_v1alpha.types.ChannelGroup`): + Required. The ChannelGroup to update. The resource's + ``name`` field is used to identify the ChannelGroup to + be updated. - This corresponds to the ``parent`` field + This corresponds to the ``channel_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -9240,18 +9357,15 @@ async def list_big_query_links( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListBigQueryLinksAsyncPager: - Response message for - ListBigQueryLinks RPC - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([channel_group, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9260,24 +9374,28 @@ async def list_big_query_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListBigQueryLinksRequest): - request = analytics_admin.ListBigQueryLinksRequest(request) + if not isinstance(request, analytics_admin.UpdateChannelGroupRequest): + request = analytics_admin.UpdateChannelGroupRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if channel_group is not None: + request.channel_group = channel_group + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_big_query_links + self._client._transport.update_channel_group ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("channel_group.name", request.channel_group.name),) + ), ) # Validate the universe domain. @@ -9291,44 +9409,30 @@ async def list_big_query_links( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListBigQueryLinksAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - async def get_enhanced_measurement_settings( + async def delete_channel_group( self, request: Optional[ - Union[analytics_admin.GetEnhancedMeasurementSettingsRequest, dict] + Union[analytics_admin.DeleteChannelGroupRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.EnhancedMeasurementSettings: - r"""Returns the enhanced measurement settings for this - data stream. Note that the stream must enable enhanced - measurement for these settings to take effect. + ) -> None: + r"""Deletes a ChannelGroup on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetEnhancedMeasurementSettingsRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteChannelGroupRequest, dict]]): The request object. Request message for - GetEnhancedMeasurementSettings RPC. + DeleteChannelGroup RPC. name (:class:`str`): - Required. The name of the settings to lookup. Format: - properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings - Example: - "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + Required. The ChannelGroup to delete. + Example format: + properties/1234/channelGroups/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -9338,14 +9442,6 @@ async def get_enhanced_measurement_settings( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: - Singleton resource under a web - DataStream, configuring measurement of - additional site interactions and - content. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -9359,10 +9455,8 @@ async def get_enhanced_measurement_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.GetEnhancedMeasurementSettingsRequest - ): - request = analytics_admin.GetEnhancedMeasurementSettingsRequest(request) + if not isinstance(request, analytics_admin.DeleteChannelGroupRequest): + request = analytics_admin.DeleteChannelGroupRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -9372,7 +9466,7 @@ async def get_enhanced_measurement_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_enhanced_measurement_settings + self._client._transport.delete_channel_group ] # Certain fields should be provided within the metadata header; @@ -9385,55 +9479,32 @@ async def get_enhanced_measurement_settings( self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - async def update_enhanced_measurement_settings( + async def set_automated_ga4_configuration_opt_out( self, request: Optional[ - Union[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict] + Union[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict] ] = None, *, - enhanced_measurement_settings: Optional[ - resources.EnhancedMeasurementSettings - ] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.EnhancedMeasurementSettings: - r"""Updates the enhanced measurement settings for this - data stream. Note that the stream must enable enhanced - measurement for these settings to take effect. + ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + r"""Sets the opt out status for the automated GA4 setup + process for a UA property. + Note: this has no effect on GA4 property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEnhancedMeasurementSettingsRequest, dict]]): - The request object. Request message for - UpdateEnhancedMeasurementSettings RPC. - enhanced_measurement_settings (:class:`google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings`): - Required. The settings to update. The ``name`` field is - used to identify the settings to be updated. - - This corresponds to the ``enhanced_measurement_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + request (Optional[Union[google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutRequest, dict]]): + The request object. Request for setting the opt out + status for the automated GA4 setup + process. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9441,56 +9512,26 @@ async def update_enhanced_measurement_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: - Singleton resource under a web - DataStream, configuring measurement of - additional site interactions and - content. + google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutResponse: + Response message for setting the opt + out status for the automated GA4 setup + process. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([enhanced_measurement_settings, update_mask]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.UpdateEnhancedMeasurementSettingsRequest + request, analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest ): - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if enhanced_measurement_settings is not None: - request.enhanced_measurement_settings = enhanced_measurement_settings - if update_mask is not None: - request.update_mask = update_mask + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_enhanced_measurement_settings + self._client._transport.set_automated_ga4_configuration_opt_out ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - ( - ( - "enhanced_measurement_settings.name", - request.enhanced_measurement_settings.name, - ), - ) - ), - ) - # Validate the universe domain. self._client._validate_universe_domain() @@ -9505,25 +9546,25 @@ async def update_enhanced_measurement_settings( # Done; return the response. return response - async def create_connected_site_tag( + async def fetch_automated_ga4_configuration_opt_out( self, request: Optional[ - Union[analytics_admin.CreateConnectedSiteTagRequest, dict] + Union[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict] ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.CreateConnectedSiteTagResponse: - r"""Creates a connected site tag for a Universal - Analytics property. You can create a maximum of 20 - connected site tags per property. Note: This API cannot - be used on GA4 properties. + ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + r"""Fetches the opt out status for the automated GA4 + setup process for a UA property. + Note: this has no effect on GA4 property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateConnectedSiteTagRequest, dict]]): - The request object. Request message for - CreateConnectedSiteTag RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutRequest, dict]]): + The request object. Request for fetching the opt out + status for the automated GA4 setup + process. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9531,21 +9572,26 @@ async def create_connected_site_tag( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CreateConnectedSiteTagResponse: - Response message for - CreateConnectedSiteTag RPC. + google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutResponse: + Response message for fetching the opt + out status for the automated GA4 setup + process. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateConnectedSiteTagRequest): - request = analytics_admin.CreateConnectedSiteTagRequest(request) + if not isinstance( + request, analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest + ): + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( + request + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_connected_site_tag + self._client._transport.fetch_automated_ga4_configuration_opt_out ] # Validate the universe domain. @@ -9562,72 +9608,120 @@ async def create_connected_site_tag( # Done; return the response. return response - async def delete_connected_site_tag( + async def create_big_query_link( self, request: Optional[ - Union[analytics_admin.DeleteConnectedSiteTagRequest, dict] + Union[analytics_admin.CreateBigQueryLinkRequest, dict] ] = None, *, + parent: Optional[str] = None, + bigquery_link: Optional[resources.BigQueryLink] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a connected site tag for a Universal - Analytics property. Note: this has no effect on GA4 - properties. + ) -> resources.BigQueryLink: + r"""Creates a BigQueryLink. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteConnectedSiteTagRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateBigQueryLinkRequest, dict]]): The request object. Request message for - DeleteConnectedSiteTag RPC. + CreateBigQueryLink RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bigquery_link (:class:`google.analytics.admin_v1alpha.types.BigQueryLink`): + Required. The BigQueryLink to create. + This corresponds to the ``bigquery_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, bigquery_link]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteConnectedSiteTagRequest): - request = analytics_admin.DeleteConnectedSiteTagRequest(request) + if not isinstance(request, analytics_admin.CreateBigQueryLinkRequest): + request = analytics_admin.CreateBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if bigquery_link is not None: + request.bigquery_link = bigquery_link # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_connected_site_tag + self._client._transport.create_big_query_link ] + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc( + response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - async def list_connected_site_tags( + # Done; return the response. + return response + + async def get_big_query_link( self, - request: Optional[ - Union[analytics_admin.ListConnectedSiteTagsRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetBigQueryLinkRequest, dict]] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.ListConnectedSiteTagsResponse: - r"""Lists the connected site tags for a Universal - Analytics property. A maximum of 20 connected site tags - will be returned. Note: this has no effect on GA4 - property. + ) -> resources.BigQueryLink: + r"""Lookup for a single BigQuery Link. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListConnectedSiteTagsRequest, dict]]): - The request object. Request message for - ListConnectedSiteTags RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetBigQueryLinkRequest, dict]]): + The request object. Request message for GetBigQueryLink + RPC. + name (:class:`str`): + Required. The name of the BigQuery link to lookup. + Format: + properties/{property_id}/bigQueryLinks/{bigquery_link_id} + Example: properties/123/bigQueryLinks/456 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9635,23 +9729,43 @@ async def list_connected_site_tags( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ListConnectedSiteTagsResponse: - Response message for - ListConnectedSiteTags RPC. + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListConnectedSiteTagsRequest): - request = analytics_admin.ListConnectedSiteTagsRequest(request) + if not isinstance(request, analytics_admin.GetBigQueryLinkRequest): + request = analytics_admin.GetBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_connected_site_tags + self._client._transport.get_big_query_link ] + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + # Validate the universe domain. self._client._validate_universe_domain() @@ -9666,24 +9780,29 @@ async def list_connected_site_tags( # Done; return the response. return response - async def fetch_connected_ga4_property( + async def list_big_query_links( self, - request: Optional[ - Union[analytics_admin.FetchConnectedGa4PropertyRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListBigQueryLinksRequest, dict]] = None, *, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.FetchConnectedGa4PropertyResponse: - r"""Given a specified UA property, looks up the GA4 - property connected to it. Note: this cannot be used with - GA4 properties. + ) -> pagers.ListBigQueryLinksAsyncPager: + r"""Lists BigQuery Links on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyRequest, dict]]): - The request object. Request for looking up GA4 property - connected to a UA property. + request (Optional[Union[google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest, dict]]): + The request object. Request message for ListBigQueryLinks + RPC. + parent (:class:`str`): + Required. The name of the property to list BigQuery + links under. Format: properties/{property_id} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9691,23 +9810,46 @@ async def fetch_connected_ga4_property( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyResponse: - Response for looking up GA4 property - connected to a UA property. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListBigQueryLinksAsyncPager: + Response message for + ListBigQueryLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.FetchConnectedGa4PropertyRequest): - request = analytics_admin.FetchConnectedGa4PropertyRequest(request) + if not isinstance(request, analytics_admin.ListBigQueryLinksRequest): + request = analytics_admin.ListBigQueryLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.fetch_connected_ga4_property + self._client._transport.list_big_query_links ] + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + # Validate the universe domain. self._client._validate_universe_domain() @@ -9719,30 +9861,41 @@ async def fetch_connected_ga4_property( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBigQueryLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - async def get_ad_sense_link( + async def delete_big_query_link( self, - request: Optional[Union[analytics_admin.GetAdSenseLinkRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.DeleteBigQueryLinkRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AdSenseLink: - r"""Looks up a single AdSenseLink. + ) -> None: + r"""Deletes a BigQueryLink on a property. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetAdSenseLinkRequest, dict]]): - The request object. Request message to be passed to - GetAdSenseLink method. + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteBigQueryLinkRequest, dict]]): + The request object. Request message for + DeleteBigQueryLink RPC. name (:class:`str`): - Required. Unique identifier for the - AdSense Link requested. Format: - properties/{propertyId}/adSenseLinks/{linkId} - Example: - properties/1234/adSenseLinks/5678 + Required. The BigQueryLink to delete. + Example format: + properties/1234/bigQueryLinks/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -9752,12 +9905,6 @@ async def get_ad_sense_link( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.AdSenseLink: - A link between a GA4 Property and an - AdSense for Content ad client. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -9771,8 +9918,8 @@ async def get_ad_sense_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAdSenseLinkRequest): - request = analytics_admin.GetAdSenseLinkRequest(request) + if not isinstance(request, analytics_admin.DeleteBigQueryLinkRequest): + request = analytics_admin.DeleteBigQueryLinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -9782,7 +9929,7 @@ async def get_ad_sense_link( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_ad_sense_link + self._client._transport.delete_big_query_link ] # Certain fields should be provided within the metadata header; @@ -9795,44 +9942,1091 @@ async def get_ad_sense_link( self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - async def create_ad_sense_link( + async def update_big_query_link( self, - request: Optional[Union[analytics_admin.CreateAdSenseLinkRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.UpdateBigQueryLinkRequest, dict] + ] = None, *, - parent: Optional[str] = None, - adsense_link: Optional[resources.AdSenseLink] = None, + bigquery_link: Optional[resources.BigQueryLink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AdSenseLink: - r"""Creates an AdSenseLink. + ) -> resources.BigQueryLink: + r"""Updates a BigQueryLink. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAdSenseLinkRequest, dict]]): - The request object. Request message to be passed to - CreateAdSenseLink method. - parent (:class:`str`): - Required. The property for which to - create an AdSense Link. Format: - properties/{propertyId} Example: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateBigQueryLinkRequest, dict]]): + The request object. Request message for + UpdateBigQueryLink RPC. + bigquery_link (:class:`google.analytics.admin_v1alpha.types.BigQueryLink`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``bigquery_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([bigquery_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateBigQueryLinkRequest): + request = analytics_admin.UpdateBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if bigquery_link is not None: + request.bigquery_link = bigquery_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_big_query_link + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("bigquery_link.name", request.bigquery_link.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_enhanced_measurement_settings( + self, + request: Optional[ + Union[analytics_admin.GetEnhancedMeasurementSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Returns the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetEnhancedMeasurementSettingsRequest, dict]]): + The request object. Request message for + GetEnhancedMeasurementSettings RPC. + name (:class:`str`): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings + Example: + "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, analytics_admin.GetEnhancedMeasurementSettingsRequest + ): + request = analytics_admin.GetEnhancedMeasurementSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_enhanced_measurement_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_enhanced_measurement_settings( + self, + request: Optional[ + Union[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict] + ] = None, + *, + enhanced_measurement_settings: Optional[ + resources.EnhancedMeasurementSettings + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Updates the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEnhancedMeasurementSettingsRequest, dict]]): + The request object. Request message for + UpdateEnhancedMeasurementSettings RPC. + enhanced_measurement_settings (:class:`google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``enhanced_measurement_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([enhanced_measurement_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, analytics_admin.UpdateEnhancedMeasurementSettingsRequest + ): + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enhanced_measurement_settings is not None: + request.enhanced_measurement_settings = enhanced_measurement_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_enhanced_measurement_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "enhanced_measurement_settings.name", + request.enhanced_measurement_settings.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_connected_site_tag( + self, + request: Optional[ + Union[analytics_admin.CreateConnectedSiteTagRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.CreateConnectedSiteTagResponse: + r"""Creates a connected site tag for a Universal + Analytics property. You can create a maximum of 20 + connected site tags per property. Note: This API cannot + be used on GA4 properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateConnectedSiteTagRequest, dict]]): + The request object. Request message for + CreateConnectedSiteTag RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CreateConnectedSiteTagResponse: + Response message for + CreateConnectedSiteTag RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConnectedSiteTagRequest): + request = analytics_admin.CreateConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_connected_site_tag + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_connected_site_tag( + self, + request: Optional[ + Union[analytics_admin.DeleteConnectedSiteTagRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a connected site tag for a Universal + Analytics property. Note: this has no effect on GA4 + properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteConnectedSiteTagRequest, dict]]): + The request object. Request message for + DeleteConnectedSiteTag RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConnectedSiteTagRequest): + request = analytics_admin.DeleteConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_connected_site_tag + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_connected_site_tags( + self, + request: Optional[ + Union[analytics_admin.ListConnectedSiteTagsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ListConnectedSiteTagsResponse: + r"""Lists the connected site tags for a Universal + Analytics property. A maximum of 20 connected site tags + will be returned. Note: this has no effect on GA4 + property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListConnectedSiteTagsRequest, dict]]): + The request object. Request message for + ListConnectedSiteTags RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ListConnectedSiteTagsResponse: + Response message for + ListConnectedSiteTags RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConnectedSiteTagsRequest): + request = analytics_admin.ListConnectedSiteTagsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_connected_site_tags + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fetch_connected_ga4_property( + self, + request: Optional[ + Union[analytics_admin.FetchConnectedGa4PropertyRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.FetchConnectedGa4PropertyResponse: + r"""Given a specified UA property, looks up the GA4 + property connected to it. Note: this cannot be used with + GA4 properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyRequest, dict]]): + The request object. Request for looking up GA4 property + connected to a UA property. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyResponse: + Response for looking up GA4 property + connected to a UA property. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.FetchConnectedGa4PropertyRequest): + request = analytics_admin.FetchConnectedGa4PropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_connected_ga4_property + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ad_sense_link( + self, + request: Optional[Union[analytics_admin.GetAdSenseLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AdSenseLink: + r"""Looks up a single AdSenseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAdSenseLinkRequest, dict]]): + The request object. Request message to be passed to + GetAdSenseLink method. + name (:class:`str`): + Required. Unique identifier for the + AdSense Link requested. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAdSenseLinkRequest): + request = analytics_admin.GetAdSenseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_ad_sense_link + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_ad_sense_link( + self, + request: Optional[Union[analytics_admin.CreateAdSenseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + adsense_link: Optional[resources.AdSenseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AdSenseLink: + r"""Creates an AdSenseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAdSenseLinkRequest, dict]]): + The request object. Request message to be passed to + CreateAdSenseLink method. + parent (:class:`str`): + Required. The property for which to + create an AdSense Link. Format: + properties/{propertyId} Example: properties/1234 This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - adsense_link (:class:`google.analytics.admin_v1alpha.types.AdSenseLink`): - Required. The AdSense Link to create - This corresponds to the ``adsense_link`` field + adsense_link (:class:`google.analytics.admin_v1alpha.types.AdSenseLink`): + Required. The AdSense Link to create + This corresponds to the ``adsense_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, adsense_link]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAdSenseLinkRequest): + request = analytics_admin.CreateAdSenseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if adsense_link is not None: + request.adsense_link = adsense_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_ad_sense_link + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_ad_sense_link( + self, + request: Optional[Union[analytics_admin.DeleteAdSenseLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an AdSenseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAdSenseLinkRequest, dict]]): + The request object. Request message to be passed to + DeleteAdSenseLink method. + name (:class:`str`): + Required. Unique identifier for the + AdSense Link to be deleted. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAdSenseLinkRequest): + request = analytics_admin.DeleteAdSenseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_ad_sense_link + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_ad_sense_links( + self, + request: Optional[Union[analytics_admin.ListAdSenseLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAdSenseLinksAsyncPager: + r"""Lists AdSenseLinks on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest, dict]]): + The request object. Request message to be passed to + ListAdSenseLinks method. + parent (:class:`str`): + Required. Resource name of the parent + property. Format: + properties/{propertyId} + Example: properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAdSenseLinksAsyncPager: + Response message for ListAdSenseLinks + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAdSenseLinksRequest): + request = analytics_admin.ListAdSenseLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_ad_sense_links + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAdSenseLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_event_create_rule( + self, + request: Optional[ + Union[analytics_admin.GetEventCreateRuleRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Lookup for a single EventCreateRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetEventCreateRuleRequest, dict]]): + The request object. Request message for + GetEventCreateRule RPC. + name (:class:`str`): + Required. The name of the + EventCreateRule to get. Example format: + properties/123/dataStreams/456/eventCreateRules/789 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEventCreateRuleRequest): + request = analytics_admin.GetEventCreateRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_event_create_rule + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_event_create_rules( + self, + request: Optional[ + Union[analytics_admin.ListEventCreateRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEventCreateRulesAsyncPager: + r"""Lists EventCreateRules on a web data stream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest, dict]]): + The request object. Request message for + ListEventCreateRules RPC. + parent (:class:`str`): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventCreateRulesAsyncPager: + Response message for + ListEventCreateRules RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListEventCreateRulesRequest): + request = analytics_admin.ListEventCreateRulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_event_create_rules + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEventCreateRulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event_create_rule( + self, + request: Optional[ + Union[analytics_admin.CreateEventCreateRuleRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Creates an EventCreateRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateEventCreateRuleRequest, dict]]): + The request object. Request message for + CreateEventCreateRule RPC. + parent (:class:`str`): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_create_rule (:class:`google.analytics.admin_v1alpha.types.EventCreateRule`): + Required. The EventCreateRule to + create. + + This corresponds to the ``event_create_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -9842,15 +11036,27 @@ async def create_ad_sense_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AdSenseLink: - A link between a GA4 Property and an - AdSense for Content ad client. + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, adsense_link]) + has_flattened_params = any([parent, event_create_rule]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9859,20 +11065,20 @@ async def create_ad_sense_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateAdSenseLinkRequest): - request = analytics_admin.CreateAdSenseLinkRequest(request) + if not isinstance(request, analytics_admin.CreateEventCreateRuleRequest): + request = analytics_admin.CreateEventCreateRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if adsense_link is not None: - request.adsense_link = adsense_link + if event_create_rule is not None: + request.event_create_rule = event_create_rule # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_ad_sense_link + self._client._transport.create_event_create_rule ] # Certain fields should be provided within the metadata header; @@ -9895,41 +11101,70 @@ async def create_ad_sense_link( # Done; return the response. return response - async def delete_ad_sense_link( + async def update_event_create_rule( self, - request: Optional[Union[analytics_admin.DeleteAdSenseLinkRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.UpdateEventCreateRuleRequest, dict] + ] = None, *, - name: Optional[str] = None, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an AdSenseLink. + ) -> event_create_and_edit.EventCreateRule: + r"""Updates an EventCreateRule. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAdSenseLinkRequest, dict]]): - The request object. Request message to be passed to - DeleteAdSenseLink method. - name (:class:`str`): - Required. Unique identifier for the - AdSense Link to be deleted. Format: - properties/{propertyId}/adSenseLinks/{linkId} - Example: - properties/1234/adSenseLinks/5678 + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEventCreateRuleRequest, dict]]): + The request object. Request message for + UpdateEventCreateRule RPC. + event_create_rule (:class:`google.analytics.admin_v1alpha.types.EventCreateRule`): + Required. The EventCreateRule to update. The resource's + ``name`` field is used to identify the EventCreateRule + to be updated. + + This corresponds to the ``event_create_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([event_create_rule, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9938,59 +11173,67 @@ async def delete_ad_sense_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteAdSenseLinkRequest): - request = analytics_admin.DeleteAdSenseLinkRequest(request) + if not isinstance(request, analytics_admin.UpdateEventCreateRuleRequest): + request = analytics_admin.UpdateEventCreateRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if event_create_rule is not None: + request.event_create_rule = event_create_rule + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_ad_sense_link + self._client._transport.update_event_create_rule ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("event_create_rule.name", request.event_create_rule.name),) + ), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - await rpc( + response = await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - async def list_ad_sense_links( + # Done; return the response. + return response + + async def delete_event_create_rule( self, - request: Optional[Union[analytics_admin.ListAdSenseLinksRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.DeleteEventCreateRuleRequest, dict] + ] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAdSenseLinksAsyncPager: - r"""Lists AdSenseLinks on a property. + ) -> None: + r"""Deletes an EventCreateRule. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest, dict]]): - The request object. Request message to be passed to - ListAdSenseLinks method. - parent (:class:`str`): - Required. Resource name of the parent - property. Format: - properties/{propertyId} - Example: properties/1234 + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteEventCreateRuleRequest, dict]]): + The request object. Request message for + DeleteEventCreateRule RPC. + name (:class:`str`): + Required. Example format: - This corresponds to the ``parent`` field + properties/123/dataStreams/456/eventCreateRules/789 + + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -9998,20 +11241,11 @@ async def list_ad_sense_links( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAdSenseLinksAsyncPager: - Response message for ListAdSenseLinks - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10020,72 +11254,56 @@ async def list_ad_sense_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListAdSenseLinksRequest): - request = analytics_admin.ListAdSenseLinksRequest(request) + if not isinstance(request, analytics_admin.DeleteEventCreateRuleRequest): + request = analytics_admin.DeleteEventCreateRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_ad_sense_links + self._client._transport.delete_event_create_rule ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._client._validate_universe_domain() # Send the request. - response = await rpc( + await rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAdSenseLinksAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_event_create_rule( + async def get_event_edit_rule( self, - request: Optional[ - Union[analytics_admin.GetEventCreateRuleRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetEventEditRuleRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Lookup for a single EventCreateRule. + ) -> event_create_and_edit.EventEditRule: + r"""Lookup for a single EventEditRule. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.GetEventCreateRuleRequest, dict]]): - The request object. Request message for - GetEventCreateRule RPC. + request (Optional[Union[google.analytics.admin_v1alpha.types.GetEventEditRuleRequest, dict]]): + The request object. Request message for GetEventEditRule + RPC. name (:class:`str`): Required. The name of the - EventCreateRule to get. Example format: - properties/123/dataStreams/456/eventCreateRules/789 + EventEditRule to get. Example format: + properties/123/dataStreams/456/eventEditRules/789 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -10097,21 +11315,21 @@ async def get_event_create_rule( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ # Create or coerce a protobuf request object. @@ -10126,8 +11344,8 @@ async def get_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetEventCreateRuleRequest): - request = analytics_admin.GetEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.GetEventEditRuleRequest): + request = analytics_admin.GetEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -10137,7 +11355,7 @@ async def get_event_create_rule( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_event_create_rule + self._client._transport.get_event_edit_rule ] # Certain fields should be provided within the metadata header; @@ -10160,23 +11378,23 @@ async def get_event_create_rule( # Done; return the response. return response - async def list_event_create_rules( + async def list_event_edit_rules( self, request: Optional[ - Union[analytics_admin.ListEventCreateRulesRequest, dict] + Union[analytics_admin.ListEventEditRulesRequest, dict] ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEventCreateRulesAsyncPager: - r"""Lists EventCreateRules on a web data stream. + ) -> pagers.ListEventEditRulesAsyncPager: + r"""Lists EventEditRules on a web data stream. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ListEventEditRulesRequest, dict]]): The request object. Request message for - ListEventCreateRules RPC. + ListEventEditRules RPC. parent (:class:`str`): Required. Example format: properties/123/dataStreams/456 @@ -10191,9 +11409,9 @@ async def list_event_create_rules( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventCreateRulesAsyncPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventEditRulesAsyncPager: Response message for - ListEventCreateRules RPC. + ListEventEditRules RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -10211,8 +11429,8 @@ async def list_event_create_rules( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListEventCreateRulesRequest): - request = analytics_admin.ListEventCreateRulesRequest(request) + if not isinstance(request, analytics_admin.ListEventEditRulesRequest): + request = analytics_admin.ListEventEditRulesRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -10222,7 +11440,7 @@ async def list_event_create_rules( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.list_event_create_rules + self._client._transport.list_event_edit_rules ] # Certain fields should be provided within the metadata header; @@ -10244,7 +11462,7 @@ async def list_event_create_rules( # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. - response = pagers.ListEventCreateRulesAsyncPager( + response = pagers.ListEventEditRulesAsyncPager( method=rpc, request=request, response=response, @@ -10256,24 +11474,24 @@ async def list_event_create_rules( # Done; return the response. return response - async def create_event_create_rule( + async def create_event_edit_rule( self, request: Optional[ - Union[analytics_admin.CreateEventCreateRuleRequest, dict] + Union[analytics_admin.CreateEventEditRuleRequest, dict] ] = None, *, parent: Optional[str] = None, - event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Creates an EventCreateRule. + ) -> event_create_and_edit.EventEditRule: + r"""Creates an EventEditRule. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateEventCreateRuleRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateEventEditRuleRequest, dict]]): The request object. Request message for - CreateEventCreateRule RPC. + CreateEventEditRule RPC. parent (:class:`str`): Required. Example format: properties/123/dataStreams/456 @@ -10281,11 +11499,11 @@ async def create_event_create_rule( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - event_create_rule (:class:`google.analytics.admin_v1alpha.types.EventCreateRule`): - Required. The EventCreateRule to + event_edit_rule (:class:`google.analytics.admin_v1alpha.types.EventEditRule`): + Required. The EventEditRule to create. - This corresponds to the ``event_create_rule`` field + This corresponds to the ``event_edit_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -10295,27 +11513,27 @@ async def create_event_create_rule( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, event_create_rule]) + has_flattened_params = any([parent, event_edit_rule]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10324,20 +11542,20 @@ async def create_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateEventCreateRuleRequest): - request = analytics_admin.CreateEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.CreateEventEditRuleRequest): + request = analytics_admin.CreateEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if event_create_rule is not None: - request.event_create_rule = event_create_rule + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_event_create_rule + self._client._transport.create_event_edit_rule ] # Certain fields should be provided within the metadata header; @@ -10360,30 +11578,30 @@ async def create_event_create_rule( # Done; return the response. return response - async def update_event_create_rule( + async def update_event_edit_rule( self, request: Optional[ - Union[analytics_admin.UpdateEventCreateRuleRequest, dict] + Union[analytics_admin.UpdateEventEditRuleRequest, dict] ] = None, *, - event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Updates an EventCreateRule. + ) -> event_create_and_edit.EventEditRule: + r"""Updates an EventEditRule. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEventCreateRuleRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEventEditRuleRequest, dict]]): The request object. Request message for - UpdateEventCreateRule RPC. - event_create_rule (:class:`google.analytics.admin_v1alpha.types.EventCreateRule`): - Required. The EventCreateRule to update. The resource's - ``name`` field is used to identify the EventCreateRule - to be updated. + UpdateEventEditRule RPC. + event_edit_rule (:class:`google.analytics.admin_v1alpha.types.EventEditRule`): + Required. The EventEditRule to update. The resource's + ``name`` field is used to identify the EventEditRule to + be updated. - This corresponds to the ``event_create_rule`` field + This corresponds to the ``event_edit_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): @@ -10403,27 +11621,27 @@ async def update_event_create_rule( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([event_create_rule, update_mask]) + has_flattened_params = any([event_edit_rule, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10432,27 +11650,27 @@ async def update_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateEventCreateRuleRequest): - request = analytics_admin.UpdateEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.UpdateEventEditRuleRequest): + request = analytics_admin.UpdateEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if event_create_rule is not None: - request.event_create_rule = event_create_rule + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.update_event_create_rule + self._client._transport.update_event_edit_rule ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("event_create_rule.name", request.event_create_rule.name),) + (("event_edit_rule.name", request.event_edit_rule.name),) ), ) @@ -10470,10 +11688,10 @@ async def update_event_create_rule( # Done; return the response. return response - async def delete_event_create_rule( + async def delete_event_edit_rule( self, request: Optional[ - Union[analytics_admin.DeleteEventCreateRuleRequest, dict] + Union[analytics_admin.DeleteEventEditRuleRequest, dict] ] = None, *, name: Optional[str] = None, @@ -10481,16 +11699,15 @@ async def delete_event_create_rule( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes an EventCreateRule. + r"""Deletes an EventEditRule. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteEventCreateRuleRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteEventEditRuleRequest, dict]]): The request object. Request message for - DeleteEventCreateRule RPC. + DeleteEventEditRule RPC. name (:class:`str`): Required. Example format: - - properties/123/dataStreams/456/eventCreateRules/789 + properties/123/dataStreams/456/eventEditRules/789 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -10513,8 +11730,8 @@ async def delete_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteEventCreateRuleRequest): - request = analytics_admin.DeleteEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.DeleteEventEditRuleRequest): + request = analytics_admin.DeleteEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -10524,7 +11741,7 @@ async def delete_event_create_rule( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_event_create_rule + self._client._transport.delete_event_edit_rule ] # Certain fields should be provided within the metadata header; @@ -10544,6 +11761,58 @@ async def delete_event_create_rule( metadata=metadata, ) + async def reorder_event_edit_rules( + self, + request: Optional[ + Union[analytics_admin.ReorderEventEditRulesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Changes the processing order of event edit rules on + the specified stream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ReorderEventEditRulesRequest, dict]]): + The request object. Request message for + ReorderEventEditRules RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ReorderEventEditRulesRequest): + request = analytics_admin.ReorderEventEditRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reorder_event_edit_rules + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + async def update_data_redaction_settings( self, request: Optional[ @@ -10853,7 +12122,7 @@ async def create_calculated_metric( metric's resource name. This value should be 1-80 characters and valid - characters are `[a-zA-Z0-9_]`, no spaces allowed. + characters are /[a-zA-Z0-9_]/, no spaces allowed. calculated_metric_id must be unique between all calculated metrics under a property. The calculated_metric_id is used when referencing this @@ -11612,19 +12881,21 @@ async def delete_rollup_property_source_link( metadata=metadata, ) - async def create_subproperty( + async def provision_subproperty( self, - request: Optional[Union[analytics_admin.CreateSubpropertyRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ProvisionSubpropertyRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.CreateSubpropertyResponse: + ) -> analytics_admin.ProvisionSubpropertyResponse: r"""Create a subproperty and a subproperty event filter that applies to the created subproperty. Args: - request (Optional[Union[google.analytics.admin_v1alpha.types.CreateSubpropertyRequest, dict]]): + request (Optional[Union[google.analytics.admin_v1alpha.types.ProvisionSubpropertyRequest, dict]]): The request object. Request message for CreateSubproperty RPC. retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, @@ -11634,21 +12905,21 @@ async def create_subproperty( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CreateSubpropertyResponse: + google.analytics.admin_v1alpha.types.ProvisionSubpropertyResponse: Response message for - CreateSubproperty RPC. + ProvisionSubproperty RPC. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateSubpropertyRequest): - request = analytics_admin.CreateSubpropertyRequest(request) + if not isinstance(request, analytics_admin.ProvisionSubpropertyRequest): + request = analytics_admin.ProvisionSubpropertyRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_subproperty + self._client._transport.provision_subproperty ] # Validate the universe domain. diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py index 45710bbc0c33..91c076087aea 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py @@ -573,6 +573,28 @@ def parse_event_create_rule_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def event_edit_rule_path( + property: str, + data_stream: str, + event_edit_rule: str, + ) -> str: + """Returns a fully-qualified event_edit_rule string.""" + return "properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule}".format( + property=property, + data_stream=data_stream, + event_edit_rule=event_edit_rule, + ) + + @staticmethod + def parse_event_edit_rule_path(path: str) -> Dict[str, str]: + """Parses a event_edit_rule path into its component segments.""" + m = re.match( + r"^properties/(?P.+?)/dataStreams/(?P.+?)/eventEditRules/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def expanded_data_set_path( property: str, @@ -667,6 +689,25 @@ def parse_google_signals_settings_path(path: str) -> Dict[str, str]: m = re.match(r"^properties/(?P.+?)/googleSignalsSettings$", path) return m.groupdict() if m else {} + @staticmethod + def key_event_path( + property: str, + key_event: str, + ) -> str: + """Returns a fully-qualified key_event string.""" + return "properties/{property}/keyEvents/{key_event}".format( + property=property, + key_event=key_event, + ) + + @staticmethod + def parse_key_event_path(path: str) -> Dict[str, str]: + """Parses a key_event path into its component segments.""" + m = re.match( + r"^properties/(?P.+?)/keyEvents/(?P.+?)$", path + ) + return m.groupdict() if m else {} + @staticmethod def measurement_protocol_secret_path( property: str, @@ -689,6 +730,21 @@ def parse_measurement_protocol_secret_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_organization_path(path: str) -> Dict[str, str]: + """Parses a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + @staticmethod def property_path( property: str, @@ -2126,8 +2182,9 @@ def create_firebase_link( The request object. Request message for CreateFirebaseLink RPC parent (str): - Required. Format: properties/{property_id} Example: - properties/1234 + Required. Format: properties/{property_id} + + Example: ``properties/1234`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2216,7 +2273,8 @@ def delete_firebase_link( name (str): Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} - Example: properties/1234/firebaseLinks/5678 + + Example: ``properties/1234/firebaseLinks/5678`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2284,8 +2342,9 @@ def list_firebase_links( The request object. Request message for ListFirebaseLinks RPC parent (str): - Required. Format: properties/{property_id} Example: - properties/1234 + Required. Format: properties/{property_id} + + Example: ``properties/1234`` This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -2380,7 +2439,9 @@ def get_global_site_tag( site tags are singletons and do not have unique IDs. Format: properties/{property_id}/dataStreams/{stream_id}/globalSiteTag - Example: "properties/123/dataStreams/456/globalSiteTag" + + Example: + ``properties/123/dataStreams/456/globalSiteTag`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -2805,11 +2866,10 @@ def get_data_sharing_settings( The request object. Request message for GetDataSharingSettings RPC. name (str): - Required. The name of the settings to - lookup. Format: + Required. The name of the settings to lookup. Format: accounts/{account}/dataSharingSettings - Example: - "accounts/1000/dataSharingSettings" + + Example: ``accounts/1000/dataSharingSettings`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -4144,8 +4204,8 @@ def create_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.ConversionEvent: - r"""Creates a conversion event with the specified - attributes. + r"""Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. Args: request (Union[google.analytics.admin_v1alpha.types.CreateConversionEventRequest, dict]): @@ -4179,6 +4239,11 @@ def create_conversion_event( Analytics property. """ + warnings.warn( + "AnalyticsAdminServiceClient.create_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -4236,8 +4301,8 @@ def update_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.ConversionEvent: - r"""Updates a conversion event with the specified - attributes. + r"""Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. Args: request (Union[google.analytics.admin_v1alpha.types.UpdateConversionEventRequest, dict]): @@ -4272,6 +4337,11 @@ def update_conversion_event( Analytics property. """ + warnings.warn( + "AnalyticsAdminServiceClient.update_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -4330,7 +4400,8 @@ def get_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.ConversionEvent: - r"""Retrieve a single conversion event. + r"""Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. Args: request (Union[google.analytics.admin_v1alpha.types.GetConversionEventRequest, dict]): @@ -4357,6 +4428,11 @@ def get_conversion_event( Analytics property. """ + warnings.warn( + "AnalyticsAdminServiceClient.get_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -4411,7 +4487,8 @@ def delete_conversion_event( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a conversion event in a property. + r"""Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. Args: request (Union[google.analytics.admin_v1alpha.types.DeleteConversionEventRequest, dict]): @@ -4432,6 +4509,11 @@ def delete_conversion_event( metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ + warnings.warn( + "AnalyticsAdminServiceClient.delete_conversion_event is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -4483,8 +4565,9 @@ def list_conversion_events( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListConversionEventsPager: - r"""Returns a list of conversion events in the specified - parent property. + r"""Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + Returns an empty list if no conversion events are found. Args: @@ -4514,6 +4597,11 @@ def list_conversion_events( automatically. """ + warnings.warn( + "AnalyticsAdminServiceClient.list_conversion_events is deprecated", + DeprecationWarning, + ) + # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. @@ -4568,30 +4656,33 @@ def list_conversion_events( # Done; return the response. return response - def get_display_video360_advertiser_link( + def create_key_event( self, - request: Optional[ - Union[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.CreateKeyEventRequest, dict]] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLink: - r"""Look up a single DisplayVideo360AdvertiserLink + ) -> resources.KeyEvent: + r"""Creates a Key Event. Args: - request (Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkRequest, dict]): - The request object. Request message for - GetDisplayVideo360AdvertiserLink RPC. - name (str): - Required. The name of the - DisplayVideo360AdvertiserLink to get. - Example format: - properties/1234/displayVideo360AdvertiserLink/5678 + request (Union[google.analytics.admin_v1alpha.types.CreateKeyEventRequest, dict]): + The request object. Request message for CreateKeyEvent + RPC + parent (str): + Required. The resource name of the + parent property where this Key Event + will be created. Format: properties/123 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to create. + This corresponds to the ``key_event`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -4601,15 +4692,15 @@ def get_display_video360_advertiser_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: - A link between a GA4 property and a - Display & Video 360 advertiser. + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, key_event]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4618,25 +4709,23 @@ def get_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.GetDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(request) + if not isinstance(request, analytics_admin.CreateKeyEventRequest): + request = analytics_admin.CreateKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if key_event is not None: + request.key_event = key_event # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_display_video360_advertiser_link - ] + rpc = self._transport._wrapped_methods[self._transport.create_key_event] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -4653,29 +4742,37 @@ def get_display_video360_advertiser_link( # Done; return the response. return response - def list_display_video360_advertiser_links( + def update_key_event( self, - request: Optional[ - Union[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.UpdateKeyEventRequest, dict]] = None, *, - parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDisplayVideo360AdvertiserLinksPager: - r"""Lists all DisplayVideo360AdvertiserLinks on a - property. + ) -> resources.KeyEvent: + r"""Updates a Key Event. Args: - request (Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest, dict]): - The request object. Request message for - ListDisplayVideo360AdvertiserLinks RPC. - parent (str): - Required. Example format: - properties/1234 + request (Union[google.analytics.admin_v1alpha.types.UpdateKeyEventRequest, dict]): + The request object. Request message for UpdateKeyEvent + RPC + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. - This corresponds to the ``parent`` field + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -4685,18 +4782,15 @@ def list_display_video360_advertiser_links( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinksPager: - Response message for - ListDisplayVideo360AdvertiserLinks RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([key_event, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4705,25 +4799,25 @@ def list_display_video360_advertiser_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.ListDisplayVideo360AdvertiserLinksRequest - ): - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) + if not isinstance(request, analytics_admin.UpdateKeyEventRequest): + request = analytics_admin.UpdateKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if key_event is not None: + request.key_event = key_event + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_display_video360_advertiser_links - ] + rpc = self._transport._wrapped_methods[self._transport.update_key_event] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("key_event.name", request.key_event.name),) + ), ) # Validate the universe domain. @@ -4737,57 +4831,30 @@ def list_display_video360_advertiser_links( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDisplayVideo360AdvertiserLinksPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - def create_display_video360_advertiser_link( + def get_key_event( self, - request: Optional[ - Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetKeyEventRequest, dict]] = None, *, - parent: Optional[str] = None, - display_video_360_advertiser_link: Optional[ - resources.DisplayVideo360AdvertiserLink - ] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLink: - r"""Creates a DisplayVideo360AdvertiserLink. - This can only be utilized by users who have proper - authorization both on the Google Analytics property and - on the Display & Video 360 advertiser. Users who do not - have access to the Display & Video 360 advertiser should - instead seek to create a DisplayVideo360LinkProposal. + ) -> resources.KeyEvent: + r"""Retrieve a single Key Event. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkRequest, dict]): - The request object. Request message for - CreateDisplayVideo360AdvertiserLink RPC. - parent (str): - Required. Example format: - properties/1234 - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): - Required. The - DisplayVideo360AdvertiserLink to create. + request (Union[google.analytics.admin_v1alpha.types.GetKeyEventRequest, dict]): + The request object. Request message for GetKeyEvent RPC + name (str): + Required. The resource name of the Key Event to + retrieve. Format: + properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456" - This corresponds to the ``display_video_360_advertiser_link`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -4797,15 +4864,15 @@ def create_display_video360_advertiser_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: - A link between a GA4 property and a - Display & Video 360 advertiser. + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, display_video_360_advertiser_link]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4814,31 +4881,21 @@ def create_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( - request - ) + if not isinstance(request, analytics_admin.GetKeyEventRequest): + request = analytics_admin.GetKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent - if display_video_360_advertiser_link is not None: - request.display_video_360_advertiser_link = ( - display_video_360_advertiser_link - ) + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.create_display_video360_advertiser_link - ] + rpc = self._transport._wrapped_methods[self._transport.get_key_event] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -4855,29 +4912,25 @@ def create_display_video360_advertiser_link( # Done; return the response. return response - def delete_display_video360_advertiser_link( + def delete_key_event( self, - request: Optional[ - Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.DeleteKeyEventRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a DisplayVideo360AdvertiserLink on a - property. + r"""Deletes a Key Event. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkRequest, dict]): - The request object. Request message for - DeleteDisplayVideo360AdvertiserLink RPC. + request (Union[google.analytics.admin_v1alpha.types.DeleteKeyEventRequest, dict]): + The request object. Request message for DeleteKeyEvent + RPC name (str): - Required. The name of the - DisplayVideo360AdvertiserLink to delete. - Example format: - properties/1234/displayVideo360AdvertiserLinks/5678 + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} + Example: "properties/123/keyEvents/456" This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -4900,12 +4953,8 @@ def delete_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( - request - ) + if not isinstance(request, analytics_admin.DeleteKeyEventRequest): + request = analytics_admin.DeleteKeyEventRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -4913,9 +4962,7 @@ def delete_display_video360_advertiser_link( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.delete_display_video360_advertiser_link - ] + rpc = self._transport._wrapped_methods[self._transport.delete_key_event] # Certain fields should be provided within the metadata header; # add these here. @@ -4934,41 +4981,28 @@ def delete_display_video360_advertiser_link( metadata=metadata, ) - def update_display_video360_advertiser_link( + def list_key_events( self, - request: Optional[ - Union[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListKeyEventsRequest, dict]] = None, *, - display_video_360_advertiser_link: Optional[ - resources.DisplayVideo360AdvertiserLink - ] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLink: - r"""Updates a DisplayVideo360AdvertiserLink on a - property. + ) -> pagers.ListKeyEventsPager: + r"""Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateDisplayVideo360AdvertiserLinkRequest, dict]): - The request object. Request message for - UpdateDisplayVideo360AdvertiserLink RPC. - display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): - The DisplayVideo360AdvertiserLink to - update - - This corresponds to the ``display_video_360_advertiser_link`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + request (Union[google.analytics.admin_v1alpha.types.ListKeyEventsRequest, dict]): + The request object. Request message for ListKeyEvents RPC + parent (str): + Required. The resource name of the + parent property. Example: + 'properties/123' - This corresponds to the ``update_mask`` field + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -4978,15 +5012,18 @@ def update_display_video360_advertiser_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: - A link between a GA4 property and a - Display & Video 360 advertiser. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListKeyEventsPager: + Response message for ListKeyEvents + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([display_video_360_advertiser_link, update_mask]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -4995,38 +5032,21 @@ def update_display_video360_advertiser_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest - ): - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest( - request - ) + if not isinstance(request, analytics_admin.ListKeyEventsRequest): + request = analytics_admin.ListKeyEventsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if display_video_360_advertiser_link is not None: - request.display_video_360_advertiser_link = ( - display_video_360_advertiser_link - ) - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_display_video360_advertiser_link - ] + rpc = self._transport._wrapped_methods[self._transport.list_key_events] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - ( - ( - "display_video_360_advertiser_link.name", - request.display_video_360_advertiser_link.name, - ), - ) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5040,33 +5060,42 @@ def update_display_video360_advertiser_link( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListKeyEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def get_display_video360_advertiser_link_proposal( + def get_display_video360_advertiser_link( self, request: Optional[ - Union[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, dict] + Union[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLinkProposal: - r"""Lookup for a single - DisplayVideo360AdvertiserLinkProposal. + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Look up a single DisplayVideo360AdvertiserLink Args: - request (Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkProposalRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkRequest, dict]): The request object. Request message for - GetDisplayVideo360AdvertiserLinkProposal - RPC. + GetDisplayVideo360AdvertiserLink RPC. name (str): Required. The name of the - DisplayVideo360AdvertiserLinkProposal to - get. Example format: - properties/1234/displayVideo360AdvertiserLinkProposals/5678 + DisplayVideo360AdvertiserLink to get. + Example format: + properties/1234/displayVideo360AdvertiserLink/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -5078,17 +5107,9 @@ def get_display_video360_advertiser_link_proposal( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: - A proposal for a link between a GA4 - property and a Display & Video 360 - advertiser. - - A proposal is converted to a - DisplayVideo360AdvertiserLink once - approved. Google Analytics admins - approve inbound proposals while Display - & Video 360 admins approve outbound - proposals. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. """ # Create or coerce a protobuf request object. @@ -5104,11 +5125,9 @@ def get_display_video360_advertiser_link_proposal( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.GetDisplayVideo360AdvertiserLinkRequest ): - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -5117,7 +5136,7 @@ def get_display_video360_advertiser_link_proposal( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.get_display_video360_advertiser_link_proposal + self._transport.get_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; @@ -5140,27 +5159,24 @@ def get_display_video360_advertiser_link_proposal( # Done; return the response. return response - def list_display_video360_advertiser_link_proposals( + def list_display_video360_advertiser_links( self, request: Optional[ - Union[ - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict - ] + Union[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, dict] ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDisplayVideo360AdvertiserLinkProposalsPager: - r"""Lists DisplayVideo360AdvertiserLinkProposals on a + ) -> pagers.ListDisplayVideo360AdvertiserLinksPager: + r"""Lists all DisplayVideo360AdvertiserLinks on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest, dict]): The request object. Request message for - ListDisplayVideo360AdvertiserLinkProposals - RPC. + ListDisplayVideo360AdvertiserLinks RPC. parent (str): Required. Example format: properties/1234 @@ -5175,12 +5191,12 @@ def list_display_video360_advertiser_link_proposals( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinkProposalsPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinksPager: Response message for - ListDisplayVideo360AdvertiserLinkProposals - RPC. Iterating over this object will - yield results and resolve additional - pages automatically. + ListDisplayVideo360AdvertiserLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. @@ -5196,11 +5212,9 @@ def list_display_video360_advertiser_link_proposals( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest + request, analytics_admin.ListDisplayVideo360AdvertiserLinksRequest ): - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( - request - ) + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -5209,7 +5223,7 @@ def list_display_video360_advertiser_link_proposals( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.list_display_video360_advertiser_link_proposals + self._transport.list_display_video360_advertiser_links ] # Certain fields should be provided within the metadata header; @@ -5231,7 +5245,7 @@ def list_display_video360_advertiser_link_proposals( # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListDisplayVideo360AdvertiserLinkProposalsPager( + response = pagers.ListDisplayVideo360AdvertiserLinksPager( method=rpc, request=request, response=response, @@ -5243,29 +5257,31 @@ def list_display_video360_advertiser_link_proposals( # Done; return the response. return response - def create_display_video360_advertiser_link_proposal( + def create_display_video360_advertiser_link( self, request: Optional[ - Union[ - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict - ] + Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, parent: Optional[str] = None, - display_video_360_advertiser_link_proposal: Optional[ - resources.DisplayVideo360AdvertiserLinkProposal + display_video_360_advertiser_link: Optional[ + resources.DisplayVideo360AdvertiserLink ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DisplayVideo360AdvertiserLinkProposal: - r"""Creates a DisplayVideo360AdvertiserLinkProposal. + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Creates a DisplayVideo360AdvertiserLink. + This can only be utilized by users who have proper + authorization both on the Google Analytics property and + on the Display & Video 360 advertiser. Users who do not + have access to the Display & Video 360 advertiser should + instead seek to create a DisplayVideo360LinkProposal. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkRequest, dict]): The request object. Request message for - CreateDisplayVideo360AdvertiserLinkProposal - RPC. + CreateDisplayVideo360AdvertiserLink RPC. parent (str): Required. Example format: properties/1234 @@ -5273,12 +5289,11 @@ def create_display_video360_advertiser_link_proposal( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - display_video_360_advertiser_link_proposal (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal): + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): Required. The - DisplayVideo360AdvertiserLinkProposal to - create. + DisplayVideo360AdvertiserLink to create. - This corresponds to the ``display_video_360_advertiser_link_proposal`` field + This corresponds to the ``display_video_360_advertiser_link`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -5288,23 +5303,15 @@ def create_display_video360_advertiser_link_proposal( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: - A proposal for a link between a GA4 - property and a Display & Video 360 - advertiser. - - A proposal is converted to a - DisplayVideo360AdvertiserLink once - approved. Google Analytics admins - approve inbound proposals while Display - & Video 360 admins approve outbound - proposals. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, display_video_360_advertiser_link_proposal]) + has_flattened_params = any([parent, display_video_360_advertiser_link]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5314,26 +5321,24 @@ def create_display_video360_advertiser_link_proposal( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest ): - request = ( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( + request ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if display_video_360_advertiser_link_proposal is not None: - request.display_video_360_advertiser_link_proposal = ( - display_video_360_advertiser_link_proposal + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = ( + display_video_360_advertiser_link ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.create_display_video360_advertiser_link_proposal + self._transport.create_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; @@ -5356,12 +5361,10 @@ def create_display_video360_advertiser_link_proposal( # Done; return the response. return response - def delete_display_video360_advertiser_link_proposal( + def delete_display_video360_advertiser_link( self, request: Optional[ - Union[ - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict - ] + Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, name: Optional[str] = None, @@ -5369,19 +5372,18 @@ def delete_display_video360_advertiser_link_proposal( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a DisplayVideo360AdvertiserLinkProposal on a - property. This can only be used on cancelled proposals. + r"""Deletes a DisplayVideo360AdvertiserLink on a + property. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkRequest, dict]): The request object. Request message for - DeleteDisplayVideo360AdvertiserLinkProposal - RPC. + DeleteDisplayVideo360AdvertiserLink RPC. name (str): Required. The name of the - DisplayVideo360AdvertiserLinkProposal to - delete. Example format: - properties/1234/displayVideo360AdvertiserLinkProposals/5678 + DisplayVideo360AdvertiserLink to delete. + Example format: + properties/1234/displayVideo360AdvertiserLinks/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -5405,12 +5407,10 @@ def delete_display_video360_advertiser_link_proposal( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest ): - request = ( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( + request ) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -5420,7 +5420,7 @@ def delete_display_video360_advertiser_link_proposal( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.delete_display_video360_advertiser_link_proposal + self._transport.delete_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; @@ -5440,29 +5440,43 @@ def delete_display_video360_advertiser_link_proposal( metadata=metadata, ) - def approve_display_video360_advertiser_link_proposal( + def update_display_video360_advertiser_link( self, request: Optional[ - Union[ - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, - dict, - ] + Union[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict] ] = None, *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, + display_video_360_advertiser_link: Optional[ + resources.DisplayVideo360AdvertiserLink + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: - r"""Approves a DisplayVideo360AdvertiserLinkProposal. - The DisplayVideo360AdvertiserLinkProposal will be - deleted and a new DisplayVideo360AdvertiserLink will be - created. + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Updates a DisplayVideo360AdvertiserLink on a + property. Args: - request (Union[google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateDisplayVideo360AdvertiserLinkRequest, dict]): The request object. Request message for - ApproveDisplayVideo360AdvertiserLinkProposal - RPC. + UpdateDisplayVideo360AdvertiserLink RPC. + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + The DisplayVideo360AdvertiserLink to + update + + This corresponds to the ``display_video_360_advertiser_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5470,34 +5484,55 @@ def approve_display_video360_advertiser_link_proposal( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalResponse: - Response message for - ApproveDisplayVideo360AdvertiserLinkProposal - RPC. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([display_video_360_advertiser_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest ): - request = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest( + request ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = ( + display_video_360_advertiser_link + ) + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.approve_display_video360_advertiser_link_proposal + self._transport.update_display_video360_advertiser_link ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "display_video_360_advertiser_link.name", + request.display_video_360_advertiser_link.name, + ), + ) + ), ) # Validate the universe domain. @@ -5514,32 +5549,34 @@ def approve_display_video360_advertiser_link_proposal( # Done; return the response. return response - def cancel_display_video360_advertiser_link_proposal( + def get_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[ - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict - ] + Union[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, dict] ] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> resources.DisplayVideo360AdvertiserLinkProposal: - r"""Cancels a DisplayVideo360AdvertiserLinkProposal. - Cancelling can mean either: - - - Declining a proposal initiated from Display & Video - 360 - - Withdrawing a proposal initiated from Google Analytics - After being cancelled, a proposal will eventually be - deleted automatically. + r"""Lookup for a single + DisplayVideo360AdvertiserLinkProposal. Args: - request (Union[google.analytics.admin_v1alpha.types.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkProposalRequest, dict]): The request object. Request message for - CancelDisplayVideo360AdvertiserLinkProposal + GetDisplayVideo360AdvertiserLinkProposal RPC. + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + get. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5561,21 +5598,32 @@ def cancel_display_video360_advertiser_link_proposal( """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest + request, analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest ): - request = ( - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( - request - ) + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( + request ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.cancel_display_video360_advertiser_link_proposal + self._transport.get_display_video360_advertiser_link_proposal ] # Certain fields should be provided within the metadata header; @@ -5598,24 +5646,27 @@ def cancel_display_video360_advertiser_link_proposal( # Done; return the response. return response - def create_custom_dimension( + def list_display_video360_advertiser_link_proposals( self, request: Optional[ - Union[analytics_admin.CreateCustomDimensionRequest, dict] + Union[ + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict + ] ] = None, *, parent: Optional[str] = None, - custom_dimension: Optional[resources.CustomDimension] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomDimension: - r"""Creates a CustomDimension. + ) -> pagers.ListDisplayVideo360AdvertiserLinkProposalsPager: + r"""Lists DisplayVideo360AdvertiserLinkProposals on a + property. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateCustomDimensionRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict]): The request object. Request message for - CreateCustomDimension RPC. + ListDisplayVideo360AdvertiserLinkProposals + RPC. parent (str): Required. Example format: properties/1234 @@ -5623,13 +5674,6 @@ def create_custom_dimension( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): - Required. The CustomDimension to - create. - - This corresponds to the ``custom_dimension`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5637,13 +5681,18 @@ def create_custom_dimension( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomDimension: - A definition for a CustomDimension. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinkProposalsPager: + Response message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. Iterating over this object will + yield results and resolve additional + pages automatically. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, custom_dimension]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5652,18 +5701,22 @@ def create_custom_dimension( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): - request = analytics_admin.CreateCustomDimensionRequest(request) + if not isinstance( + request, analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest + ): + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if custom_dimension is not None: - request.custom_dimension = custom_dimension # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_custom_dimension] + rpc = self._transport._wrapped_methods[ + self._transport.list_display_video360_advertiser_link_proposals + ] # Certain fields should be provided within the metadata header; # add these here. @@ -5682,39 +5735,56 @@ def create_custom_dimension( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDisplayVideo360AdvertiserLinkProposalsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def update_custom_dimension( + def create_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.UpdateCustomDimensionRequest, dict] + Union[ + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict + ] ] = None, *, - custom_dimension: Optional[resources.CustomDimension] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, + display_video_360_advertiser_link_proposal: Optional[ + resources.DisplayVideo360AdvertiserLinkProposal + ] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomDimension: - r"""Updates a CustomDimension on a property. + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Creates a DisplayVideo360AdvertiserLinkProposal. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateCustomDimensionRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]): The request object. Request message for - UpdateCustomDimension RPC. - custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): - The CustomDimension to update - This corresponds to the ``custom_dimension`` field + CreateDisplayVideo360AdvertiserLinkProposal + RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + display_video_360_advertiser_link_proposal (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal): + Required. The + DisplayVideo360AdvertiserLinkProposal to + create. - This corresponds to the ``update_mask`` field + This corresponds to the ``display_video_360_advertiser_link_proposal`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -5724,13 +5794,23 @@ def update_custom_dimension( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomDimension: - A definition for a CustomDimension. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([custom_dimension, update_mask]) + has_flattened_params = any([parent, display_video_360_advertiser_link_proposal]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5739,25 +5819,33 @@ def update_custom_dimension( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): - request = analytics_admin.UpdateCustomDimensionRequest(request) + if not isinstance( + request, analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if custom_dimension is not None: - request.custom_dimension = custom_dimension - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent + if display_video_360_advertiser_link_proposal is not None: + request.display_video_360_advertiser_link_proposal = ( + display_video_360_advertiser_link_proposal + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_custom_dimension] + rpc = self._transport._wrapped_methods[ + self._transport.create_display_video360_advertiser_link_proposal + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("custom_dimension.name", request.custom_dimension.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -5774,28 +5862,34 @@ def update_custom_dimension( # Done; return the response. return response - def list_custom_dimensions( + def delete_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.ListCustomDimensionsRequest, dict] + Union[ + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict + ] ] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCustomDimensionsPager: - r"""Lists CustomDimensions on a property. + ) -> None: + r"""Deletes a DisplayVideo360AdvertiserLinkProposal on a + property. This can only be used on cancelled proposals. Args: - request (Union[google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict]): The request object. Request message for - ListCustomDimensions RPC. - parent (str): - Required. Example format: - properties/1234 + DeleteDisplayVideo360AdvertiserLinkProposal + RPC. + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + delete. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 - This corresponds to the ``parent`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -5803,20 +5897,11 @@ def list_custom_dimensions( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomDimensionsPager: - Response message for - ListCustomDimensions RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -5825,102 +5910,95 @@ def list_custom_dimensions( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): - request = analytics_admin.ListCustomDimensionsRequest(request) + if not isinstance( + request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_custom_dimensions] + rpc = self._transport._wrapped_methods[ + self._transport.delete_display_video360_advertiser_link_proposal + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCustomDimensionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def archive_custom_dimension( + def approve_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.ArchiveCustomDimensionRequest, dict] + Union[ + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + dict, + ] ] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Archives a CustomDimension on a property. + ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + r"""Approves a DisplayVideo360AdvertiserLinkProposal. + The DisplayVideo360AdvertiserLinkProposal will be + deleted and a new DisplayVideo360AdvertiserLink will be + created. Args: - request (Union[google.analytics.admin_v1alpha.types.ArchiveCustomDimensionRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]): The request object. Request message for - ArchiveCustomDimension RPC. - name (str): - Required. The name of the - CustomDimension to archive. Example - format: - properties/1234/customDimensions/5678 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + Response message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): - request = analytics_admin.ArchiveCustomDimensionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance( + request, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.archive_custom_dimension] + rpc = self._transport._wrapped_methods[ + self._transport.approve_display_video360_advertiser_link_proposal + ] # Certain fields should be provided within the metadata header; # add these here. @@ -5932,38 +6010,42 @@ def archive_custom_dimension( self._validate_universe_domain() # Send the request. - rpc( + response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - def get_custom_dimension( + # Done; return the response. + return response + + def cancel_display_video360_advertiser_link_proposal( self, request: Optional[ - Union[analytics_admin.GetCustomDimensionRequest, dict] + Union[ + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict + ] ] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomDimension: - r"""Lookup for a single CustomDimension. + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Cancels a DisplayVideo360AdvertiserLinkProposal. + Cancelling can mean either: + + - Declining a proposal initiated from Display & Video + 360 + - Withdrawing a proposal initiated from Google Analytics + After being cancelled, a proposal will eventually be + deleted automatically. Args: - request (Union[google.analytics.admin_v1alpha.types.GetCustomDimensionRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]): The request object. Request message for - GetCustomDimension RPC. - name (str): - Required. The name of the - CustomDimension to get. Example format: - properties/1234/customDimensions/5678 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + CancelDisplayVideo360AdvertiserLinkProposal + RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5971,31 +6053,36 @@ def get_custom_dimension( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomDimension: - A definition for a CustomDimension. + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetCustomDimensionRequest): - request = analytics_admin.GetCustomDimensionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance( + request, analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest + ): + request = ( + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( + request + ) + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_custom_dimension] + rpc = self._transport._wrapped_methods[ + self._transport.cancel_display_video360_advertiser_link_proposal + ] # Certain fields should be provided within the metadata header; # add these here. @@ -6017,24 +6104,24 @@ def get_custom_dimension( # Done; return the response. return response - def create_custom_metric( + def create_custom_dimension( self, request: Optional[ - Union[analytics_admin.CreateCustomMetricRequest, dict] + Union[analytics_admin.CreateCustomDimensionRequest, dict] ] = None, *, parent: Optional[str] = None, - custom_metric: Optional[resources.CustomMetric] = None, + custom_dimension: Optional[resources.CustomDimension] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomMetric: - r"""Creates a CustomMetric. + ) -> resources.CustomDimension: + r"""Creates a CustomDimension. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateCustomMetricRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateCustomDimensionRequest, dict]): The request object. Request message for - CreateCustomMetric RPC. + CreateCustomDimension RPC. parent (str): Required. Example format: properties/1234 @@ -6042,9 +6129,11 @@ def create_custom_metric( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): - Required. The CustomMetric to create. - This corresponds to the ``custom_metric`` field + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + Required. The CustomDimension to + create. + + This corresponds to the ``custom_dimension`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -6054,13 +6143,13 @@ def create_custom_metric( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomMetric: - A definition for a custom metric. + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, custom_metric]) + has_flattened_params = any([parent, custom_dimension]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6069,18 +6158,18 @@ def create_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateCustomMetricRequest): - request = analytics_admin.CreateCustomMetricRequest(request) + if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): + request = analytics_admin.CreateCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if custom_metric is not None: - request.custom_metric = custom_metric + if custom_dimension is not None: + request.custom_dimension = custom_dimension # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_custom_metric] + rpc = self._transport._wrapped_methods[self._transport.create_custom_dimension] # Certain fields should be provided within the metadata header; # add these here. @@ -6102,27 +6191,27 @@ def create_custom_metric( # Done; return the response. return response - def update_custom_metric( + def update_custom_dimension( self, request: Optional[ - Union[analytics_admin.UpdateCustomMetricRequest, dict] + Union[analytics_admin.UpdateCustomDimensionRequest, dict] ] = None, *, - custom_metric: Optional[resources.CustomMetric] = None, + custom_dimension: Optional[resources.CustomDimension] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomMetric: - r"""Updates a CustomMetric on a property. + ) -> resources.CustomDimension: + r"""Updates a CustomDimension on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateCustomMetricRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateCustomDimensionRequest, dict]): The request object. Request message for - UpdateCustomMetric RPC. - custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): - The CustomMetric to update - This corresponds to the ``custom_metric`` field + UpdateCustomDimension RPC. + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + The CustomDimension to update + This corresponds to the ``custom_dimension`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): @@ -6141,13 +6230,13 @@ def update_custom_metric( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomMetric: - A definition for a custom metric. + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([custom_metric, update_mask]) + has_flattened_params = any([custom_dimension, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6156,24 +6245,24 @@ def update_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): - request = analytics_admin.UpdateCustomMetricRequest(request) + if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): + request = analytics_admin.UpdateCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if custom_metric is not None: - request.custom_metric = custom_metric + if custom_dimension is not None: + request.custom_dimension = custom_dimension if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_custom_metric] + rpc = self._transport._wrapped_methods[self._transport.update_custom_dimension] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("custom_metric.name", request.custom_metric.name),) + (("custom_dimension.name", request.custom_dimension.name),) ), ) @@ -6191,21 +6280,23 @@ def update_custom_metric( # Done; return the response. return response - def list_custom_metrics( + def list_custom_dimensions( self, - request: Optional[Union[analytics_admin.ListCustomMetricsRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ListCustomDimensionsRequest, dict] + ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCustomMetricsPager: - r"""Lists CustomMetrics on a property. + ) -> pagers.ListCustomDimensionsPager: + r"""Lists CustomDimensions on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListCustomMetricsRequest, dict]): - The request object. Request message for ListCustomMetrics - RPC. + request (Union[google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest, dict]): + The request object. Request message for + ListCustomDimensions RPC. parent (str): Required. Example format: properties/1234 @@ -6220,9 +6311,9 @@ def list_custom_metrics( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomMetricsPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomDimensionsPager: Response message for - ListCustomMetrics RPC. + ListCustomDimensions RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -6240,8 +6331,8 @@ def list_custom_metrics( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListCustomMetricsRequest): - request = analytics_admin.ListCustomMetricsRequest(request) + if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): + request = analytics_admin.ListCustomDimensionsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -6249,7 +6340,7 @@ def list_custom_metrics( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_custom_metrics] + rpc = self._transport._wrapped_methods[self._transport.list_custom_dimensions] # Certain fields should be provided within the metadata header; # add these here. @@ -6270,7 +6361,7 @@ def list_custom_metrics( # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListCustomMetricsPager( + response = pagers.ListCustomDimensionsPager( method=rpc, request=request, response=response, @@ -6282,10 +6373,10 @@ def list_custom_metrics( # Done; return the response. return response - def archive_custom_metric( + def archive_custom_dimension( self, request: Optional[ - Union[analytics_admin.ArchiveCustomMetricRequest, dict] + Union[analytics_admin.ArchiveCustomDimensionRequest, dict] ] = None, *, name: Optional[str] = None, @@ -6293,16 +6384,17 @@ def archive_custom_metric( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Archives a CustomMetric on a property. + r"""Archives a CustomDimension on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.ArchiveCustomMetricRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ArchiveCustomDimensionRequest, dict]): The request object. Request message for - ArchiveCustomMetric RPC. + ArchiveCustomDimension RPC. name (str): Required. The name of the - CustomMetric to archive. Example format: - properties/1234/customMetrics/5678 + CustomDimension to archive. Example + format: + properties/1234/customDimensions/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -6325,8 +6417,8 @@ def archive_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): - request = analytics_admin.ArchiveCustomMetricRequest(request) + if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): + request = analytics_admin.ArchiveCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -6334,7 +6426,7 @@ def archive_custom_metric( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.archive_custom_metric] + rpc = self._transport._wrapped_methods[self._transport.archive_custom_dimension] # Certain fields should be provided within the metadata header; # add these here. @@ -6353,25 +6445,27 @@ def archive_custom_metric( metadata=metadata, ) - def get_custom_metric( + def get_custom_dimension( self, - request: Optional[Union[analytics_admin.GetCustomMetricRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.GetCustomDimensionRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CustomMetric: - r"""Lookup for a single CustomMetric. + ) -> resources.CustomDimension: + r"""Lookup for a single CustomDimension. Args: - request (Union[google.analytics.admin_v1alpha.types.GetCustomMetricRequest, dict]): - The request object. Request message for GetCustomMetric - RPC. + request (Union[google.analytics.admin_v1alpha.types.GetCustomDimensionRequest, dict]): + The request object. Request message for + GetCustomDimension RPC. name (str): Required. The name of the - CustomMetric to get. Example format: - properties/1234/customMetrics/5678 + CustomDimension to get. Example format: + properties/1234/customDimensions/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -6383,8 +6477,8 @@ def get_custom_metric( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CustomMetric: - A definition for a custom metric. + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -6398,8 +6492,8 @@ def get_custom_metric( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetCustomMetricRequest): - request = analytics_admin.GetCustomMetricRequest(request) + if not isinstance(request, analytics_admin.GetCustomDimensionRequest): + request = analytics_admin.GetCustomDimensionRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -6407,7 +6501,7 @@ def get_custom_metric( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_custom_metric] + rpc = self._transport._wrapped_methods[self._transport.get_custom_dimension] # Certain fields should be provided within the metadata header; # add these here. @@ -6429,33 +6523,34 @@ def get_custom_metric( # Done; return the response. return response - def get_data_retention_settings( + def create_custom_metric( self, request: Optional[ - Union[analytics_admin.GetDataRetentionSettingsRequest, dict] + Union[analytics_admin.CreateCustomMetricRequest, dict] ] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + custom_metric: Optional[resources.CustomMetric] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataRetentionSettings: - r"""Returns the singleton data retention settings for - this property. + ) -> resources.CustomMetric: + r"""Creates a CustomMetric. Args: - request (Union[google.analytics.admin_v1alpha.types.GetDataRetentionSettingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateCustomMetricRequest, dict]): The request object. Request message for - GetDataRetentionSettings RPC. - name (str): - Required. The name of the settings to - lookup. Format: - - properties/{property}/dataRetentionSettings - Example: - "properties/1000/dataRetentionSettings" + CreateCustomMetric RPC. + parent (str): + Required. Example format: + properties/1234 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + Required. The CustomMetric to create. + This corresponds to the ``custom_metric`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -6465,15 +6560,13 @@ def get_data_retention_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataRetentionSettings: - Settings values for data retention. - This is a singleton resource. - + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, custom_metric]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6482,23 +6575,23 @@ def get_data_retention_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): - request = analytics_admin.GetDataRetentionSettingsRequest(request) + if not isinstance(request, analytics_admin.CreateCustomMetricRequest): + request = analytics_admin.CreateCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if custom_metric is not None: + request.custom_metric = custom_metric # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_data_retention_settings - ] + rpc = self._transport._wrapped_methods[self._transport.create_custom_metric] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -6515,35 +6608,31 @@ def get_data_retention_settings( # Done; return the response. return response - def update_data_retention_settings( + def update_custom_metric( self, request: Optional[ - Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict] + Union[analytics_admin.UpdateCustomMetricRequest, dict] ] = None, *, - data_retention_settings: Optional[resources.DataRetentionSettings] = None, + custom_metric: Optional[resources.CustomMetric] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataRetentionSettings: - r"""Updates the singleton data retention settings for - this property. + ) -> resources.CustomMetric: + r"""Updates a CustomMetric on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateDataRetentionSettingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateCustomMetricRequest, dict]): The request object. Request message for - UpdateDataRetentionSettings RPC. - data_retention_settings (google.analytics.admin_v1alpha.types.DataRetentionSettings): - Required. The settings to update. The ``name`` field is - used to identify the settings to be updated. - - This corresponds to the ``data_retention_settings`` field + UpdateCustomMetric RPC. + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + The CustomMetric to update + This corresponds to the ``custom_metric`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted + Required. The list of fields to be updated. Omitted fields will not be updated. To replace the entire entity, use one path with the string "*" to match all fields. @@ -6558,15 +6647,13 @@ def update_data_retention_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataRetentionSettings: - Settings values for data retention. - This is a singleton resource. - + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([data_retention_settings, update_mask]) + has_flattened_params = any([custom_metric, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6575,31 +6662,24 @@ def update_data_retention_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): - request = analytics_admin.UpdateDataRetentionSettingsRequest(request) + if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): + request = analytics_admin.UpdateCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if data_retention_settings is not None: - request.data_retention_settings = data_retention_settings + if custom_metric is not None: + request.custom_metric = custom_metric if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_data_retention_settings - ] + rpc = self._transport._wrapped_methods[self._transport.update_custom_metric] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - ( - ( - "data_retention_settings.name", - request.data_retention_settings.name, - ), - ) + (("custom_metric.name", request.custom_metric.name),) ), ) @@ -6617,21 +6697,20 @@ def update_data_retention_settings( # Done; return the response. return response - def create_data_stream( + def list_custom_metrics( self, - request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, + request: Optional[Union[analytics_admin.ListCustomMetricsRequest, dict]] = None, *, parent: Optional[str] = None, - data_stream: Optional[resources.DataStream] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataStream: - r"""Creates a DataStream. + ) -> pagers.ListCustomMetricsPager: + r"""Lists CustomMetrics on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateDataStreamRequest, dict]): - The request object. Request message for CreateDataStream + request (Union[google.analytics.admin_v1alpha.types.ListCustomMetricsRequest, dict]): + The request object. Request message for ListCustomMetrics RPC. parent (str): Required. Example format: @@ -6640,11 +6719,6 @@ def create_data_stream( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - data_stream (google.analytics.admin_v1alpha.types.DataStream): - Required. The DataStream to create. - This corresponds to the ``data_stream`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6652,15 +6726,18 @@ def create_data_stream( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataStream: - A resource message representing a - data stream. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomMetricsPager: + Response message for + ListCustomMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, data_stream]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6669,18 +6746,16 @@ def create_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateDataStreamRequest): - request = analytics_admin.CreateDataStreamRequest(request) + if not isinstance(request, analytics_admin.ListCustomMetricsRequest): + request = analytics_admin.ListCustomMetricsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if data_stream is not None: - request.data_stream = data_stream # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_data_stream] + rpc = self._transport._wrapped_methods[self._transport.list_custom_metrics] # Certain fields should be provided within the metadata header; # add these here. @@ -6699,28 +6774,41 @@ def create_data_stream( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCustomMetricsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def delete_data_stream( + def archive_custom_metric( self, - request: Optional[Union[analytics_admin.DeleteDataStreamRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ArchiveCustomMetricRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a DataStream on a property. + r"""Archives a CustomMetric on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteDataStreamRequest, dict]): - The request object. Request message for DeleteDataStream - RPC. + request (Union[google.analytics.admin_v1alpha.types.ArchiveCustomMetricRequest, dict]): + The request object. Request message for + ArchiveCustomMetric RPC. name (str): - Required. The name of the DataStream - to delete. Example format: - properties/1234/dataStreams/5678 + Required. The name of the + CustomMetric to archive. Example format: + properties/1234/customMetrics/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -6743,8 +6831,8 @@ def delete_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteDataStreamRequest): - request = analytics_admin.DeleteDataStreamRequest(request) + if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): + request = analytics_admin.ArchiveCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -6752,7 +6840,7 @@ def delete_data_stream( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_data_stream] + rpc = self._transport._wrapped_methods[self._transport.archive_custom_metric] # Certain fields should be provided within the metadata header; # add these here. @@ -6771,34 +6859,27 @@ def delete_data_stream( metadata=metadata, ) - def update_data_stream( + def get_custom_metric( self, - request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, + request: Optional[Union[analytics_admin.GetCustomMetricRequest, dict]] = None, *, - data_stream: Optional[resources.DataStream] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataStream: - r"""Updates a DataStream on a property. + ) -> resources.CustomMetric: + r"""Lookup for a single CustomMetric. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateDataStreamRequest, dict]): - The request object. Request message for UpdateDataStream + request (Union[google.analytics.admin_v1alpha.types.GetCustomMetricRequest, dict]): + The request object. Request message for GetCustomMetric RPC. - data_stream (google.analytics.admin_v1alpha.types.DataStream): - The DataStream to update - This corresponds to the ``data_stream`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + name (str): + Required. The name of the + CustomMetric to get. Example format: + properties/1234/customMetrics/5678 - This corresponds to the ``update_mask`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -6808,15 +6889,13 @@ def update_data_stream( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataStream: - A resource message representing a - data stream. - + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([data_stream, update_mask]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6825,25 +6904,21 @@ def update_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateDataStreamRequest): - request = analytics_admin.UpdateDataStreamRequest(request) + if not isinstance(request, analytics_admin.GetCustomMetricRequest): + request = analytics_admin.GetCustomMetricRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if data_stream is not None: - request.data_stream = data_stream - if update_mask is not None: - request.update_mask = update_mask + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_data_stream] + rpc = self._transport._wrapped_methods[self._transport.get_custom_metric] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("data_stream.name", request.data_stream.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -6860,26 +6935,33 @@ def update_data_stream( # Done; return the response. return response - def list_data_streams( + def get_data_retention_settings( self, - request: Optional[Union[analytics_admin.ListDataStreamsRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.GetDataRetentionSettingsRequest, dict] + ] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataStreamsPager: - r"""Lists DataStreams on a property. + ) -> resources.DataRetentionSettings: + r"""Returns the singleton data retention settings for + this property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListDataStreamsRequest, dict]): - The request object. Request message for ListDataStreams - RPC. - parent (str): - Required. Example format: - properties/1234 + request (Union[google.analytics.admin_v1alpha.types.GetDataRetentionSettingsRequest, dict]): + The request object. Request message for + GetDataRetentionSettings RPC. + name (str): + Required. The name of the settings to + lookup. Format: - This corresponds to the ``parent`` field + properties/{property}/dataRetentionSettings + Example: + "properties/1000/dataRetentionSettings" + + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -6889,18 +6971,15 @@ def list_data_streams( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDataStreamsPager: - Response message for ListDataStreams - RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6909,21 +6988,23 @@ def list_data_streams( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListDataStreamsRequest): - request = analytics_admin.ListDataStreamsRequest(request) + if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): + request = analytics_admin.GetDataRetentionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_data_streams] + rpc = self._transport._wrapped_methods[ + self._transport.get_data_retention_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -6937,41 +7018,43 @@ def list_data_streams( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDataStreamsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - def get_data_stream( + def update_data_retention_settings( self, - request: Optional[Union[analytics_admin.GetDataStreamRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict] + ] = None, *, - name: Optional[str] = None, + data_retention_settings: Optional[resources.DataRetentionSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.DataStream: - r"""Lookup for a single DataStream. + ) -> resources.DataRetentionSettings: + r"""Updates the singleton data retention settings for + this property. Args: - request (Union[google.analytics.admin_v1alpha.types.GetDataStreamRequest, dict]): - The request object. Request message for GetDataStream - RPC. - name (str): - Required. The name of the DataStream - to get. Example format: - properties/1234/dataStreams/5678 + request (Union[google.analytics.admin_v1alpha.types.UpdateDataRetentionSettingsRequest, dict]): + The request object. Request message for + UpdateDataRetentionSettings RPC. + data_retention_settings (google.analytics.admin_v1alpha.types.DataRetentionSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. - This corresponds to the ``name`` field + This corresponds to the ``data_retention_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -6981,15 +7064,15 @@ def get_data_stream( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.DataStream: - A resource message representing a - data stream. + google.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([data_retention_settings, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -6998,21 +7081,32 @@ def get_data_stream( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetDataStreamRequest): - request = analytics_admin.GetDataStreamRequest(request) + if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): + request = analytics_admin.UpdateDataRetentionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if data_retention_settings is not None: + request.data_retention_settings = data_retention_settings + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_data_stream] + rpc = self._transport._wrapped_methods[ + self._transport.update_data_retention_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "data_retention_settings.name", + request.data_retention_settings.name, + ), + ) + ), ) # Validate the universe domain. @@ -7029,28 +7123,32 @@ def get_data_stream( # Done; return the response. return response - def get_audience( + def create_data_stream( self, - request: Optional[Union[analytics_admin.GetAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + data_stream: Optional[resources.DataStream] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> audience.Audience: - r"""Lookup for a single Audience. - Audiences created before 2020 may not be supported. - Default audiences will not show filter definitions. + ) -> resources.DataStream: + r"""Creates a DataStream. Args: - request (Union[google.analytics.admin_v1alpha.types.GetAudienceRequest, dict]): - The request object. Request message for GetAudience RPC. - name (str): - Required. The name of the Audience to - get. Example format: - properties/1234/audiences/5678 + request (Union[google.analytics.admin_v1alpha.types.CreateDataStreamRequest, dict]): + The request object. Request message for CreateDataStream + RPC. + parent (str): + Required. Example format: + properties/1234 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_stream (google.analytics.admin_v1alpha.types.DataStream): + Required. The DataStream to create. + This corresponds to the ``data_stream`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7060,15 +7158,15 @@ def get_audience( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.Audience: - A resource message representing a GA4 - Audience. + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, data_stream]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7077,21 +7175,23 @@ def get_audience( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAudienceRequest): - request = analytics_admin.GetAudienceRequest(request) + if not isinstance(request, analytics_admin.CreateDataStreamRequest): + request = analytics_admin.CreateDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if data_stream is not None: + request.data_stream = data_stream # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_audience] + rpc = self._transport._wrapped_methods[self._transport.create_data_stream] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -7108,28 +7208,27 @@ def get_audience( # Done; return the response. return response - def list_audiences( + def delete_data_stream( self, - request: Optional[Union[analytics_admin.ListAudiencesRequest, dict]] = None, + request: Optional[Union[analytics_admin.DeleteDataStreamRequest, dict]] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAudiencesPager: - r"""Lists Audiences on a property. - Audiences created before 2020 may not be supported. - Default audiences will not show filter definitions. + ) -> None: + r"""Deletes a DataStream on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListAudiencesRequest, dict]): - The request object. Request message for ListAudiences + request (Union[google.analytics.admin_v1alpha.types.DeleteDataStreamRequest, dict]): + The request object. Request message for DeleteDataStream RPC. - parent (str): - Required. Example format: - properties/1234 + name (str): + Required. The name of the DataStream + to delete. Example format: + properties/1234/dataStreams/5678 - This corresponds to the ``parent`` field + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7137,20 +7236,11 @@ def list_audiences( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAudiencesPager: - Response message for ListAudiences - RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7159,74 +7249,62 @@ def list_audiences( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListAudiencesRequest): - request = analytics_admin.ListAudiencesRequest(request) + if not isinstance(request, analytics_admin.DeleteDataStreamRequest): + request = analytics_admin.DeleteDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_audiences] + rpc = self._transport._wrapped_methods[self._transport.delete_data_stream] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAudiencesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_audience( + def update_data_stream( self, - request: Optional[Union[analytics_admin.CreateAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, *, - parent: Optional[str] = None, - audience: Optional[gaa_audience.Audience] = None, + data_stream: Optional[resources.DataStream] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_audience.Audience: - r"""Creates an Audience. + ) -> resources.DataStream: + r"""Updates a DataStream on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateAudienceRequest, dict]): - The request object. Request message for CreateAudience + request (Union[google.analytics.admin_v1alpha.types.UpdateDataStreamRequest, dict]): + The request object. Request message for UpdateDataStream RPC. - parent (str): - Required. Example format: - properties/1234 - - This corresponds to the ``parent`` field + data_stream (google.analytics.admin_v1alpha.types.DataStream): + The DataStream to update + This corresponds to the ``data_stream`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - audience (google.analytics.admin_v1alpha.types.Audience): - Required. The audience to create. - This corresponds to the ``audience`` field + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7236,15 +7314,15 @@ def create_audience( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.Audience: - A resource message representing a GA4 - Audience. + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, audience]) + has_flattened_params = any([data_stream, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7253,23 +7331,25 @@ def create_audience( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateAudienceRequest): - request = analytics_admin.CreateAudienceRequest(request) + if not isinstance(request, analytics_admin.UpdateDataStreamRequest): + request = analytics_admin.UpdateDataStreamRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent - if audience is not None: - request.audience = audience + if data_stream is not None: + request.data_stream = data_stream + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_audience] + rpc = self._transport._wrapped_methods[self._transport.update_data_stream] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("data_stream.name", request.data_stream.name),) + ), ) # Validate the universe domain. @@ -7286,38 +7366,26 @@ def create_audience( # Done; return the response. return response - def update_audience( + def list_data_streams( self, - request: Optional[Union[analytics_admin.UpdateAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.ListDataStreamsRequest, dict]] = None, *, - audience: Optional[gaa_audience.Audience] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_audience.Audience: - r"""Updates an Audience on a property. + ) -> pagers.ListDataStreamsPager: + r"""Lists DataStreams on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateAudienceRequest, dict]): - The request object. Request message for UpdateAudience + request (Union[google.analytics.admin_v1alpha.types.ListDataStreamsRequest, dict]): + The request object. Request message for ListDataStreams RPC. - audience (google.analytics.admin_v1alpha.types.Audience): - Required. The audience to update. The audience's - ``name`` field is used to identify the audience to be - updated. - - This corresponds to the ``audience`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + parent (str): + Required. Example format: + properties/1234 - This corresponds to the ``update_mask`` field + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7327,15 +7395,18 @@ def update_audience( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.Audience: - A resource message representing a GA4 - Audience. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDataStreamsPager: + Response message for ListDataStreams + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([audience, update_mask]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7344,25 +7415,21 @@ def update_audience( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateAudienceRequest): - request = analytics_admin.UpdateAudienceRequest(request) + if not isinstance(request, analytics_admin.ListDataStreamsRequest): + request = analytics_admin.ListDataStreamsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if audience is not None: - request.audience = audience - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_audience] + rpc = self._transport._wrapped_methods[self._transport.list_data_streams] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("audience.name", request.audience.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -7376,38 +7443,77 @@ def update_audience( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataStreamsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def archive_audience( + def get_data_stream( self, - request: Optional[Union[analytics_admin.ArchiveAudienceRequest, dict]] = None, + request: Optional[Union[analytics_admin.GetDataStreamRequest, dict]] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Archives an Audience on a property. + ) -> resources.DataStream: + r"""Lookup for a single DataStream. Args: - request (Union[google.analytics.admin_v1alpha.types.ArchiveAudienceRequest, dict]): - The request object. Request message for ArchiveAudience + request (Union[google.analytics.admin_v1alpha.types.GetDataStreamRequest, dict]): + The request object. Request message for GetDataStream RPC. + name (str): + Required. The name of the DataStream + to get. Example format: + properties/1234/dataStreams/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ArchiveAudienceRequest): - request = analytics_admin.ArchiveAudienceRequest(request) + if not isinstance(request, analytics_admin.GetDataStreamRequest): + request = analytics_admin.GetDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.archive_audience] + rpc = self._transport._wrapped_methods[self._transport.get_data_stream] # Certain fields should be provided within the metadata header; # add these here. @@ -7419,34 +7525,36 @@ def archive_audience( self._validate_universe_domain() # Send the request. - rpc( + response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - def get_search_ads360_link( + # Done; return the response. + return response + + def get_audience( self, - request: Optional[ - Union[analytics_admin.GetSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetAudienceRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.SearchAds360Link: - r"""Look up a single SearchAds360Link + ) -> audience.Audience: + r"""Lookup for a single Audience. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. Args: - request (Union[google.analytics.admin_v1alpha.types.GetSearchAds360LinkRequest, dict]): - The request object. Request message for - GetSearchAds360Link RPC. + request (Union[google.analytics.admin_v1alpha.types.GetAudienceRequest, dict]): + The request object. Request message for GetAudience RPC. name (str): - Required. The name of the - SearchAds360Link to get. Example format: - properties/1234/SearchAds360Link/5678 + Required. The name of the Audience to + get. Example format: + properties/1234/audiences/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -7458,9 +7566,9 @@ def get_search_ads360_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SearchAds360Link: - A link between a GA4 property and a - Search Ads 360 entity. + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. """ # Create or coerce a protobuf request object. @@ -7475,8 +7583,8 @@ def get_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetSearchAds360LinkRequest): - request = analytics_admin.GetSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.GetAudienceRequest): + request = analytics_admin.GetAudienceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -7484,7 +7592,7 @@ def get_search_ads360_link( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_search_ads360_link] + rpc = self._transport._wrapped_methods[self._transport.get_audience] # Certain fields should be provided within the metadata header; # add these here. @@ -7506,23 +7614,23 @@ def get_search_ads360_link( # Done; return the response. return response - def list_search_ads360_links( + def list_audiences( self, - request: Optional[ - Union[analytics_admin.ListSearchAds360LinksRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListAudiencesRequest, dict]] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSearchAds360LinksPager: - r"""Lists all SearchAds360Links on a property. + ) -> pagers.ListAudiencesPager: + r"""Lists Audiences on a property. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. Args: - request (Union[google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest, dict]): - The request object. Request message for - ListSearchAds360Links RPC. + request (Union[google.analytics.admin_v1alpha.types.ListAudiencesRequest, dict]): + The request object. Request message for ListAudiences + RPC. parent (str): Required. Example format: properties/1234 @@ -7537,9 +7645,9 @@ def list_search_ads360_links( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSearchAds360LinksPager: - Response message for - ListSearchAds360Links RPC. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAudiencesPager: + Response message for ListAudiences + RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -7557,8 +7665,8 @@ def list_search_ads360_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListSearchAds360LinksRequest): - request = analytics_admin.ListSearchAds360LinksRequest(request) + if not isinstance(request, analytics_admin.ListAudiencesRequest): + request = analytics_admin.ListAudiencesRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -7566,7 +7674,7 @@ def list_search_ads360_links( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_search_ads360_links] + rpc = self._transport._wrapped_methods[self._transport.list_audiences] # Certain fields should be provided within the metadata header; # add these here. @@ -7587,7 +7695,7 @@ def list_search_ads360_links( # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListSearchAds360LinksPager( + response = pagers.ListAudiencesPager( method=rpc, request=request, response=response, @@ -7599,24 +7707,22 @@ def list_search_ads360_links( # Done; return the response. return response - def create_search_ads360_link( + def create_audience( self, - request: Optional[ - Union[analytics_admin.CreateSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.CreateAudienceRequest, dict]] = None, *, parent: Optional[str] = None, - search_ads_360_link: Optional[resources.SearchAds360Link] = None, + audience: Optional[gaa_audience.Audience] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.SearchAds360Link: - r"""Creates a SearchAds360Link. + ) -> gaa_audience.Audience: + r"""Creates an Audience. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateSearchAds360LinkRequest, dict]): - The request object. Request message for - CreateSearchAds360Link RPC. + request (Union[google.analytics.admin_v1alpha.types.CreateAudienceRequest, dict]): + The request object. Request message for CreateAudience + RPC. parent (str): Required. Example format: properties/1234 @@ -7624,11 +7730,9 @@ def create_search_ads360_link( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): - Required. The SearchAds360Link to - create. - - This corresponds to the ``search_ads_360_link`` field + audience (google.analytics.admin_v1alpha.types.Audience): + Required. The audience to create. + This corresponds to the ``audience`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7638,15 +7742,15 @@ def create_search_ads360_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SearchAds360Link: - A link between a GA4 property and a - Search Ads 360 entity. + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, search_ads_360_link]) + has_flattened_params = any([parent, audience]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7655,20 +7759,18 @@ def create_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateSearchAds360LinkRequest): - request = analytics_admin.CreateSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.CreateAudienceRequest): + request = analytics_admin.CreateAudienceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if search_ads_360_link is not None: - request.search_ads_360_link = search_ads_360_link + if audience is not None: + request.audience = audience # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.create_search_ads360_link - ] + rpc = self._transport._wrapped_methods[self._transport.create_audience] # Certain fields should be provided within the metadata header; # add these here. @@ -7690,30 +7792,38 @@ def create_search_ads360_link( # Done; return the response. return response - def delete_search_ads360_link( + def update_audience( self, - request: Optional[ - Union[analytics_admin.DeleteSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.UpdateAudienceRequest, dict]] = None, *, - name: Optional[str] = None, + audience: Optional[gaa_audience.Audience] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a SearchAds360Link on a property. + ) -> gaa_audience.Audience: + r"""Updates an Audience on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteSearchAds360LinkRequest, dict]): - The request object. Request message for - DeleteSearchAds360Link RPC. - name (str): - Required. The name of the - SearchAds360Link to delete. Example - format: - properties/1234/SearchAds360Links/5678 + request (Union[google.analytics.admin_v1alpha.types.UpdateAudienceRequest, dict]): + The request object. Request message for UpdateAudience + RPC. + audience (google.analytics.admin_v1alpha.types.Audience): + Required. The audience to update. The audience's + ``name`` field is used to identify the audience to be + updated. - This corresponds to the ``name`` field + This corresponds to the ``audience`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7721,11 +7831,17 @@ def delete_search_ads360_link( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([audience, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7734,150 +7850,109 @@ def delete_search_ads360_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteSearchAds360LinkRequest): - request = analytics_admin.DeleteSearchAds360LinkRequest(request) + if not isinstance(request, analytics_admin.UpdateAudienceRequest): + request = analytics_admin.UpdateAudienceRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if audience is not None: + request.audience = audience + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.delete_search_ads360_link - ] + rpc = self._transport._wrapped_methods[self._transport.update_audience] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("audience.name", request.audience.name),) + ), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( + response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - def update_search_ads360_link( + # Done; return the response. + return response + + def archive_audience( self, - request: Optional[ - Union[analytics_admin.UpdateSearchAds360LinkRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ArchiveAudienceRequest, dict]] = None, *, - search_ads_360_link: Optional[resources.SearchAds360Link] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.SearchAds360Link: - r"""Updates a SearchAds360Link on a property. + ) -> None: + r"""Archives an Audience on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateSearchAds360LinkRequest, dict]): - The request object. Request message for - UpdateSearchAds360Link RPC. - search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): - The SearchAds360Link to update - This corresponds to the ``search_ads_360_link`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. + request (Union[google.analytics.admin_v1alpha.types.ArchiveAudienceRequest, dict]): + The request object. Request message for ArchiveAudience + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.SearchAds360Link: - A link between a GA4 property and a - Search Ads 360 entity. - """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([search_ads_360_link, update_mask]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateSearchAds360LinkRequest): - request = analytics_admin.UpdateSearchAds360LinkRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if search_ads_360_link is not None: - request.search_ads_360_link = search_ads_360_link - if update_mask is not None: - request.update_mask = update_mask + if not isinstance(request, analytics_admin.ArchiveAudienceRequest): + request = analytics_admin.ArchiveAudienceRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_search_ads360_link - ] + rpc = self._transport._wrapped_methods[self._transport.archive_audience] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("search_ads_360_link.name", request.search_ads_360_link.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - def get_attribution_settings( + def get_search_ads360_link( self, request: Optional[ - Union[analytics_admin.GetAttributionSettingsRequest, dict] + Union[analytics_admin.GetSearchAds360LinkRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AttributionSettings: - r"""Lookup for a AttributionSettings singleton. + ) -> resources.SearchAds360Link: + r"""Look up a single SearchAds360Link Args: - request (Union[google.analytics.admin_v1alpha.types.GetAttributionSettingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.GetSearchAds360LinkRequest, dict]): The request object. Request message for - GetAttributionSettings RPC. + GetSearchAds360Link RPC. name (str): - Required. The name of the attribution - settings to retrieve. Format: - properties/{property}/attributionSettings + Required. The name of the + SearchAds360Link to get. Example format: + properties/1234/SearchAds360Link/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -7889,10 +7964,9 @@ def get_attribution_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AttributionSettings: - The attribution settings used for a - given property. This is a singleton - resource. + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. """ # Create or coerce a protobuf request object. @@ -7907,8 +7981,8 @@ def get_attribution_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAttributionSettingsRequest): - request = analytics_admin.GetAttributionSettingsRequest(request) + if not isinstance(request, analytics_admin.GetSearchAds360LinkRequest): + request = analytics_admin.GetSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -7916,7 +7990,7 @@ def get_attribution_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_attribution_settings] + rpc = self._transport._wrapped_methods[self._transport.get_search_ads360_link] # Certain fields should be provided within the metadata header; # add these here. @@ -7938,40 +8012,28 @@ def get_attribution_settings( # Done; return the response. return response - def update_attribution_settings( + def list_search_ads360_links( self, request: Optional[ - Union[analytics_admin.UpdateAttributionSettingsRequest, dict] + Union[analytics_admin.ListSearchAds360LinksRequest, dict] ] = None, *, - attribution_settings: Optional[resources.AttributionSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AttributionSettings: - r"""Updates attribution settings on a property. + ) -> pagers.ListSearchAds360LinksPager: + r"""Lists all SearchAds360Links on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateAttributionSettingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest, dict]): The request object. Request message for - UpdateAttributionSettings RPC - attribution_settings (google.analytics.admin_v1alpha.types.AttributionSettings): - Required. The attribution settings to update. The - ``name`` field is used to identify the settings to be - updated. - - This corresponds to the ``attribution_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + ListSearchAds360Links RPC. + parent (str): + Required. Example format: + properties/1234 - This corresponds to the ``update_mask`` field + This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -7981,16 +8043,18 @@ def update_attribution_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AttributionSettings: - The attribution settings used for a - given property. This is a singleton - resource. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSearchAds360LinksPager: + Response message for + ListSearchAds360Links RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([attribution_settings, update_mask]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -7999,27 +8063,21 @@ def update_attribution_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateAttributionSettingsRequest): - request = analytics_admin.UpdateAttributionSettingsRequest(request) + if not isinstance(request, analytics_admin.ListSearchAds360LinksRequest): + request = analytics_admin.ListSearchAds360LinksRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if attribution_settings is not None: - request.attribution_settings = attribution_settings - if update_mask is not None: - request.update_mask = update_mask + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_attribution_settings - ] + rpc = self._transport._wrapped_methods[self._transport.list_search_ads360_links] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("attribution_settings.name", request.attribution_settings.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -8033,72 +8091,12 @@ def update_attribution_settings( metadata=metadata, ) - # Done; return the response. - return response - - def run_access_report( - self, - request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.RunAccessReportResponse: - r"""Returns a customized report of data access records. The report - provides records of each time a user reads Google Analytics - reporting data. Access records are retained for up to 2 years. - - Data Access Reports can be requested for a property. Reports may - be requested for any property, but dimensions that aren't - related to quota can only be requested on Google Analytics 360 - properties. This method is only available to Administrators. - - These data access records include GA4 UI Reporting, GA4 UI - Explorations, GA4 Data API, and other products like Firebase & - Admob that can retrieve data from Google Analytics through a - linkage. These records don't include property configuration - changes like adding a stream or changing a property's time zone. - For configuration change history, see - `searchChangeHistoryEvents `__. - - Args: - request (Union[google.analytics.admin_v1alpha.types.RunAccessReportRequest, dict]): - The request object. The request for a Data Access Record - Report. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.RunAccessReportResponse: - The customized Data Access Record - Report response. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.RunAccessReportRequest): - request = analytics_admin.RunAccessReportRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_access_report] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("entity", request.entity),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSearchAds360LinksPager( + method=rpc, + request=request, + response=response, retry=retry, timeout=timeout, metadata=metadata, @@ -8107,38 +8105,36 @@ def run_access_report( # Done; return the response. return response - def create_access_binding( + def create_search_ads360_link( self, request: Optional[ - Union[analytics_admin.CreateAccessBindingRequest, dict] + Union[analytics_admin.CreateSearchAds360LinkRequest, dict] ] = None, *, parent: Optional[str] = None, - access_binding: Optional[resources.AccessBinding] = None, + search_ads_360_link: Optional[resources.SearchAds360Link] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AccessBinding: - r"""Creates an access binding on an account or property. + ) -> resources.SearchAds360Link: + r"""Creates a SearchAds360Link. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateSearchAds360LinkRequest, dict]): The request object. Request message for - CreateAccessBinding RPC. + CreateSearchAds360Link RPC. parent (str): - Required. Formats: - - - accounts/{account} - - properties/{property} + Required. Example format: + properties/1234 This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - access_binding (google.analytics.admin_v1alpha.types.AccessBinding): - Required. The access binding to + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + Required. The SearchAds360Link to create. - This corresponds to the ``access_binding`` field + This corresponds to the ``search_ads_360_link`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -8148,15 +8144,15 @@ def create_access_binding( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AccessBinding: - A binding of a user to a set of - roles. + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, access_binding]) + has_flattened_params = any([parent, search_ads_360_link]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -8165,18 +8161,20 @@ def create_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateAccessBindingRequest): - request = analytics_admin.CreateAccessBindingRequest(request) + if not isinstance(request, analytics_admin.CreateSearchAds360LinkRequest): + request = analytics_admin.CreateSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if access_binding is not None: - request.access_binding = access_binding + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_access_binding] + rpc = self._transport._wrapped_methods[ + self._transport.create_search_ads360_link + ] # Certain fields should be provided within the metadata header; # add these here. @@ -8198,29 +8196,28 @@ def create_access_binding( # Done; return the response. return response - def get_access_binding( + def delete_search_ads360_link( self, - request: Optional[Union[analytics_admin.GetAccessBindingRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.DeleteSearchAds360LinkRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AccessBinding: - r"""Gets information about an access binding. + ) -> None: + r"""Deletes a SearchAds360Link on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.GetAccessBindingRequest, dict]): - The request object. Request message for GetAccessBinding - RPC. + request (Union[google.analytics.admin_v1alpha.types.DeleteSearchAds360LinkRequest, dict]): + The request object. Request message for + DeleteSearchAds360Link RPC. name (str): - Required. The name of the access - binding to retrieve. Formats: - - - - accounts/{account}/accessBindings/{accessBinding} - - - properties/{property}/accessBindings/{accessBinding} + Required. The name of the + SearchAds360Link to delete. Example + format: + properties/1234/SearchAds360Links/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -8230,12 +8227,6 @@ def get_access_binding( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.AccessBinding: - A binding of a user to a set of - roles. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -8249,8 +8240,8 @@ def get_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAccessBindingRequest): - request = analytics_admin.GetAccessBindingRequest(request) + if not isinstance(request, analytics_admin.DeleteSearchAds360LinkRequest): + request = analytics_admin.DeleteSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -8258,7 +8249,9 @@ def get_access_binding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_access_binding] + rpc = self._transport._wrapped_methods[ + self._transport.delete_search_ads360_link + ] # Certain fields should be provided within the metadata header; # add these here. @@ -8270,38 +8263,43 @@ def get_access_binding( self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - def update_access_binding( + def update_search_ads360_link( self, request: Optional[ - Union[analytics_admin.UpdateAccessBindingRequest, dict] + Union[analytics_admin.UpdateSearchAds360LinkRequest, dict] ] = None, *, - access_binding: Optional[resources.AccessBinding] = None, + search_ads_360_link: Optional[resources.SearchAds360Link] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AccessBinding: - r"""Updates an access binding on an account or property. + ) -> resources.SearchAds360Link: + r"""Updates a SearchAds360Link on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateSearchAds360LinkRequest, dict]): The request object. Request message for - UpdateAccessBinding RPC. - access_binding (google.analytics.admin_v1alpha.types.AccessBinding): - Required. The access binding to - update. + UpdateSearchAds360Link RPC. + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + The SearchAds360Link to update + This corresponds to the ``search_ads_360_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. - This corresponds to the ``access_binding`` field + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -8311,15 +8309,15 @@ def update_access_binding( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AccessBinding: - A binding of a user to a set of - roles. + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([access_binding]) + has_flattened_params = any([search_ads_360_link, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -8328,22 +8326,26 @@ def update_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateAccessBindingRequest): - request = analytics_admin.UpdateAccessBindingRequest(request) + if not isinstance(request, analytics_admin.UpdateSearchAds360LinkRequest): + request = analytics_admin.UpdateSearchAds360LinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if access_binding is not None: - request.access_binding = access_binding + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_access_binding] + rpc = self._transport._wrapped_methods[ + self._transport.update_search_ads360_link + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("access_binding.name", request.access_binding.name),) + (("search_ads_360_link.name", request.search_ads_360_link.name),) ), ) @@ -8361,30 +8363,27 @@ def update_access_binding( # Done; return the response. return response - def delete_access_binding( + def get_attribution_settings( self, request: Optional[ - Union[analytics_admin.DeleteAccessBindingRequest, dict] + Union[analytics_admin.GetAttributionSettingsRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an access binding on an account or property. + ) -> resources.AttributionSettings: + r"""Lookup for a AttributionSettings singleton. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.GetAttributionSettingsRequest, dict]): The request object. Request message for - DeleteAccessBinding RPC. + GetAttributionSettings RPC. name (str): - Required. Formats: - - - - accounts/{account}/accessBindings/{accessBinding} - - - properties/{property}/accessBindings/{accessBinding} + Required. The name of the attribution + settings to retrieve. Format: + properties/{property}/attributionSettings This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -8394,6 +8393,13 @@ def delete_access_binding( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -8407,8 +8413,8 @@ def delete_access_binding( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteAccessBindingRequest): - request = analytics_admin.DeleteAccessBindingRequest(request) + if not isinstance(request, analytics_admin.GetAttributionSettingsRequest): + request = analytics_admin.GetAttributionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -8416,7 +8422,7 @@ def delete_access_binding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_access_binding] + rpc = self._transport._wrapped_methods[self._transport.get_attribution_settings] # Certain fields should be provided within the metadata header; # add these here. @@ -8428,37 +8434,50 @@ def delete_access_binding( self._validate_universe_domain() # Send the request. - rpc( + response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - def list_access_bindings( + # Done; return the response. + return response + + def update_attribution_settings( self, request: Optional[ - Union[analytics_admin.ListAccessBindingsRequest, dict] + Union[analytics_admin.UpdateAttributionSettingsRequest, dict] ] = None, *, - parent: Optional[str] = None, + attribution_settings: Optional[resources.AttributionSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAccessBindingsPager: - r"""Lists all access bindings on an account or property. + ) -> resources.AttributionSettings: + r"""Updates attribution settings on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListAccessBindingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateAttributionSettingsRequest, dict]): The request object. Request message for - ListAccessBindings RPC. - parent (str): - Required. Formats: + UpdateAttributionSettings RPC + attribution_settings (google.analytics.admin_v1alpha.types.AttributionSettings): + Required. The attribution settings to update. The + ``name`` field is used to identify the settings to be + updated. - - accounts/{account} - - properties/{property} + This corresponds to the ``attribution_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. - This corresponds to the ``parent`` field + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -8468,18 +8487,16 @@ def list_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccessBindingsPager: - Response message for - ListAccessBindings RPC. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([attribution_settings, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -8488,21 +8505,27 @@ def list_access_bindings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListAccessBindingsRequest): - request = analytics_admin.ListAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.UpdateAttributionSettingsRequest): + request = analytics_admin.UpdateAttributionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if attribution_settings is not None: + request.attribution_settings = attribution_settings + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_access_bindings] + rpc = self._transport._wrapped_methods[ + self._transport.update_attribution_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("attribution_settings.name", request.attribution_settings.name),) + ), ) # Validate the universe domain. @@ -8516,41 +8539,38 @@ def list_access_bindings( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAccessBindingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - def batch_create_access_bindings( + def run_access_report( self, - request: Optional[ - Union[analytics_admin.BatchCreateAccessBindingsRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.BatchCreateAccessBindingsResponse: - r"""Creates information about multiple access bindings to - an account or property. + ) -> analytics_admin.RunAccessReportResponse: + r"""Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. - This method is transactional. If any AccessBinding - cannot be created, none of the AccessBindings will be - created. + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. Args: - request (Union[google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsRequest, dict]): - The request object. Request message for - BatchCreateAccessBindings RPC. + request (Union[google.analytics.admin_v1alpha.types.RunAccessReportRequest, dict]): + The request object. The request for a Data Access Record + Report. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8558,27 +8578,25 @@ def batch_create_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsResponse: - Response message for - BatchCreateAccessBindings RPC. + google.analytics.admin_v1alpha.types.RunAccessReportResponse: + The customized Data Access Record + Report response. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchCreateAccessBindingsRequest): - request = analytics_admin.BatchCreateAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.RunAccessReportRequest): + request = analytics_admin.RunAccessReportRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.batch_create_access_bindings - ] + rpc = self._transport._wrapped_methods[self._transport.run_access_report] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("entity", request.entity),)), ) # Validate the universe domain. @@ -8595,23 +8613,40 @@ def batch_create_access_bindings( # Done; return the response. return response - def batch_get_access_bindings( + def create_access_binding( self, request: Optional[ - Union[analytics_admin.BatchGetAccessBindingsRequest, dict] + Union[analytics_admin.CreateAccessBindingRequest, dict] ] = None, *, + parent: Optional[str] = None, + access_binding: Optional[resources.AccessBinding] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.BatchGetAccessBindingsResponse: - r"""Gets information about multiple access bindings to an - account or property. + ) -> resources.AccessBinding: + r"""Creates an access binding on an account or property. Args: - request (Union[google.analytics.admin_v1alpha.types.BatchGetAccessBindingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest, dict]): The request object. Request message for - BatchGetAccessBindings RPC. + CreateAccessBinding RPC. + parent (str): + Required. Formats: + + - accounts/{account} + - properties/{property} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + access_binding (google.analytics.admin_v1alpha.types.AccessBinding): + Required. The access binding to + create. + + This corresponds to the ``access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8619,22 +8654,35 @@ def batch_get_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BatchGetAccessBindingsResponse: - Response message for - BatchGetAccessBindings RPC. + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, access_binding]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchGetAccessBindingsRequest): - request = analytics_admin.BatchGetAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.CreateAccessBindingRequest): + request = analytics_admin.CreateAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if access_binding is not None: + request.access_binding = access_binding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.batch_get_access_bindings - ] + rpc = self._transport._wrapped_methods[self._transport.create_access_binding] # Certain fields should be provided within the metadata header; # add these here. @@ -8656,23 +8704,33 @@ def batch_get_access_bindings( # Done; return the response. return response - def batch_update_access_bindings( + def get_access_binding( self, - request: Optional[ - Union[analytics_admin.BatchUpdateAccessBindingsRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetAccessBindingRequest, dict]] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.BatchUpdateAccessBindingsResponse: - r"""Updates information about multiple access bindings to - an account or property. + ) -> resources.AccessBinding: + r"""Gets information about an access binding. Args: - request (Union[google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsRequest, dict]): - The request object. Request message for - BatchUpdateAccessBindings RPC. + request (Union[google.analytics.admin_v1alpha.types.GetAccessBindingRequest, dict]): + The request object. Request message for GetAccessBinding + RPC. + name (str): + Required. The name of the access + binding to retrieve. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8680,27 +8738,38 @@ def batch_update_access_bindings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsResponse: - Response message for - BatchUpdateAccessBindings RPC. + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchUpdateAccessBindingsRequest): - request = analytics_admin.BatchUpdateAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.GetAccessBindingRequest): + request = analytics_admin.GetAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.batch_update_access_bindings - ] + rpc = self._transport._wrapped_methods[self._transport.get_access_binding] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -8717,79 +8786,111 @@ def batch_update_access_bindings( # Done; return the response. return response - def batch_delete_access_bindings( + def update_access_binding( self, request: Optional[ - Union[analytics_admin.BatchDeleteAccessBindingsRequest, dict] + Union[analytics_admin.UpdateAccessBindingRequest, dict] ] = None, *, + access_binding: Optional[resources.AccessBinding] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes information about multiple users' links to an - account or property. + ) -> resources.AccessBinding: + r"""Updates an access binding on an account or property. Args: - request (Union[google.analytics.admin_v1alpha.types.BatchDeleteAccessBindingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest, dict]): The request object. Request message for - BatchDeleteAccessBindings RPC. + UpdateAccessBinding RPC. + access_binding (google.analytics.admin_v1alpha.types.AccessBinding): + Required. The access binding to + update. + + This corresponds to the ``access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([access_binding]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.BatchDeleteAccessBindingsRequest): - request = analytics_admin.BatchDeleteAccessBindingsRequest(request) + if not isinstance(request, analytics_admin.UpdateAccessBindingRequest): + request = analytics_admin.UpdateAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if access_binding is not None: + request.access_binding = access_binding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.batch_delete_access_bindings - ] + rpc = self._transport._wrapped_methods[self._transport.update_access_binding] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("access_binding.name", request.access_binding.name),) + ), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( + response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - def get_expanded_data_set( + # Done; return the response. + return response + + def delete_access_binding( self, request: Optional[ - Union[analytics_admin.GetExpandedDataSetRequest, dict] + Union[analytics_admin.DeleteAccessBindingRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> expanded_data_set.ExpandedDataSet: - r"""Lookup for a single ExpandedDataSet. + ) -> None: + r"""Deletes an access binding on an account or property. Args: - request (Union[google.analytics.admin_v1alpha.types.GetExpandedDataSetRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest, dict]): The request object. Request message for - GetExpandedDataSet RPC. + DeleteAccessBinding RPC. name (str): - Required. The name of the - ExpandedDataSet to get. Example format: - properties/1234/expandedDataSets/5678 + Required. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -8799,12 +8900,6 @@ def get_expanded_data_set( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.ExpandedDataSet: - A resource message representing a GA4 - ExpandedDataSet. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -8818,8 +8913,8 @@ def get_expanded_data_set( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetExpandedDataSetRequest): - request = analytics_admin.GetExpandedDataSetRequest(request) + if not isinstance(request, analytics_admin.DeleteAccessBindingRequest): + request = analytics_admin.DeleteAccessBindingRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -8827,7 +8922,7 @@ def get_expanded_data_set( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_expanded_data_set] + rpc = self._transport._wrapped_methods[self._transport.delete_access_binding] # Certain fields should be provided within the metadata header; # add these here. @@ -8839,36 +8934,35 @@ def get_expanded_data_set( self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - def list_expanded_data_sets( + def list_access_bindings( self, request: Optional[ - Union[analytics_admin.ListExpandedDataSetsRequest, dict] + Union[analytics_admin.ListAccessBindingsRequest, dict] ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListExpandedDataSetsPager: - r"""Lists ExpandedDataSets on a property. + ) -> pagers.ListAccessBindingsPager: + r"""Lists all access bindings on an account or property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ListAccessBindingsRequest, dict]): The request object. Request message for - ListExpandedDataSets RPC. + ListAccessBindings RPC. parent (str): - Required. Example format: - properties/1234 + Required. Formats: + + - accounts/{account} + - properties/{property} This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this @@ -8880,9 +8974,9 @@ def list_expanded_data_sets( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListExpandedDataSetsPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccessBindingsPager: Response message for - ListExpandedDataSets RPC. + ListAccessBindings RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -8900,8 +8994,8 @@ def list_expanded_data_sets( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListExpandedDataSetsRequest): - request = analytics_admin.ListExpandedDataSetsRequest(request) + if not isinstance(request, analytics_admin.ListAccessBindingsRequest): + request = analytics_admin.ListAccessBindingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -8909,7 +9003,7 @@ def list_expanded_data_sets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_expanded_data_sets] + rpc = self._transport._wrapped_methods[self._transport.list_access_bindings] # Certain fields should be provided within the metadata header; # add these here. @@ -8930,7 +9024,7 @@ def list_expanded_data_sets( # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListExpandedDataSetsPager( + response = pagers.ListAccessBindingsPager( method=rpc, request=request, response=response, @@ -8942,38 +9036,27 @@ def list_expanded_data_sets( # Done; return the response. return response - def create_expanded_data_set( + def batch_create_access_bindings( self, request: Optional[ - Union[analytics_admin.CreateExpandedDataSetRequest, dict] + Union[analytics_admin.BatchCreateAccessBindingsRequest, dict] ] = None, *, - parent: Optional[str] = None, - expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_expanded_data_set.ExpandedDataSet: - r"""Creates a ExpandedDataSet. + ) -> analytics_admin.BatchCreateAccessBindingsResponse: + r"""Creates information about multiple access bindings to + an account or property. + + This method is transactional. If any AccessBinding + cannot be created, none of the AccessBindings will be + created. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateExpandedDataSetRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsRequest, dict]): The request object. Request message for - CreateExpandedDataSet RPC. - parent (str): - Required. Example format: - properties/1234 - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): - Required. The ExpandedDataSet to - create. - - This corresponds to the ``expanded_data_set`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + BatchCreateAccessBindings RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8981,35 +9064,22 @@ def create_expanded_data_set( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ExpandedDataSet: - A resource message representing a GA4 - ExpandedDataSet. + google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsResponse: + Response message for + BatchCreateAccessBindings RPC. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, expanded_data_set]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateExpandedDataSetRequest): - request = analytics_admin.CreateExpandedDataSetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if expanded_data_set is not None: - request.expanded_data_set = expanded_data_set + if not isinstance(request, analytics_admin.BatchCreateAccessBindingsRequest): + request = analytics_admin.BatchCreateAccessBindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_expanded_data_set] + rpc = self._transport._wrapped_methods[ + self._transport.batch_create_access_bindings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -9031,42 +9101,84 @@ def create_expanded_data_set( # Done; return the response. return response - def update_expanded_data_set( + def batch_get_access_bindings( self, request: Optional[ - Union[analytics_admin.UpdateExpandedDataSetRequest, dict] + Union[analytics_admin.BatchGetAccessBindingsRequest, dict] ] = None, *, - expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_expanded_data_set.ExpandedDataSet: - r"""Updates a ExpandedDataSet on a property. + ) -> analytics_admin.BatchGetAccessBindingsResponse: + r"""Gets information about multiple access bindings to an + account or property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateExpandedDataSetRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.BatchGetAccessBindingsRequest, dict]): The request object. Request message for - UpdateExpandedDataSet RPC. - expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): - Required. The ExpandedDataSet to update. The resource's - ``name`` field is used to identify the ExpandedDataSet - to be updated. + BatchGetAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - This corresponds to the ``expanded_data_set`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. + Returns: + google.analytics.admin_v1alpha.types.BatchGetAccessBindingsResponse: + Response message for + BatchGetAccessBindings RPC. - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchGetAccessBindingsRequest): + request = analytics_admin.BatchGetAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_get_access_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_update_access_bindings( + self, + request: Optional[ + Union[analytics_admin.BatchUpdateAccessBindingsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchUpdateAccessBindingsResponse: + r"""Updates information about multiple access bindings to + an account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsRequest, dict]): + The request object. Request message for + BatchUpdateAccessBindings RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9074,42 +9186,27 @@ def update_expanded_data_set( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ExpandedDataSet: - A resource message representing a GA4 - ExpandedDataSet. + google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsResponse: + Response message for + BatchUpdateAccessBindings RPC. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([expanded_data_set, update_mask]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateExpandedDataSetRequest): - request = analytics_admin.UpdateExpandedDataSetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if expanded_data_set is not None: - request.expanded_data_set = expanded_data_set - if update_mask is not None: - request.update_mask = update_mask + if not isinstance(request, analytics_admin.BatchUpdateAccessBindingsRequest): + request = analytics_admin.BatchUpdateAccessBindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_expanded_data_set] + rpc = self._transport._wrapped_methods[ + self._transport.batch_update_access_bindings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("expanded_data_set.name", request.expanded_data_set.name),) - ), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -9126,30 +9223,23 @@ def update_expanded_data_set( # Done; return the response. return response - def delete_expanded_data_set( + def batch_delete_access_bindings( self, request: Optional[ - Union[analytics_admin.DeleteExpandedDataSetRequest, dict] + Union[analytics_admin.BatchDeleteAccessBindingsRequest, dict] ] = None, *, - name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a ExpandedDataSet on a property. + r"""Deletes information about multiple users' links to an + account or property. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteExpandedDataSetRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.BatchDeleteAccessBindingsRequest, dict]): The request object. Request message for - DeleteExpandedDataSet RPC. - name (str): - Required. Example format: - properties/1234/expandedDataSets/5678 - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + BatchDeleteAccessBindings RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9157,32 +9247,21 @@ def delete_expanded_data_set( sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteExpandedDataSetRequest): - request = analytics_admin.DeleteExpandedDataSetRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name + if not isinstance(request, analytics_admin.BatchDeleteAccessBindingsRequest): + request = analytics_admin.BatchDeleteAccessBindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_expanded_data_set] + rpc = self._transport._wrapped_methods[ + self._transport.batch_delete_access_bindings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -9196,25 +9275,27 @@ def delete_expanded_data_set( metadata=metadata, ) - def get_channel_group( + def get_expanded_data_set( self, - request: Optional[Union[analytics_admin.GetChannelGroupRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.GetExpandedDataSetRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> channel_group.ChannelGroup: - r"""Lookup for a single ChannelGroup. + ) -> expanded_data_set.ExpandedDataSet: + r"""Lookup for a single ExpandedDataSet. Args: - request (Union[google.analytics.admin_v1alpha.types.GetChannelGroupRequest, dict]): - The request object. Request message for GetChannelGroup - RPC. + request (Union[google.analytics.admin_v1alpha.types.GetExpandedDataSetRequest, dict]): + The request object. Request message for + GetExpandedDataSet RPC. name (str): - Required. The ChannelGroup to get. - Example format: - properties/1234/channelGroups/5678 + Required. The name of the + ExpandedDataSet to get. Example format: + properties/1234/expandedDataSets/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -9226,9 +9307,9 @@ def get_channel_group( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ChannelGroup: - A resource message representing a - Channel Group. + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. """ # Create or coerce a protobuf request object. @@ -9243,8 +9324,8 @@ def get_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetChannelGroupRequest): - request = analytics_admin.GetChannelGroupRequest(request) + if not isinstance(request, analytics_admin.GetExpandedDataSetRequest): + request = analytics_admin.GetExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -9252,7 +9333,7 @@ def get_channel_group( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_channel_group] + rpc = self._transport._wrapped_methods[self._transport.get_expanded_data_set] # Certain fields should be provided within the metadata header; # add these here. @@ -9274,24 +9355,25 @@ def get_channel_group( # Done; return the response. return response - def list_channel_groups( + def list_expanded_data_sets( self, - request: Optional[Union[analytics_admin.ListChannelGroupsRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ListExpandedDataSetsRequest, dict] + ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListChannelGroupsPager: - r"""Lists ChannelGroups on a property. + ) -> pagers.ListExpandedDataSetsPager: + r"""Lists ExpandedDataSets on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.ListChannelGroupsRequest, dict]): - The request object. Request message for ListChannelGroups - RPC. + request (Union[google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest, dict]): + The request object. Request message for + ListExpandedDataSets RPC. parent (str): - Required. The property for which to - list ChannelGroups. Example format: + Required. Example format: properties/1234 This corresponds to the ``parent`` field @@ -9304,9 +9386,9 @@ def list_channel_groups( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListChannelGroupsPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListExpandedDataSetsPager: Response message for - ListChannelGroups RPC. + ListExpandedDataSets RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -9324,8 +9406,8 @@ def list_channel_groups( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListChannelGroupsRequest): - request = analytics_admin.ListChannelGroupsRequest(request) + if not isinstance(request, analytics_admin.ListExpandedDataSetsRequest): + request = analytics_admin.ListExpandedDataSetsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -9333,7 +9415,7 @@ def list_channel_groups( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_channel_groups] + rpc = self._transport._wrapped_methods[self._transport.list_expanded_data_sets] # Certain fields should be provided within the metadata header; # add these here. @@ -9354,7 +9436,7 @@ def list_channel_groups( # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListChannelGroupsPager( + response = pagers.ListExpandedDataSetsPager( method=rpc, request=request, response=response, @@ -9366,35 +9448,36 @@ def list_channel_groups( # Done; return the response. return response - def create_channel_group( + def create_expanded_data_set( self, request: Optional[ - Union[analytics_admin.CreateChannelGroupRequest, dict] + Union[analytics_admin.CreateExpandedDataSetRequest, dict] ] = None, *, parent: Optional[str] = None, - channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_channel_group.ChannelGroup: - r"""Creates a ChannelGroup. + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Creates a ExpandedDataSet. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateChannelGroupRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateExpandedDataSetRequest, dict]): The request object. Request message for - CreateChannelGroup RPC. + CreateExpandedDataSet RPC. parent (str): - Required. The property for which to - create a ChannelGroup. Example format: + Required. Example format: properties/1234 This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): - Required. The ChannelGroup to create. - This corresponds to the ``channel_group`` field + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + Required. The ExpandedDataSet to + create. + + This corresponds to the ``expanded_data_set`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -9404,15 +9487,15 @@ def create_channel_group( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ChannelGroup: - A resource message representing a - Channel Group. + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, channel_group]) + has_flattened_params = any([parent, expanded_data_set]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9421,18 +9504,18 @@ def create_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateChannelGroupRequest): - request = analytics_admin.CreateChannelGroupRequest(request) + if not isinstance(request, analytics_admin.CreateExpandedDataSetRequest): + request = analytics_admin.CreateExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if channel_group is not None: - request.channel_group = channel_group + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_channel_group] + rpc = self._transport._wrapped_methods[self._transport.create_expanded_data_set] # Certain fields should be provided within the metadata header; # add these here. @@ -9454,30 +9537,30 @@ def create_channel_group( # Done; return the response. return response - def update_channel_group( + def update_expanded_data_set( self, request: Optional[ - Union[analytics_admin.UpdateChannelGroupRequest, dict] + Union[analytics_admin.UpdateExpandedDataSetRequest, dict] ] = None, *, - channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> gaa_channel_group.ChannelGroup: - r"""Updates a ChannelGroup. + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Updates a ExpandedDataSet on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateChannelGroupRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateExpandedDataSetRequest, dict]): The request object. Request message for - UpdateChannelGroup RPC. - channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): - Required. The ChannelGroup to update. The resource's - ``name`` field is used to identify the ChannelGroup to - be updated. + UpdateExpandedDataSet RPC. + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + Required. The ExpandedDataSet to update. The resource's + ``name`` field is used to identify the ExpandedDataSet + to be updated. - This corresponds to the ``channel_group`` field + This corresponds to the ``expanded_data_set`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): @@ -9497,15 +9580,15 @@ def update_channel_group( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ChannelGroup: - A resource message representing a - Channel Group. + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([channel_group, update_mask]) + has_flattened_params = any([expanded_data_set, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9514,24 +9597,24 @@ def update_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateChannelGroupRequest): - request = analytics_admin.UpdateChannelGroupRequest(request) + if not isinstance(request, analytics_admin.UpdateExpandedDataSetRequest): + request = analytics_admin.UpdateExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if channel_group is not None: - request.channel_group = channel_group + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_channel_group] + rpc = self._transport._wrapped_methods[self._transport.update_expanded_data_set] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("channel_group.name", request.channel_group.name),) + (("expanded_data_set.name", request.expanded_data_set.name),) ), ) @@ -9549,10 +9632,10 @@ def update_channel_group( # Done; return the response. return response - def delete_channel_group( + def delete_expanded_data_set( self, request: Optional[ - Union[analytics_admin.DeleteChannelGroupRequest, dict] + Union[analytics_admin.DeleteExpandedDataSetRequest, dict] ] = None, *, name: Optional[str] = None, @@ -9560,16 +9643,15 @@ def delete_channel_group( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a ChannelGroup on a property. + r"""Deletes a ExpandedDataSet on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteChannelGroupRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.DeleteExpandedDataSetRequest, dict]): The request object. Request message for - DeleteChannelGroup RPC. + DeleteExpandedDataSet RPC. name (str): - Required. The ChannelGroup to delete. - Example format: - properties/1234/channelGroups/5678 + Required. Example format: + properties/1234/expandedDataSets/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -9592,8 +9674,8 @@ def delete_channel_group( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteChannelGroupRequest): - request = analytics_admin.DeleteChannelGroupRequest(request) + if not isinstance(request, analytics_admin.DeleteExpandedDataSetRequest): + request = analytics_admin.DeleteExpandedDataSetRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -9601,7 +9683,7 @@ def delete_channel_group( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_channel_group] + rpc = self._transport._wrapped_methods[self._transport.delete_expanded_data_set] # Certain fields should be provided within the metadata header; # add these here. @@ -9620,25 +9702,29 @@ def delete_channel_group( metadata=metadata, ) - def set_automated_ga4_configuration_opt_out( + def get_channel_group( self, - request: Optional[ - Union[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetChannelGroupRequest, dict]] = None, *, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: - r"""Sets the opt out status for the automated GA4 setup - process for a UA property. - Note: this has no effect on GA4 property. + ) -> channel_group.ChannelGroup: + r"""Lookup for a single ChannelGroup. Args: - request (Union[google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutRequest, dict]): - The request object. Request for setting the opt out - status for the automated GA4 setup - process. + request (Union[google.analytics.admin_v1alpha.types.GetChannelGroupRequest, dict]): + The request object. Request message for GetChannelGroup + RPC. + name (str): + Required. The ChannelGroup to get. + Example format: + properties/1234/channelGroups/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9646,25 +9732,39 @@ def set_automated_ga4_configuration_opt_out( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutResponse: - Response message for setting the opt - out status for the automated GA4 setup - process. + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest - ): - request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest(request) + if not isinstance(request, analytics_admin.GetChannelGroupRequest): + request = analytics_admin.GetChannelGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.set_automated_ga4_configuration_opt_out - ] + rpc = self._transport._wrapped_methods[self._transport.get_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) # Validate the universe domain. self._validate_universe_domain() @@ -9680,25 +9780,29 @@ def set_automated_ga4_configuration_opt_out( # Done; return the response. return response - def fetch_automated_ga4_configuration_opt_out( + def list_channel_groups( self, - request: Optional[ - Union[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.ListChannelGroupsRequest, dict]] = None, *, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: - r"""Fetches the opt out status for the automated GA4 - setup process for a UA property. - Note: this has no effect on GA4 property. + ) -> pagers.ListChannelGroupsPager: + r"""Lists ChannelGroups on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutRequest, dict]): - The request object. Request for fetching the opt out - status for the automated GA4 setup - process. + request (Union[google.analytics.admin_v1alpha.types.ListChannelGroupsRequest, dict]): + The request object. Request message for ListChannelGroups + RPC. + parent (str): + Required. The property for which to + list ChannelGroups. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9706,27 +9810,42 @@ def fetch_automated_ga4_configuration_opt_out( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutResponse: - Response message for fetching the opt - out status for the automated GA4 setup - process. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListChannelGroupsPager: + Response message for + ListChannelGroups RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest - ): - request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( - request + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." ) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListChannelGroupsRequest): + request = analytics_admin.ListChannelGroupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.fetch_automated_ga4_configuration_opt_out - ] + rpc = self._transport._wrapped_methods[self._transport.list_channel_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) # Validate the universe domain. self._validate_universe_domain() @@ -9739,31 +9858,49 @@ def fetch_automated_ga4_configuration_opt_out( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListChannelGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def get_big_query_link( + def create_channel_group( self, - request: Optional[Union[analytics_admin.GetBigQueryLinkRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.CreateChannelGroupRequest, dict] + ] = None, *, - name: Optional[str] = None, + parent: Optional[str] = None, + channel_group: Optional[gaa_channel_group.ChannelGroup] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.BigQueryLink: - r"""Lookup for a single BigQuery Link. + ) -> gaa_channel_group.ChannelGroup: + r"""Creates a ChannelGroup. Args: - request (Union[google.analytics.admin_v1alpha.types.GetBigQueryLinkRequest, dict]): - The request object. Request message for GetBigQueryLink - RPC. - name (str): - Required. The name of the BigQuery link to lookup. - Format: - properties/{property_id}/bigQueryLinks/{bigquery_link_id} - Example: properties/123/bigQueryLinks/456 + request (Union[google.analytics.admin_v1alpha.types.CreateChannelGroupRequest, dict]): + The request object. Request message for + CreateChannelGroup RPC. + parent (str): + Required. The property for which to + create a ChannelGroup. Example format: + properties/1234 - This corresponds to the ``name`` field + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + Required. The ChannelGroup to create. + This corresponds to the ``channel_group`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -9773,15 +9910,15 @@ def get_big_query_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.BigQueryLink: - A link between a GA4 Property and - BigQuery project. + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([parent, channel_group]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9790,21 +9927,23 @@ def get_big_query_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetBigQueryLinkRequest): - request = analytics_admin.GetBigQueryLinkRequest(request) + if not isinstance(request, analytics_admin.CreateChannelGroupRequest): + request = analytics_admin.CreateChannelGroupRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if parent is not None: + request.parent = parent + if channel_group is not None: + request.channel_group = channel_group # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_big_query_link] + rpc = self._transport._wrapped_methods[self._transport.create_channel_group] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Validate the universe domain. @@ -9821,27 +9960,40 @@ def get_big_query_link( # Done; return the response. return response - def list_big_query_links( + def update_channel_group( self, - request: Optional[Union[analytics_admin.ListBigQueryLinksRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.UpdateChannelGroupRequest, dict] + ] = None, *, - parent: Optional[str] = None, + channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListBigQueryLinksPager: - r"""Lists BigQuery Links on a property. + ) -> gaa_channel_group.ChannelGroup: + r"""Updates a ChannelGroup. Args: - request (Union[google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest, dict]): - The request object. Request message for ListBigQueryLinks - RPC. - parent (str): - Required. The name of the property to list BigQuery - links under. Format: properties/{property_id} Example: - properties/1234 + request (Union[google.analytics.admin_v1alpha.types.UpdateChannelGroupRequest, dict]): + The request object. Request message for + UpdateChannelGroup RPC. + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + Required. The ChannelGroup to update. The resource's + ``name`` field is used to identify the ChannelGroup to + be updated. - This corresponds to the ``parent`` field + This corresponds to the ``channel_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -9851,18 +10003,15 @@ def list_big_query_links( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListBigQueryLinksPager: - Response message for - ListBigQueryLinks RPC - Iterating over this object will yield - results and resolve additional pages - automatically. + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([channel_group, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -9871,21 +10020,25 @@ def list_big_query_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListBigQueryLinksRequest): - request = analytics_admin.ListBigQueryLinksRequest(request) + if not isinstance(request, analytics_admin.UpdateChannelGroupRequest): + request = analytics_admin.UpdateChannelGroupRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if channel_group is not None: + request.channel_group = channel_group + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_big_query_links] + rpc = self._transport._wrapped_methods[self._transport.update_channel_group] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata( + (("channel_group.name", request.channel_group.name),) + ), ) # Validate the universe domain. @@ -9899,44 +10052,30 @@ def list_big_query_links( metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListBigQueryLinksPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - def get_enhanced_measurement_settings( + def delete_channel_group( self, request: Optional[ - Union[analytics_admin.GetEnhancedMeasurementSettingsRequest, dict] + Union[analytics_admin.DeleteChannelGroupRequest, dict] ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.EnhancedMeasurementSettings: - r"""Returns the enhanced measurement settings for this - data stream. Note that the stream must enable enhanced - measurement for these settings to take effect. + ) -> None: + r"""Deletes a ChannelGroup on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.GetEnhancedMeasurementSettingsRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.DeleteChannelGroupRequest, dict]): The request object. Request message for - GetEnhancedMeasurementSettings RPC. + DeleteChannelGroup RPC. name (str): - Required. The name of the settings to lookup. Format: - properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings - Example: - "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + Required. The ChannelGroup to delete. + Example format: + properties/1234/channelGroups/5678 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -9946,14 +10085,6 @@ def get_enhanced_measurement_settings( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: - Singleton resource under a web - DataStream, configuring measurement of - additional site interactions and - content. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have @@ -9967,10 +10098,8 @@ def get_enhanced_measurement_settings( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance( - request, analytics_admin.GetEnhancedMeasurementSettingsRequest - ): - request = analytics_admin.GetEnhancedMeasurementSettingsRequest(request) + if not isinstance(request, analytics_admin.DeleteChannelGroupRequest): + request = analytics_admin.DeleteChannelGroupRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -9978,9 +10107,7 @@ def get_enhanced_measurement_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_enhanced_measurement_settings - ] + rpc = self._transport._wrapped_methods[self._transport.delete_channel_group] # Certain fields should be provided within the metadata header; # add these here. @@ -9992,55 +10119,32 @@ def get_enhanced_measurement_settings( self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # Done; return the response. - return response - - def update_enhanced_measurement_settings( + def set_automated_ga4_configuration_opt_out( self, request: Optional[ - Union[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict] + Union[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict] ] = None, *, - enhanced_measurement_settings: Optional[ - resources.EnhancedMeasurementSettings - ] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.EnhancedMeasurementSettings: - r"""Updates the enhanced measurement settings for this - data stream. Note that the stream must enable enhanced - measurement for these settings to take effect. + ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + r"""Sets the opt out status for the automated GA4 setup + process for a UA property. + Note: this has no effect on GA4 property. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateEnhancedMeasurementSettingsRequest, dict]): - The request object. Request message for - UpdateEnhancedMeasurementSettings RPC. - enhanced_measurement_settings (google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings): - Required. The settings to update. The ``name`` field is - used to identify the settings to be updated. - - This corresponds to the ``enhanced_measurement_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. Field names - must be in snake case (e.g., "field_to_update"). Omitted - fields will not be updated. To replace the entire - entity, use one path with the string "*" to match all - fields. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. + request (Union[google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutRequest, dict]): + The request object. Request for setting the opt out + status for the automated GA4 setup + process. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -10048,55 +10152,26 @@ def update_enhanced_measurement_settings( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: - Singleton resource under a web - DataStream, configuring measurement of - additional site interactions and - content. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([enhanced_measurement_settings, update_mask]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) + google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutResponse: + Response message for setting the opt + out status for the automated GA4 setup + process. + """ + # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. if not isinstance( - request, analytics_admin.UpdateEnhancedMeasurementSettingsRequest + request, analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest ): - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if enhanced_measurement_settings is not None: - request.enhanced_measurement_settings = enhanced_measurement_settings - if update_mask is not None: - request.update_mask = update_mask + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.update_enhanced_measurement_settings + self._transport.set_automated_ga4_configuration_opt_out ] - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - ( - ( - "enhanced_measurement_settings.name", - request.enhanced_measurement_settings.name, - ), - ) - ), - ) - # Validate the universe domain. self._validate_universe_domain() @@ -10111,25 +10186,25 @@ def update_enhanced_measurement_settings( # Done; return the response. return response - def create_connected_site_tag( + def fetch_automated_ga4_configuration_opt_out( self, request: Optional[ - Union[analytics_admin.CreateConnectedSiteTagRequest, dict] + Union[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict] ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.CreateConnectedSiteTagResponse: - r"""Creates a connected site tag for a Universal - Analytics property. You can create a maximum of 20 - connected site tags per property. Note: This API cannot - be used on GA4 properties. + ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + r"""Fetches the opt out status for the automated GA4 + setup process for a UA property. + Note: this has no effect on GA4 property. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateConnectedSiteTagRequest, dict]): - The request object. Request message for - CreateConnectedSiteTag RPC. + request (Union[google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutRequest, dict]): + The request object. Request for fetching the opt out + status for the automated GA4 setup + process. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -10137,21 +10212,26 @@ def create_connected_site_tag( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CreateConnectedSiteTagResponse: - Response message for - CreateConnectedSiteTag RPC. + google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutResponse: + Response message for fetching the opt + out status for the automated GA4 setup + process. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateConnectedSiteTagRequest): - request = analytics_admin.CreateConnectedSiteTagRequest(request) + if not isinstance( + request, analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest + ): + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( + request + ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[ - self._transport.create_connected_site_tag + self._transport.fetch_automated_ga4_configuration_opt_out ] # Validate the universe domain. @@ -10168,72 +10248,36 @@ def create_connected_site_tag( # Done; return the response. return response - def delete_connected_site_tag( + def create_big_query_link( self, request: Optional[ - Union[analytics_admin.DeleteConnectedSiteTagRequest, dict] + Union[analytics_admin.CreateBigQueryLinkRequest, dict] ] = None, *, + parent: Optional[str] = None, + bigquery_link: Optional[resources.BigQueryLink] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a connected site tag for a Universal - Analytics property. Note: this has no effect on GA4 - properties. + ) -> resources.BigQueryLink: + r"""Creates a BigQueryLink. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteConnectedSiteTagRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateBigQueryLinkRequest, dict]): The request object. Request message for - DeleteConnectedSiteTag RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteConnectedSiteTagRequest): - request = analytics_admin.DeleteConnectedSiteTagRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.delete_connected_site_tag - ] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def list_connected_site_tags( - self, - request: Optional[ - Union[analytics_admin.ListConnectedSiteTagsRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.ListConnectedSiteTagsResponse: - r"""Lists the connected site tags for a Universal - Analytics property. A maximum of 20 connected site tags - will be returned. Note: this has no effect on GA4 - property. + CreateBigQueryLink RPC. + parent (str): + Required. Example format: + properties/1234 - Args: - request (Union[google.analytics.admin_v1alpha.types.ListConnectedSiteTagsRequest, dict]): - The request object. Request message for - ListConnectedSiteTags RPC. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The BigQueryLink to create. + This corresponds to the ``bigquery_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -10241,77 +10285,42 @@ def list_connected_site_tags( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.ListConnectedSiteTagsResponse: - Response message for - ListConnectedSiteTags RPC. + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. """ # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, bigquery_link]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListConnectedSiteTagsRequest): - request = analytics_admin.ListConnectedSiteTagsRequest(request) + if not isinstance(request, analytics_admin.CreateBigQueryLinkRequest): + request = analytics_admin.CreateBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if bigquery_link is not None: + request.bigquery_link = bigquery_link # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_connected_site_tags] - - # Validate the universe domain. - self._validate_universe_domain() + rpc = self._transport._wrapped_methods[self._transport.create_big_query_link] - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) - # Done; return the response. - return response - - def fetch_connected_ga4_property( - self, - request: Optional[ - Union[analytics_admin.FetchConnectedGa4PropertyRequest, dict] - ] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.FetchConnectedGa4PropertyResponse: - r"""Given a specified UA property, looks up the GA4 - property connected to it. Note: this cannot be used with - GA4 properties. - - Args: - request (Union[google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyRequest, dict]): - The request object. Request for looking up GA4 property - connected to a UA property. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyResponse: - Response for looking up GA4 property - connected to a UA property. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.FetchConnectedGa4PropertyRequest): - request = analytics_admin.FetchConnectedGa4PropertyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.fetch_connected_ga4_property - ] - # Validate the universe domain. self._validate_universe_domain() @@ -10326,27 +10335,26 @@ def fetch_connected_ga4_property( # Done; return the response. return response - def get_ad_sense_link( + def get_big_query_link( self, - request: Optional[Union[analytics_admin.GetAdSenseLinkRequest, dict]] = None, + request: Optional[Union[analytics_admin.GetBigQueryLinkRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AdSenseLink: - r"""Looks up a single AdSenseLink. + ) -> resources.BigQueryLink: + r"""Lookup for a single BigQuery Link. Args: - request (Union[google.analytics.admin_v1alpha.types.GetAdSenseLinkRequest, dict]): - The request object. Request message to be passed to - GetAdSenseLink method. + request (Union[google.analytics.admin_v1alpha.types.GetBigQueryLinkRequest, dict]): + The request object. Request message for GetBigQueryLink + RPC. name (str): - Required. Unique identifier for the - AdSense Link requested. Format: - properties/{propertyId}/adSenseLinks/{linkId} - Example: - properties/1234/adSenseLinks/5678 + Required. The name of the BigQuery link to lookup. + Format: + properties/{property_id}/bigQueryLinks/{bigquery_link_id} + Example: properties/123/bigQueryLinks/456 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -10358,9 +10366,9 @@ def get_ad_sense_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AdSenseLink: - A link between a GA4 Property and an - AdSense for Content ad client. + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. """ # Create or coerce a protobuf request object. @@ -10375,8 +10383,8 @@ def get_ad_sense_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetAdSenseLinkRequest): - request = analytics_admin.GetAdSenseLinkRequest(request) + if not isinstance(request, analytics_admin.GetBigQueryLinkRequest): + request = analytics_admin.GetBigQueryLinkRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -10384,7 +10392,7 @@ def get_ad_sense_link( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_ad_sense_link] + rpc = self._transport._wrapped_methods[self._transport.get_big_query_link] # Certain fields should be provided within the metadata header; # add these here. @@ -10406,36 +10414,29 @@ def get_ad_sense_link( # Done; return the response. return response - def create_ad_sense_link( + def list_big_query_links( self, - request: Optional[Union[analytics_admin.CreateAdSenseLinkRequest, dict]] = None, + request: Optional[Union[analytics_admin.ListBigQueryLinksRequest, dict]] = None, *, parent: Optional[str] = None, - adsense_link: Optional[resources.AdSenseLink] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.AdSenseLink: - r"""Creates an AdSenseLink. + ) -> pagers.ListBigQueryLinksPager: + r"""Lists BigQuery Links on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateAdSenseLinkRequest, dict]): - The request object. Request message to be passed to - CreateAdSenseLink method. + request (Union[google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest, dict]): + The request object. Request message for ListBigQueryLinks + RPC. parent (str): - Required. The property for which to - create an AdSense Link. Format: - properties/{propertyId} Example: + Required. The name of the property to list BigQuery + links under. Format: properties/{property_id} Example: properties/1234 This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - adsense_link (google.analytics.admin_v1alpha.types.AdSenseLink): - Required. The AdSense Link to create - This corresponds to the ``adsense_link`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -10443,15 +10444,18 @@ def create_ad_sense_link( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.AdSenseLink: - A link between a GA4 Property and an - AdSense for Content ad client. + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListBigQueryLinksPager: + Response message for + ListBigQueryLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, adsense_link]) + has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10460,18 +10464,16 @@ def create_ad_sense_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateAdSenseLinkRequest): - request = analytics_admin.CreateAdSenseLinkRequest(request) + if not isinstance(request, analytics_admin.ListBigQueryLinksRequest): + request = analytics_admin.ListBigQueryLinksRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if adsense_link is not None: - request.adsense_link = adsense_link # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_ad_sense_link] + rpc = self._transport._wrapped_methods[self._transport.list_big_query_links] # Certain fields should be provided within the metadata header; # add these here. @@ -10490,44 +10492,1279 @@ def create_ad_sense_link( metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBigQueryLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def delete_ad_sense_link( + def delete_big_query_link( self, - request: Optional[Union[analytics_admin.DeleteAdSenseLinkRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.DeleteBigQueryLinkRequest, dict] + ] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes an AdSenseLink. + r"""Deletes a BigQueryLink on a property. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteAdSenseLinkRequest, dict]): - The request object. Request message to be passed to - DeleteAdSenseLink method. + request (Union[google.analytics.admin_v1alpha.types.DeleteBigQueryLinkRequest, dict]): + The request object. Request message for + DeleteBigQueryLink RPC. name (str): - Required. Unique identifier for the - AdSense Link to be deleted. Format: - properties/{propertyId}/adSenseLinks/{linkId} + Required. The BigQueryLink to delete. + Example format: + properties/1234/bigQueryLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteBigQueryLinkRequest): + request = analytics_admin.DeleteBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_big_query_link( + self, + request: Optional[ + Union[analytics_admin.UpdateBigQueryLinkRequest, dict] + ] = None, + *, + bigquery_link: Optional[resources.BigQueryLink] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.BigQueryLink: + r"""Updates a BigQueryLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateBigQueryLinkRequest, dict]): + The request object. Request message for + UpdateBigQueryLink RPC. + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``bigquery_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([bigquery_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateBigQueryLinkRequest): + request = analytics_admin.UpdateBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if bigquery_link is not None: + request.bigquery_link = bigquery_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("bigquery_link.name", request.bigquery_link.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_enhanced_measurement_settings( + self, + request: Optional[ + Union[analytics_admin.GetEnhancedMeasurementSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Returns the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetEnhancedMeasurementSettingsRequest, dict]): + The request object. Request message for + GetEnhancedMeasurementSettings RPC. + name (str): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings Example: - properties/1234/adSenseLinks/5678 + "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, analytics_admin.GetEnhancedMeasurementSettingsRequest + ): + request = analytics_admin.GetEnhancedMeasurementSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_enhanced_measurement_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_enhanced_measurement_settings( + self, + request: Optional[ + Union[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict] + ] = None, + *, + enhanced_measurement_settings: Optional[ + resources.EnhancedMeasurementSettings + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Updates the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateEnhancedMeasurementSettingsRequest, dict]): + The request object. Request message for + UpdateEnhancedMeasurementSettings RPC. + enhanced_measurement_settings (google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``enhanced_measurement_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([enhanced_measurement_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, analytics_admin.UpdateEnhancedMeasurementSettingsRequest + ): + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enhanced_measurement_settings is not None: + request.enhanced_measurement_settings = enhanced_measurement_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_enhanced_measurement_settings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "enhanced_measurement_settings.name", + request.enhanced_measurement_settings.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_connected_site_tag( + self, + request: Optional[ + Union[analytics_admin.CreateConnectedSiteTagRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.CreateConnectedSiteTagResponse: + r"""Creates a connected site tag for a Universal + Analytics property. You can create a maximum of 20 + connected site tags per property. Note: This API cannot + be used on GA4 properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateConnectedSiteTagRequest, dict]): + The request object. Request message for + CreateConnectedSiteTag RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CreateConnectedSiteTagResponse: + Response message for + CreateConnectedSiteTag RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConnectedSiteTagRequest): + request = analytics_admin.CreateConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_connected_site_tag + ] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_connected_site_tag( + self, + request: Optional[ + Union[analytics_admin.DeleteConnectedSiteTagRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a connected site tag for a Universal + Analytics property. Note: this has no effect on GA4 + properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteConnectedSiteTagRequest, dict]): + The request object. Request message for + DeleteConnectedSiteTag RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConnectedSiteTagRequest): + request = analytics_admin.DeleteConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_connected_site_tag + ] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_connected_site_tags( + self, + request: Optional[ + Union[analytics_admin.ListConnectedSiteTagsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ListConnectedSiteTagsResponse: + r"""Lists the connected site tags for a Universal + Analytics property. A maximum of 20 connected site tags + will be returned. Note: this has no effect on GA4 + property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListConnectedSiteTagsRequest, dict]): + The request object. Request message for + ListConnectedSiteTags RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ListConnectedSiteTagsResponse: + Response message for + ListConnectedSiteTags RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConnectedSiteTagsRequest): + request = analytics_admin.ListConnectedSiteTagsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_connected_site_tags] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fetch_connected_ga4_property( + self, + request: Optional[ + Union[analytics_admin.FetchConnectedGa4PropertyRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.FetchConnectedGa4PropertyResponse: + r"""Given a specified UA property, looks up the GA4 + property connected to it. Note: this cannot be used with + GA4 properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyRequest, dict]): + The request object. Request for looking up GA4 property + connected to a UA property. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyResponse: + Response for looking up GA4 property + connected to a UA property. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.FetchConnectedGa4PropertyRequest): + request = analytics_admin.FetchConnectedGa4PropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_connected_ga4_property + ] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ad_sense_link( + self, + request: Optional[Union[analytics_admin.GetAdSenseLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AdSenseLink: + r"""Looks up a single AdSenseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetAdSenseLinkRequest, dict]): + The request object. Request message to be passed to + GetAdSenseLink method. + name (str): + Required. Unique identifier for the + AdSense Link requested. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAdSenseLinkRequest): + request = analytics_admin.GetAdSenseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ad_sense_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_ad_sense_link( + self, + request: Optional[Union[analytics_admin.CreateAdSenseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + adsense_link: Optional[resources.AdSenseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AdSenseLink: + r"""Creates an AdSenseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateAdSenseLinkRequest, dict]): + The request object. Request message to be passed to + CreateAdSenseLink method. + parent (str): + Required. The property for which to + create an AdSense Link. Format: + properties/{propertyId} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + adsense_link (google.analytics.admin_v1alpha.types.AdSenseLink): + Required. The AdSense Link to create + This corresponds to the ``adsense_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, adsense_link]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAdSenseLinkRequest): + request = analytics_admin.CreateAdSenseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if adsense_link is not None: + request.adsense_link = adsense_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ad_sense_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_ad_sense_link( + self, + request: Optional[Union[analytics_admin.DeleteAdSenseLinkRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an AdSenseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteAdSenseLinkRequest, dict]): + The request object. Request message to be passed to + DeleteAdSenseLink method. + name (str): + Required. Unique identifier for the + AdSense Link to be deleted. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAdSenseLinkRequest): + request = analytics_admin.DeleteAdSenseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_ad_sense_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_ad_sense_links( + self, + request: Optional[Union[analytics_admin.ListAdSenseLinksRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAdSenseLinksPager: + r"""Lists AdSenseLinks on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest, dict]): + The request object. Request message to be passed to + ListAdSenseLinks method. + parent (str): + Required. Resource name of the parent + property. Format: + properties/{propertyId} + Example: properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAdSenseLinksPager: + Response message for ListAdSenseLinks + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAdSenseLinksRequest): + request = analytics_admin.ListAdSenseLinksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ad_sense_links] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAdSenseLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_event_create_rule( + self, + request: Optional[ + Union[analytics_admin.GetEventCreateRuleRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Lookup for a single EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetEventCreateRuleRequest, dict]): + The request object. Request message for + GetEventCreateRule RPC. + name (str): + Required. The name of the + EventCreateRule to get. Example format: + properties/123/dataStreams/456/eventCreateRules/789 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEventCreateRuleRequest): + request = analytics_admin.GetEventCreateRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_event_create_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_event_create_rules( + self, + request: Optional[ + Union[analytics_admin.ListEventCreateRulesRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEventCreateRulesPager: + r"""Lists EventCreateRules on a web data stream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest, dict]): + The request object. Request message for + ListEventCreateRules RPC. + parent (str): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventCreateRulesPager: + Response message for + ListEventCreateRules RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListEventCreateRulesRequest): + request = analytics_admin.ListEventCreateRulesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_event_create_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEventCreateRulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event_create_rule( + self, + request: Optional[ + Union[analytics_admin.CreateEventCreateRuleRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Creates an EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateEventCreateRuleRequest, dict]): + The request object. Request message for + CreateEventCreateRule RPC. + parent (str): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + Required. The EventCreateRule to + create. + + This corresponds to the ``event_create_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_create_rule]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateEventCreateRuleRequest): + request = analytics_admin.CreateEventCreateRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_create_rule is not None: + request.event_create_rule = event_create_rule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event_create_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_event_create_rule( + self, + request: Optional[ + Union[analytics_admin.UpdateEventCreateRuleRequest, dict] + ] = None, + *, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Updates an EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateEventCreateRuleRequest, dict]): + The request object. Request message for + UpdateEventCreateRule RPC. + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + Required. The EventCreateRule to update. The resource's + ``name`` field is used to identify the EventCreateRule + to be updated. + + This corresponds to the ``event_create_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) + has_flattened_params = any([event_create_rule, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10536,56 +11773,64 @@ def delete_ad_sense_link( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteAdSenseLinkRequest): - request = analytics_admin.DeleteAdSenseLinkRequest(request) + if not isinstance(request, analytics_admin.UpdateEventCreateRuleRequest): + request = analytics_admin.UpdateEventCreateRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: - request.name = name + if event_create_rule is not None: + request.event_create_rule = event_create_rule + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_ad_sense_link] + rpc = self._transport._wrapped_methods[self._transport.update_event_create_rule] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata( + (("event_create_rule.name", request.event_create_rule.name),) + ), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - rpc( + response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - def list_ad_sense_links( + # Done; return the response. + return response + + def delete_event_create_rule( self, - request: Optional[Union[analytics_admin.ListAdSenseLinksRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.DeleteEventCreateRuleRequest, dict] + ] = None, *, - parent: Optional[str] = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAdSenseLinksPager: - r"""Lists AdSenseLinks on a property. + ) -> None: + r"""Deletes an EventCreateRule. Args: - request (Union[google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest, dict]): - The request object. Request message to be passed to - ListAdSenseLinks method. - parent (str): - Required. Resource name of the parent - property. Format: - properties/{propertyId} - Example: properties/1234 + request (Union[google.analytics.admin_v1alpha.types.DeleteEventCreateRuleRequest, dict]): + The request object. Request message for + DeleteEventCreateRule RPC. + name (str): + Required. Example format: - This corresponds to the ``parent`` field + properties/123/dataStreams/456/eventCreateRules/789 + + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -10593,20 +11838,11 @@ def list_ad_sense_links( timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAdSenseLinksPager: - Response message for ListAdSenseLinks - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) + has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10615,69 +11851,53 @@ def list_ad_sense_links( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListAdSenseLinksRequest): - request = analytics_admin.ListAdSenseLinksRequest(request) + if not isinstance(request, analytics_admin.DeleteEventCreateRuleRequest): + request = analytics_admin.DeleteEventCreateRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_ad_sense_links] + rpc = self._transport._wrapped_methods[self._transport.delete_event_create_rule] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. self._validate_universe_domain() # Send the request. - response = rpc( + rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAdSenseLinksPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_event_create_rule( + def get_event_edit_rule( self, - request: Optional[ - Union[analytics_admin.GetEventCreateRuleRequest, dict] - ] = None, + request: Optional[Union[analytics_admin.GetEventEditRuleRequest, dict]] = None, *, name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Lookup for a single EventCreateRule. + ) -> event_create_and_edit.EventEditRule: + r"""Lookup for a single EventEditRule. Args: - request (Union[google.analytics.admin_v1alpha.types.GetEventCreateRuleRequest, dict]): - The request object. Request message for - GetEventCreateRule RPC. + request (Union[google.analytics.admin_v1alpha.types.GetEventEditRuleRequest, dict]): + The request object. Request message for GetEventEditRule + RPC. name (str): Required. The name of the - EventCreateRule to get. Example format: - properties/123/dataStreams/456/eventCreateRules/789 + EventEditRule to get. Example format: + properties/123/dataStreams/456/eventEditRules/789 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -10689,21 +11909,21 @@ def get_event_create_rule( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ # Create or coerce a protobuf request object. @@ -10718,8 +11938,8 @@ def get_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.GetEventCreateRuleRequest): - request = analytics_admin.GetEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.GetEventEditRuleRequest): + request = analytics_admin.GetEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -10727,7 +11947,7 @@ def get_event_create_rule( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_event_create_rule] + rpc = self._transport._wrapped_methods[self._transport.get_event_edit_rule] # Certain fields should be provided within the metadata header; # add these here. @@ -10749,23 +11969,23 @@ def get_event_create_rule( # Done; return the response. return response - def list_event_create_rules( + def list_event_edit_rules( self, request: Optional[ - Union[analytics_admin.ListEventCreateRulesRequest, dict] + Union[analytics_admin.ListEventEditRulesRequest, dict] ] = None, *, parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEventCreateRulesPager: - r"""Lists EventCreateRules on a web data stream. + ) -> pagers.ListEventEditRulesPager: + r"""Lists EventEditRules on a web data stream. Args: - request (Union[google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ListEventEditRulesRequest, dict]): The request object. Request message for - ListEventCreateRules RPC. + ListEventEditRules RPC. parent (str): Required. Example format: properties/123/dataStreams/456 @@ -10780,9 +12000,9 @@ def list_event_create_rules( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventCreateRulesPager: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventEditRulesPager: Response message for - ListEventCreateRules RPC. + ListEventEditRules RPC. Iterating over this object will yield results and resolve additional pages automatically. @@ -10800,8 +12020,8 @@ def list_event_create_rules( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.ListEventCreateRulesRequest): - request = analytics_admin.ListEventCreateRulesRequest(request) + if not isinstance(request, analytics_admin.ListEventEditRulesRequest): + request = analytics_admin.ListEventEditRulesRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -10809,7 +12029,7 @@ def list_event_create_rules( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_event_create_rules] + rpc = self._transport._wrapped_methods[self._transport.list_event_edit_rules] # Certain fields should be provided within the metadata header; # add these here. @@ -10830,7 +12050,7 @@ def list_event_create_rules( # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. - response = pagers.ListEventCreateRulesPager( + response = pagers.ListEventEditRulesPager( method=rpc, request=request, response=response, @@ -10842,24 +12062,24 @@ def list_event_create_rules( # Done; return the response. return response - def create_event_create_rule( + def create_event_edit_rule( self, request: Optional[ - Union[analytics_admin.CreateEventCreateRuleRequest, dict] + Union[analytics_admin.CreateEventEditRuleRequest, dict] ] = None, *, parent: Optional[str] = None, - event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Creates an EventCreateRule. + ) -> event_create_and_edit.EventEditRule: + r"""Creates an EventEditRule. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateEventCreateRuleRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.CreateEventEditRuleRequest, dict]): The request object. Request message for - CreateEventCreateRule RPC. + CreateEventEditRule RPC. parent (str): Required. Example format: properties/123/dataStreams/456 @@ -10867,11 +12087,11 @@ def create_event_create_rule( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): - Required. The EventCreateRule to + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to create. - This corresponds to the ``event_create_rule`` field + This corresponds to the ``event_edit_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -10881,27 +12101,27 @@ def create_event_create_rule( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, event_create_rule]) + has_flattened_params = any([parent, event_edit_rule]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -10910,18 +12130,18 @@ def create_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateEventCreateRuleRequest): - request = analytics_admin.CreateEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.CreateEventEditRuleRequest): + request = analytics_admin.CreateEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if event_create_rule is not None: - request.event_create_rule = event_create_rule + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_event_create_rule] + rpc = self._transport._wrapped_methods[self._transport.create_event_edit_rule] # Certain fields should be provided within the metadata header; # add these here. @@ -10943,30 +12163,30 @@ def create_event_create_rule( # Done; return the response. return response - def update_event_create_rule( + def update_event_edit_rule( self, request: Optional[ - Union[analytics_admin.UpdateEventCreateRuleRequest, dict] + Union[analytics_admin.UpdateEventEditRuleRequest, dict] ] = None, *, - event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = None, update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Updates an EventCreateRule. + ) -> event_create_and_edit.EventEditRule: + r"""Updates an EventEditRule. Args: - request (Union[google.analytics.admin_v1alpha.types.UpdateEventCreateRuleRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.UpdateEventEditRuleRequest, dict]): The request object. Request message for - UpdateEventCreateRule RPC. - event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): - Required. The EventCreateRule to update. The resource's - ``name`` field is used to identify the EventCreateRule - to be updated. + UpdateEventEditRule RPC. + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to update. The resource's + ``name`` field is used to identify the EventEditRule to + be updated. - This corresponds to the ``event_create_rule`` field + This corresponds to the ``event_edit_rule`` field on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): @@ -10986,27 +12206,27 @@ def update_event_create_rule( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ # Create or coerce a protobuf request object. # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([event_create_rule, update_mask]) + has_flattened_params = any([event_edit_rule, update_mask]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -11015,24 +12235,24 @@ def update_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.UpdateEventCreateRuleRequest): - request = analytics_admin.UpdateEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.UpdateEventEditRuleRequest): + request = analytics_admin.UpdateEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. - if event_create_rule is not None: - request.event_create_rule = event_create_rule + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule if update_mask is not None: request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_event_create_rule] + rpc = self._transport._wrapped_methods[self._transport.update_event_edit_rule] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata( - (("event_create_rule.name", request.event_create_rule.name),) + (("event_edit_rule.name", request.event_edit_rule.name),) ), ) @@ -11050,10 +12270,10 @@ def update_event_create_rule( # Done; return the response. return response - def delete_event_create_rule( + def delete_event_edit_rule( self, request: Optional[ - Union[analytics_admin.DeleteEventCreateRuleRequest, dict] + Union[analytics_admin.DeleteEventEditRuleRequest, dict] ] = None, *, name: Optional[str] = None, @@ -11061,16 +12281,15 @@ def delete_event_create_rule( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes an EventCreateRule. + r"""Deletes an EventEditRule. Args: - request (Union[google.analytics.admin_v1alpha.types.DeleteEventCreateRuleRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.DeleteEventEditRuleRequest, dict]): The request object. Request message for - DeleteEventCreateRule RPC. + DeleteEventEditRule RPC. name (str): Required. Example format: - - properties/123/dataStreams/456/eventCreateRules/789 + properties/123/dataStreams/456/eventEditRules/789 This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -11093,8 +12312,8 @@ def delete_event_create_rule( # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.DeleteEventCreateRuleRequest): - request = analytics_admin.DeleteEventCreateRuleRequest(request) + if not isinstance(request, analytics_admin.DeleteEventEditRuleRequest): + request = analytics_admin.DeleteEventEditRuleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -11102,7 +12321,7 @@ def delete_event_create_rule( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_event_create_rule] + rpc = self._transport._wrapped_methods[self._transport.delete_event_edit_rule] # Certain fields should be provided within the metadata header; # add these here. @@ -11121,6 +12340,56 @@ def delete_event_create_rule( metadata=metadata, ) + def reorder_event_edit_rules( + self, + request: Optional[ + Union[analytics_admin.ReorderEventEditRulesRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Changes the processing order of event edit rules on + the specified stream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ReorderEventEditRulesRequest, dict]): + The request object. Request message for + ReorderEventEditRules RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ReorderEventEditRulesRequest): + request = analytics_admin.ReorderEventEditRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.reorder_event_edit_rules] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + def update_data_redaction_settings( self, request: Optional[ @@ -11425,7 +12694,7 @@ def create_calculated_metric( metric's resource name. This value should be 1-80 characters and valid - characters are `[a-zA-Z0-9_]`, no spaces allowed. + characters are /[a-zA-Z0-9_]/, no spaces allowed. calculated_metric_id must be unique between all calculated metrics under a property. The calculated_metric_id is used when referencing this @@ -12166,19 +13435,21 @@ def delete_rollup_property_source_link( metadata=metadata, ) - def create_subproperty( + def provision_subproperty( self, - request: Optional[Union[analytics_admin.CreateSubpropertyRequest, dict]] = None, + request: Optional[ + Union[analytics_admin.ProvisionSubpropertyRequest, dict] + ] = None, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.CreateSubpropertyResponse: + ) -> analytics_admin.ProvisionSubpropertyResponse: r"""Create a subproperty and a subproperty event filter that applies to the created subproperty. Args: - request (Union[google.analytics.admin_v1alpha.types.CreateSubpropertyRequest, dict]): + request (Union[google.analytics.admin_v1alpha.types.ProvisionSubpropertyRequest, dict]): The request object. Request message for CreateSubproperty RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -12188,20 +13459,20 @@ def create_subproperty( sent along with the request as metadata. Returns: - google.analytics.admin_v1alpha.types.CreateSubpropertyResponse: + google.analytics.admin_v1alpha.types.ProvisionSubpropertyResponse: Response message for - CreateSubproperty RPC. + ProvisionSubproperty RPC. """ # Create or coerce a protobuf request object. # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, analytics_admin.CreateSubpropertyRequest): - request = analytics_admin.CreateSubpropertyRequest(request) + if not isinstance(request, analytics_admin.ProvisionSubpropertyRequest): + request = analytics_admin.ProvisionSubpropertyRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_subproperty] + rpc = self._transport._wrapped_methods[self._transport.provision_subproperty] # Validate the universe domain. self._validate_universe_domain() diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py index ed8c53f696c4..1b458359c185 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py @@ -1442,6 +1442,158 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListKeyEventsPager: + """A pager for iterating through ``list_key_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``key_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKeyEvents`` requests and continue to iterate + through the ``key_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., analytics_admin.ListKeyEventsResponse], + request: analytics_admin.ListKeyEventsRequest, + response: analytics_admin.ListKeyEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListKeyEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListKeyEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListKeyEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListKeyEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resources.KeyEvent]: + for page in self.pages: + yield from page.key_events + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListKeyEventsAsyncPager: + """A pager for iterating through ``list_key_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``key_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeyEvents`` requests and continue to iterate + through the ``key_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[analytics_admin.ListKeyEventsResponse]], + request: analytics_admin.ListKeyEventsRequest, + response: analytics_admin.ListKeyEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListKeyEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListKeyEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListKeyEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListKeyEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.KeyEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.key_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListDisplayVideo360AdvertiserLinksPager: """A pager for iterating through ``list_display_video360_advertiser_links`` requests. @@ -3457,6 +3609,158 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListEventEditRulesPager: + """A pager for iterating through ``list_event_edit_rules`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_edit_rules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEventEditRules`` requests and continue to iterate + through the ``event_edit_rules`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., analytics_admin.ListEventEditRulesResponse], + request: analytics_admin.ListEventEditRulesRequest, + response: analytics_admin.ListEventEditRulesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListEventEditRulesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListEventEditRulesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListEventEditRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListEventEditRulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[event_create_and_edit.EventEditRule]: + for page in self.pages: + yield from page.event_edit_rules + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEventEditRulesAsyncPager: + """A pager for iterating through ``list_event_edit_rules`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_edit_rules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEventEditRules`` requests and continue to iterate + through the ``event_edit_rules`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[analytics_admin.ListEventEditRulesResponse]], + request: analytics_admin.ListEventEditRulesRequest, + response: analytics_admin.ListEventEditRulesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListEventEditRulesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListEventEditRulesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListEventEditRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListEventEditRulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[event_create_and_edit.EventEditRule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_edit_rules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListCalculatedMetricsPager: """A pager for iterating through ``list_calculated_metrics`` requests. diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py index 9e0d10b2ba63..b920e8f88c08 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py @@ -343,6 +343,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_key_event: gapic_v1.method.wrap_method( + self.create_key_event, + default_timeout=None, + client_info=client_info, + ), + self.update_key_event: gapic_v1.method.wrap_method( + self.update_key_event, + default_timeout=None, + client_info=client_info, + ), + self.get_key_event: gapic_v1.method.wrap_method( + self.get_key_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_key_event: gapic_v1.method.wrap_method( + self.delete_key_event, + default_timeout=None, + client_info=client_info, + ), + self.list_key_events: gapic_v1.method.wrap_method( + self.list_key_events, + default_timeout=None, + client_info=client_info, + ), self.get_display_video360_advertiser_link: gapic_v1.method.wrap_method( self.get_display_video360_advertiser_link, default_timeout=None, @@ -653,6 +678,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_big_query_link: gapic_v1.method.wrap_method( + self.create_big_query_link, + default_timeout=None, + client_info=client_info, + ), self.get_big_query_link: gapic_v1.method.wrap_method( self.get_big_query_link, default_timeout=None, @@ -663,6 +693,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_big_query_link: gapic_v1.method.wrap_method( + self.delete_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_link: gapic_v1.method.wrap_method( + self.update_big_query_link, + default_timeout=None, + client_info=client_info, + ), self.get_enhanced_measurement_settings: gapic_v1.method.wrap_method( self.get_enhanced_measurement_settings, default_timeout=60.0, @@ -738,6 +778,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_event_edit_rule: gapic_v1.method.wrap_method( + self.get_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_event_edit_rules: gapic_v1.method.wrap_method( + self.list_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_event_edit_rule: gapic_v1.method.wrap_method( + self.create_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_event_edit_rule: gapic_v1.method.wrap_method( + self.update_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_edit_rule: gapic_v1.method.wrap_method( + self.delete_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.reorder_event_edit_rules: gapic_v1.method.wrap_method( + self.reorder_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), self.update_data_redaction_settings: gapic_v1.method.wrap_method( self.update_data_redaction_settings, default_timeout=None, @@ -798,8 +868,8 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - self.create_subproperty: gapic_v1.method.wrap_method( - self.create_subproperty, + self.provision_subproperty: gapic_v1.method.wrap_method( + self.provision_subproperty, default_timeout=None, client_info=client_info, ), @@ -1245,6 +1315,54 @@ def list_conversion_events( ]: raise NotImplementedError() + @property + def create_key_event( + self, + ) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + Union[resources.KeyEvent, Awaitable[resources.KeyEvent]], + ]: + raise NotImplementedError() + + @property + def update_key_event( + self, + ) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + Union[resources.KeyEvent, Awaitable[resources.KeyEvent]], + ]: + raise NotImplementedError() + + @property + def get_key_event( + self, + ) -> Callable[ + [analytics_admin.GetKeyEventRequest], + Union[resources.KeyEvent, Awaitable[resources.KeyEvent]], + ]: + raise NotImplementedError() + + @property + def delete_key_event( + self, + ) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_key_events( + self, + ) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + Union[ + analytics_admin.ListKeyEventsResponse, + Awaitable[analytics_admin.ListKeyEventsResponse], + ], + ]: + raise NotImplementedError() + @property def get_display_video360_advertiser_link( self, @@ -1893,6 +2011,15 @@ def fetch_automated_ga4_configuration_opt_out( ]: raise NotImplementedError() + @property + def create_big_query_link( + self, + ) -> Callable[ + [analytics_admin.CreateBigQueryLinkRequest], + Union[resources.BigQueryLink, Awaitable[resources.BigQueryLink]], + ]: + raise NotImplementedError() + @property def get_big_query_link( self, @@ -1914,6 +2041,24 @@ def list_big_query_links( ]: raise NotImplementedError() + @property + def delete_big_query_link( + self, + ) -> Callable[ + [analytics_admin.DeleteBigQueryLinkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def update_big_query_link( + self, + ) -> Callable[ + [analytics_admin.UpdateBigQueryLinkRequest], + Union[resources.BigQueryLink, Awaitable[resources.BigQueryLink]], + ]: + raise NotImplementedError() + @property def get_enhanced_measurement_settings( self, @@ -2079,6 +2224,72 @@ def delete_event_create_rule( ]: raise NotImplementedError() + @property + def get_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], + Union[ + event_create_and_edit.EventEditRule, + Awaitable[event_create_and_edit.EventEditRule], + ], + ]: + raise NotImplementedError() + + @property + def list_event_edit_rules( + self, + ) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + Union[ + analytics_admin.ListEventEditRulesResponse, + Awaitable[analytics_admin.ListEventEditRulesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + Union[ + event_create_and_edit.EventEditRule, + Awaitable[event_create_and_edit.EventEditRule], + ], + ]: + raise NotImplementedError() + + @property + def update_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + Union[ + event_create_and_edit.EventEditRule, + Awaitable[event_create_and_edit.EventEditRule], + ], + ]: + raise NotImplementedError() + + @property + def delete_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.DeleteEventEditRuleRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def reorder_event_edit_rules( + self, + ) -> Callable[ + [analytics_admin.ReorderEventEditRulesRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + @property def update_data_redaction_settings( self, @@ -2207,13 +2418,13 @@ def delete_rollup_property_source_link( raise NotImplementedError() @property - def create_subproperty( + def provision_subproperty( self, ) -> Callable[ - [analytics_admin.CreateSubpropertyRequest], + [analytics_admin.ProvisionSubpropertyRequest], Union[ - analytics_admin.CreateSubpropertyResponse, - Awaitable[analytics_admin.CreateSubpropertyResponse], + analytics_admin.ProvisionSubpropertyResponse, + Awaitable[analytics_admin.ProvisionSubpropertyResponse], ], ]: raise NotImplementedError() diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py index 4d51d993b37b..e73db13774f3 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py @@ -1289,8 +1289,8 @@ def create_conversion_event( ]: r"""Return a callable for the create conversion event method over gRPC. - Creates a conversion event with the specified - attributes. + Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. Returns: Callable[[~.CreateConversionEventRequest], @@ -1318,8 +1318,8 @@ def update_conversion_event( ]: r"""Return a callable for the update conversion event method over gRPC. - Updates a conversion event with the specified - attributes. + Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. Returns: Callable[[~.UpdateConversionEventRequest], @@ -1347,7 +1347,8 @@ def get_conversion_event( ]: r"""Return a callable for the get conversion event method over gRPC. - Retrieve a single conversion event. + Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. Returns: Callable[[~.GetConversionEventRequest], @@ -1373,7 +1374,8 @@ def delete_conversion_event( ) -> Callable[[analytics_admin.DeleteConversionEventRequest], empty_pb2.Empty]: r"""Return a callable for the delete conversion event method over gRPC. - Deletes a conversion event in a property. + Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. Returns: Callable[[~.DeleteConversionEventRequest], @@ -1402,8 +1404,9 @@ def list_conversion_events( ]: r"""Return a callable for the list conversion events method over gRPC. - Returns a list of conversion events in the specified - parent property. + Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + Returns an empty list if no conversion events are found. Returns: @@ -1424,6 +1427,140 @@ def list_conversion_events( ) return self._stubs["list_conversion_events"] + @property + def create_key_event( + self, + ) -> Callable[[analytics_admin.CreateKeyEventRequest], resources.KeyEvent]: + r"""Return a callable for the create key event method over gRPC. + + Creates a Key Event. + + Returns: + Callable[[~.CreateKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_key_event" not in self._stubs: + self._stubs["create_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateKeyEvent", + request_serializer=analytics_admin.CreateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs["create_key_event"] + + @property + def update_key_event( + self, + ) -> Callable[[analytics_admin.UpdateKeyEventRequest], resources.KeyEvent]: + r"""Return a callable for the update key event method over gRPC. + + Updates a Key Event. + + Returns: + Callable[[~.UpdateKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_key_event" not in self._stubs: + self._stubs["update_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateKeyEvent", + request_serializer=analytics_admin.UpdateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs["update_key_event"] + + @property + def get_key_event( + self, + ) -> Callable[[analytics_admin.GetKeyEventRequest], resources.KeyEvent]: + r"""Return a callable for the get key event method over gRPC. + + Retrieve a single Key Event. + + Returns: + Callable[[~.GetKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_key_event" not in self._stubs: + self._stubs["get_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/GetKeyEvent", + request_serializer=analytics_admin.GetKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs["get_key_event"] + + @property + def delete_key_event( + self, + ) -> Callable[[analytics_admin.DeleteKeyEventRequest], empty_pb2.Empty]: + r"""Return a callable for the delete key event method over gRPC. + + Deletes a Key Event. + + Returns: + Callable[[~.DeleteKeyEventRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_key_event" not in self._stubs: + self._stubs["delete_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteKeyEvent", + request_serializer=analytics_admin.DeleteKeyEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_key_event"] + + @property + def list_key_events( + self, + ) -> Callable[ + [analytics_admin.ListKeyEventsRequest], analytics_admin.ListKeyEventsResponse + ]: + r"""Return a callable for the list key events method over gRPC. + + Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Returns: + Callable[[~.ListKeyEventsRequest], + ~.ListKeyEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_key_events" not in self._stubs: + self._stubs["list_key_events"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ListKeyEvents", + request_serializer=analytics_admin.ListKeyEventsRequest.serialize, + response_deserializer=analytics_admin.ListKeyEventsResponse.deserialize, + ) + return self._stubs["list_key_events"] + @property def get_display_video360_advertiser_link( self, @@ -3243,6 +3380,32 @@ def fetch_automated_ga4_configuration_opt_out( ) return self._stubs["fetch_automated_ga4_configuration_opt_out"] + @property + def create_big_query_link( + self, + ) -> Callable[[analytics_admin.CreateBigQueryLinkRequest], resources.BigQueryLink]: + r"""Return a callable for the create big query link method over gRPC. + + Creates a BigQueryLink. + + Returns: + Callable[[~.CreateBigQueryLinkRequest], + ~.BigQueryLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_big_query_link" not in self._stubs: + self._stubs["create_big_query_link"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateBigQueryLink", + request_serializer=analytics_admin.CreateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs["create_big_query_link"] + @property def get_big_query_link( self, @@ -3298,6 +3461,58 @@ def list_big_query_links( ) return self._stubs["list_big_query_links"] + @property + def delete_big_query_link( + self, + ) -> Callable[[analytics_admin.DeleteBigQueryLinkRequest], empty_pb2.Empty]: + r"""Return a callable for the delete big query link method over gRPC. + + Deletes a BigQueryLink on a property. + + Returns: + Callable[[~.DeleteBigQueryLinkRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_big_query_link" not in self._stubs: + self._stubs["delete_big_query_link"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteBigQueryLink", + request_serializer=analytics_admin.DeleteBigQueryLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_big_query_link"] + + @property + def update_big_query_link( + self, + ) -> Callable[[analytics_admin.UpdateBigQueryLinkRequest], resources.BigQueryLink]: + r"""Return a callable for the update big query link method over gRPC. + + Updates a BigQueryLink. + + Returns: + Callable[[~.UpdateBigQueryLinkRequest], + ~.BigQueryLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_big_query_link" not in self._stubs: + self._stubs["update_big_query_link"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateBigQueryLink", + request_serializer=analytics_admin.UpdateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs["update_big_query_link"] + @property def get_enhanced_measurement_settings( self, @@ -3738,6 +3953,174 @@ def delete_event_create_rule( ) return self._stubs["delete_event_create_rule"] + @property + def get_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], event_create_and_edit.EventEditRule + ]: + r"""Return a callable for the get event edit rule method over gRPC. + + Lookup for a single EventEditRule. + + Returns: + Callable[[~.GetEventEditRuleRequest], + ~.EventEditRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_event_edit_rule" not in self._stubs: + self._stubs["get_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEventEditRule", + request_serializer=analytics_admin.GetEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs["get_event_edit_rule"] + + @property + def list_event_edit_rules( + self, + ) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + analytics_admin.ListEventEditRulesResponse, + ]: + r"""Return a callable for the list event edit rules method over gRPC. + + Lists EventEditRules on a web data stream. + + Returns: + Callable[[~.ListEventEditRulesRequest], + ~.ListEventEditRulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_event_edit_rules" not in self._stubs: + self._stubs["list_event_edit_rules"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ListEventEditRules", + request_serializer=analytics_admin.ListEventEditRulesRequest.serialize, + response_deserializer=analytics_admin.ListEventEditRulesResponse.deserialize, + ) + return self._stubs["list_event_edit_rules"] + + @property + def create_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + event_create_and_edit.EventEditRule, + ]: + r"""Return a callable for the create event edit rule method over gRPC. + + Creates an EventEditRule. + + Returns: + Callable[[~.CreateEventEditRuleRequest], + ~.EventEditRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_event_edit_rule" not in self._stubs: + self._stubs["create_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateEventEditRule", + request_serializer=analytics_admin.CreateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs["create_event_edit_rule"] + + @property + def update_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + event_create_and_edit.EventEditRule, + ]: + r"""Return a callable for the update event edit rule method over gRPC. + + Updates an EventEditRule. + + Returns: + Callable[[~.UpdateEventEditRuleRequest], + ~.EventEditRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_event_edit_rule" not in self._stubs: + self._stubs["update_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEventEditRule", + request_serializer=analytics_admin.UpdateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs["update_event_edit_rule"] + + @property + def delete_event_edit_rule( + self, + ) -> Callable[[analytics_admin.DeleteEventEditRuleRequest], empty_pb2.Empty]: + r"""Return a callable for the delete event edit rule method over gRPC. + + Deletes an EventEditRule. + + Returns: + Callable[[~.DeleteEventEditRuleRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_event_edit_rule" not in self._stubs: + self._stubs["delete_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteEventEditRule", + request_serializer=analytics_admin.DeleteEventEditRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_event_edit_rule"] + + @property + def reorder_event_edit_rules( + self, + ) -> Callable[[analytics_admin.ReorderEventEditRulesRequest], empty_pb2.Empty]: + r"""Return a callable for the reorder event edit rules method over gRPC. + + Changes the processing order of event edit rules on + the specified stream. + + Returns: + Callable[[~.ReorderEventEditRulesRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "reorder_event_edit_rules" not in self._stubs: + self._stubs["reorder_event_edit_rules"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ReorderEventEditRules", + request_serializer=analytics_admin.ReorderEventEditRulesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["reorder_event_edit_rules"] + @property def update_data_redaction_settings( self, @@ -4107,20 +4490,20 @@ def delete_rollup_property_source_link( return self._stubs["delete_rollup_property_source_link"] @property - def create_subproperty( + def provision_subproperty( self, ) -> Callable[ - [analytics_admin.CreateSubpropertyRequest], - analytics_admin.CreateSubpropertyResponse, + [analytics_admin.ProvisionSubpropertyRequest], + analytics_admin.ProvisionSubpropertyResponse, ]: - r"""Return a callable for the create subproperty method over gRPC. + r"""Return a callable for the provision subproperty method over gRPC. Create a subproperty and a subproperty event filter that applies to the created subproperty. Returns: - Callable[[~.CreateSubpropertyRequest], - ~.CreateSubpropertyResponse]: + Callable[[~.ProvisionSubpropertyRequest], + ~.ProvisionSubpropertyResponse]: A function that, when called, will call the underlying RPC on the server. """ @@ -4128,13 +4511,13 @@ def create_subproperty( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_subproperty" not in self._stubs: - self._stubs["create_subproperty"] = self.grpc_channel.unary_unary( - "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSubproperty", - request_serializer=analytics_admin.CreateSubpropertyRequest.serialize, - response_deserializer=analytics_admin.CreateSubpropertyResponse.deserialize, + if "provision_subproperty" not in self._stubs: + self._stubs["provision_subproperty"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ProvisionSubproperty", + request_serializer=analytics_admin.ProvisionSubpropertyRequest.serialize, + response_deserializer=analytics_admin.ProvisionSubpropertyResponse.deserialize, ) - return self._stubs["create_subproperty"] + return self._stubs["provision_subproperty"] @property def create_subproperty_event_filter( diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py index 74e6b73f4ffd..4b19ffcc0cbf 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py @@ -1313,8 +1313,8 @@ def create_conversion_event( ]: r"""Return a callable for the create conversion event method over gRPC. - Creates a conversion event with the specified - attributes. + Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. Returns: Callable[[~.CreateConversionEventRequest], @@ -1343,8 +1343,8 @@ def update_conversion_event( ]: r"""Return a callable for the update conversion event method over gRPC. - Updates a conversion event with the specified - attributes. + Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. Returns: Callable[[~.UpdateConversionEventRequest], @@ -1373,7 +1373,8 @@ def get_conversion_event( ]: r"""Return a callable for the get conversion event method over gRPC. - Retrieve a single conversion event. + Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. Returns: Callable[[~.GetConversionEventRequest], @@ -1401,7 +1402,8 @@ def delete_conversion_event( ]: r"""Return a callable for the delete conversion event method over gRPC. - Deletes a conversion event in a property. + Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. Returns: Callable[[~.DeleteConversionEventRequest], @@ -1430,8 +1432,9 @@ def list_conversion_events( ]: r"""Return a callable for the list conversion events method over gRPC. - Returns a list of conversion events in the specified - parent property. + Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + Returns an empty list if no conversion events are found. Returns: @@ -1452,6 +1455,145 @@ def list_conversion_events( ) return self._stubs["list_conversion_events"] + @property + def create_key_event( + self, + ) -> Callable[ + [analytics_admin.CreateKeyEventRequest], Awaitable[resources.KeyEvent] + ]: + r"""Return a callable for the create key event method over gRPC. + + Creates a Key Event. + + Returns: + Callable[[~.CreateKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_key_event" not in self._stubs: + self._stubs["create_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateKeyEvent", + request_serializer=analytics_admin.CreateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs["create_key_event"] + + @property + def update_key_event( + self, + ) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], Awaitable[resources.KeyEvent] + ]: + r"""Return a callable for the update key event method over gRPC. + + Updates a Key Event. + + Returns: + Callable[[~.UpdateKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_key_event" not in self._stubs: + self._stubs["update_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateKeyEvent", + request_serializer=analytics_admin.UpdateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs["update_key_event"] + + @property + def get_key_event( + self, + ) -> Callable[[analytics_admin.GetKeyEventRequest], Awaitable[resources.KeyEvent]]: + r"""Return a callable for the get key event method over gRPC. + + Retrieve a single Key Event. + + Returns: + Callable[[~.GetKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_key_event" not in self._stubs: + self._stubs["get_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/GetKeyEvent", + request_serializer=analytics_admin.GetKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs["get_key_event"] + + @property + def delete_key_event( + self, + ) -> Callable[[analytics_admin.DeleteKeyEventRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete key event method over gRPC. + + Deletes a Key Event. + + Returns: + Callable[[~.DeleteKeyEventRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_key_event" not in self._stubs: + self._stubs["delete_key_event"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteKeyEvent", + request_serializer=analytics_admin.DeleteKeyEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_key_event"] + + @property + def list_key_events( + self, + ) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + Awaitable[analytics_admin.ListKeyEventsResponse], + ]: + r"""Return a callable for the list key events method over gRPC. + + Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Returns: + Callable[[~.ListKeyEventsRequest], + Awaitable[~.ListKeyEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_key_events" not in self._stubs: + self._stubs["list_key_events"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ListKeyEvents", + request_serializer=analytics_admin.ListKeyEventsRequest.serialize, + response_deserializer=analytics_admin.ListKeyEventsResponse.deserialize, + ) + return self._stubs["list_key_events"] + @property def get_display_video360_advertiser_link( self, @@ -3319,6 +3461,34 @@ def fetch_automated_ga4_configuration_opt_out( ) return self._stubs["fetch_automated_ga4_configuration_opt_out"] + @property + def create_big_query_link( + self, + ) -> Callable[ + [analytics_admin.CreateBigQueryLinkRequest], Awaitable[resources.BigQueryLink] + ]: + r"""Return a callable for the create big query link method over gRPC. + + Creates a BigQueryLink. + + Returns: + Callable[[~.CreateBigQueryLinkRequest], + Awaitable[~.BigQueryLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_big_query_link" not in self._stubs: + self._stubs["create_big_query_link"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateBigQueryLink", + request_serializer=analytics_admin.CreateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs["create_big_query_link"] + @property def get_big_query_link( self, @@ -3376,6 +3546,62 @@ def list_big_query_links( ) return self._stubs["list_big_query_links"] + @property + def delete_big_query_link( + self, + ) -> Callable[ + [analytics_admin.DeleteBigQueryLinkRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete big query link method over gRPC. + + Deletes a BigQueryLink on a property. + + Returns: + Callable[[~.DeleteBigQueryLinkRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_big_query_link" not in self._stubs: + self._stubs["delete_big_query_link"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteBigQueryLink", + request_serializer=analytics_admin.DeleteBigQueryLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_big_query_link"] + + @property + def update_big_query_link( + self, + ) -> Callable[ + [analytics_admin.UpdateBigQueryLinkRequest], Awaitable[resources.BigQueryLink] + ]: + r"""Return a callable for the update big query link method over gRPC. + + Updates a BigQueryLink. + + Returns: + Callable[[~.UpdateBigQueryLinkRequest], + Awaitable[~.BigQueryLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_big_query_link" not in self._stubs: + self._stubs["update_big_query_link"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateBigQueryLink", + request_serializer=analytics_admin.UpdateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs["update_big_query_link"] + @property def get_enhanced_measurement_settings( self, @@ -3826,6 +4052,179 @@ def delete_event_create_rule( ) return self._stubs["delete_event_create_rule"] + @property + def get_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], + Awaitable[event_create_and_edit.EventEditRule], + ]: + r"""Return a callable for the get event edit rule method over gRPC. + + Lookup for a single EventEditRule. + + Returns: + Callable[[~.GetEventEditRuleRequest], + Awaitable[~.EventEditRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_event_edit_rule" not in self._stubs: + self._stubs["get_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEventEditRule", + request_serializer=analytics_admin.GetEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs["get_event_edit_rule"] + + @property + def list_event_edit_rules( + self, + ) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + Awaitable[analytics_admin.ListEventEditRulesResponse], + ]: + r"""Return a callable for the list event edit rules method over gRPC. + + Lists EventEditRules on a web data stream. + + Returns: + Callable[[~.ListEventEditRulesRequest], + Awaitable[~.ListEventEditRulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_event_edit_rules" not in self._stubs: + self._stubs["list_event_edit_rules"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ListEventEditRules", + request_serializer=analytics_admin.ListEventEditRulesRequest.serialize, + response_deserializer=analytics_admin.ListEventEditRulesResponse.deserialize, + ) + return self._stubs["list_event_edit_rules"] + + @property + def create_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + Awaitable[event_create_and_edit.EventEditRule], + ]: + r"""Return a callable for the create event edit rule method over gRPC. + + Creates an EventEditRule. + + Returns: + Callable[[~.CreateEventEditRuleRequest], + Awaitable[~.EventEditRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_event_edit_rule" not in self._stubs: + self._stubs["create_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateEventEditRule", + request_serializer=analytics_admin.CreateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs["create_event_edit_rule"] + + @property + def update_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + Awaitable[event_create_and_edit.EventEditRule], + ]: + r"""Return a callable for the update event edit rule method over gRPC. + + Updates an EventEditRule. + + Returns: + Callable[[~.UpdateEventEditRuleRequest], + Awaitable[~.EventEditRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_event_edit_rule" not in self._stubs: + self._stubs["update_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEventEditRule", + request_serializer=analytics_admin.UpdateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs["update_event_edit_rule"] + + @property + def delete_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.DeleteEventEditRuleRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete event edit rule method over gRPC. + + Deletes an EventEditRule. + + Returns: + Callable[[~.DeleteEventEditRuleRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_event_edit_rule" not in self._stubs: + self._stubs["delete_event_edit_rule"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteEventEditRule", + request_serializer=analytics_admin.DeleteEventEditRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_event_edit_rule"] + + @property + def reorder_event_edit_rules( + self, + ) -> Callable[ + [analytics_admin.ReorderEventEditRulesRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the reorder event edit rules method over gRPC. + + Changes the processing order of event edit rules on + the specified stream. + + Returns: + Callable[[~.ReorderEventEditRulesRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "reorder_event_edit_rules" not in self._stubs: + self._stubs["reorder_event_edit_rules"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ReorderEventEditRules", + request_serializer=analytics_admin.ReorderEventEditRulesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["reorder_event_edit_rules"] + @property def update_data_redaction_settings( self, @@ -4201,20 +4600,20 @@ def delete_rollup_property_source_link( return self._stubs["delete_rollup_property_source_link"] @property - def create_subproperty( + def provision_subproperty( self, ) -> Callable[ - [analytics_admin.CreateSubpropertyRequest], - Awaitable[analytics_admin.CreateSubpropertyResponse], + [analytics_admin.ProvisionSubpropertyRequest], + Awaitable[analytics_admin.ProvisionSubpropertyResponse], ]: - r"""Return a callable for the create subproperty method over gRPC. + r"""Return a callable for the provision subproperty method over gRPC. Create a subproperty and a subproperty event filter that applies to the created subproperty. Returns: - Callable[[~.CreateSubpropertyRequest], - Awaitable[~.CreateSubpropertyResponse]]: + Callable[[~.ProvisionSubpropertyRequest], + Awaitable[~.ProvisionSubpropertyResponse]]: A function that, when called, will call the underlying RPC on the server. """ @@ -4222,13 +4621,13 @@ def create_subproperty( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_subproperty" not in self._stubs: - self._stubs["create_subproperty"] = self.grpc_channel.unary_unary( - "/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSubproperty", - request_serializer=analytics_admin.CreateSubpropertyRequest.serialize, - response_deserializer=analytics_admin.CreateSubpropertyResponse.deserialize, + if "provision_subproperty" not in self._stubs: + self._stubs["provision_subproperty"] = self.grpc_channel.unary_unary( + "/google.analytics.admin.v1alpha.AnalyticsAdminService/ProvisionSubproperty", + request_serializer=analytics_admin.ProvisionSubpropertyRequest.serialize, + response_deserializer=analytics_admin.ProvisionSubpropertyResponse.deserialize, ) - return self._stubs["create_subproperty"] + return self._stubs["provision_subproperty"] @property def create_subproperty_event_filter( @@ -4584,6 +4983,31 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_key_event: gapic_v1.method_async.wrap_method( + self.create_key_event, + default_timeout=None, + client_info=client_info, + ), + self.update_key_event: gapic_v1.method_async.wrap_method( + self.update_key_event, + default_timeout=None, + client_info=client_info, + ), + self.get_key_event: gapic_v1.method_async.wrap_method( + self.get_key_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_key_event: gapic_v1.method_async.wrap_method( + self.delete_key_event, + default_timeout=None, + client_info=client_info, + ), + self.list_key_events: gapic_v1.method_async.wrap_method( + self.list_key_events, + default_timeout=None, + client_info=client_info, + ), self.get_display_video360_advertiser_link: gapic_v1.method_async.wrap_method( self.get_display_video360_advertiser_link, default_timeout=None, @@ -4894,6 +5318,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_big_query_link: gapic_v1.method_async.wrap_method( + self.create_big_query_link, + default_timeout=None, + client_info=client_info, + ), self.get_big_query_link: gapic_v1.method_async.wrap_method( self.get_big_query_link, default_timeout=None, @@ -4904,6 +5333,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.delete_big_query_link: gapic_v1.method_async.wrap_method( + self.delete_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_link: gapic_v1.method_async.wrap_method( + self.update_big_query_link, + default_timeout=None, + client_info=client_info, + ), self.get_enhanced_measurement_settings: gapic_v1.method_async.wrap_method( self.get_enhanced_measurement_settings, default_timeout=60.0, @@ -4979,6 +5418,36 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_event_edit_rule: gapic_v1.method_async.wrap_method( + self.get_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_event_edit_rules: gapic_v1.method_async.wrap_method( + self.list_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_event_edit_rule: gapic_v1.method_async.wrap_method( + self.create_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_event_edit_rule: gapic_v1.method_async.wrap_method( + self.update_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_edit_rule: gapic_v1.method_async.wrap_method( + self.delete_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.reorder_event_edit_rules: gapic_v1.method_async.wrap_method( + self.reorder_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), self.update_data_redaction_settings: gapic_v1.method_async.wrap_method( self.update_data_redaction_settings, default_timeout=None, @@ -5039,8 +5508,8 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - self.create_subproperty: gapic_v1.method_async.wrap_method( - self.create_subproperty, + self.provision_subproperty: gapic_v1.method_async.wrap_method( + self.provision_subproperty, default_timeout=None, client_info=client_info, ), diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py index 6efb1ce3be4f..18bf7bf2a0c4 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py @@ -167,6 +167,14 @@ def post_create_audience(self, response): logging.log(f"Received response: {response}") return response + def pre_create_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_link(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_calculated_metric(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -247,6 +255,14 @@ def post_create_event_create_rule(self, response): logging.log(f"Received response: {response}") return response + def pre_create_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event_edit_rule(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_expanded_data_set(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -271,6 +287,14 @@ def post_create_google_ads_link(self, response): logging.log(f"Received response: {response}") return response + def pre_create_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_key_event(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_measurement_protocol_secret(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -319,14 +343,6 @@ def post_create_sk_ad_network_conversion_value_schema(self, response): logging.log(f"Received response: {response}") return response - def pre_create_subproperty(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_subproperty(self, response): - logging.log(f"Received response: {response}") - return response - def pre_create_subproperty_event_filter(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -347,6 +363,10 @@ def pre_delete_ad_sense_link(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_delete_calculated_metric(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -379,6 +399,10 @@ def pre_delete_event_create_rule(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_delete_expanded_data_set(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -391,6 +415,10 @@ def pre_delete_google_ads_link(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_delete_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_delete_measurement_protocol_secret(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -587,6 +615,14 @@ def post_get_event_create_rule(self, response): logging.log(f"Received response: {response}") return response + def pre_get_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event_edit_rule(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_expanded_data_set(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -611,6 +647,14 @@ def post_get_google_signals_settings(self, response): logging.log(f"Received response: {response}") return response + def pre_get_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_key_event(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_measurement_protocol_secret(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -787,6 +831,14 @@ def post_list_event_create_rules(self, response): logging.log(f"Received response: {response}") return response + def pre_list_event_edit_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_event_edit_rules(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_expanded_data_sets(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -811,6 +863,14 @@ def post_list_google_ads_links(self, response): logging.log(f"Received response: {response}") return response + def pre_list_key_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_key_events(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_measurement_protocol_secrets(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -867,6 +927,18 @@ def post_provision_account_ticket(self, response): logging.log(f"Received response: {response}") return response + def pre_provision_subproperty(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_provision_subproperty(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reorder_event_edit_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_run_access_report(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -923,6 +995,14 @@ def post_update_audience(self, response): logging.log(f"Received response: {response}") return response + def pre_update_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_link(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_calculated_metric(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1011,6 +1091,14 @@ def post_update_event_create_rule(self, response): logging.log(f"Received response: {response}") return response + def pre_update_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event_edit_rule(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_expanded_data_set(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1035,6 +1123,14 @@ def post_update_google_signals_settings(self, response): logging.log(f"Received response: {response}") return response + def pre_update_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_key_event(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_measurement_protocol_secret(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1355,6 +1451,29 @@ def post_create_audience( """ return response + def pre_create_big_query_link( + self, + request: analytics_admin.CreateBigQueryLinkRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.CreateBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_big_query_link( + self, response: resources.BigQueryLink + ) -> resources.BigQueryLink: + """Post-rpc interceptor for create_big_query_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_calculated_metric( self, request: analytics_admin.CreateCalculatedMetricRequest, @@ -1595,6 +1714,29 @@ def post_create_event_create_rule( """ return response + def pre_create_event_edit_rule( + self, + request: analytics_admin.CreateEventEditRuleRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.CreateEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_event_edit_rule( + self, response: event_create_and_edit.EventEditRule + ) -> event_create_and_edit.EventEditRule: + """Post-rpc interceptor for create_event_edit_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_expanded_data_set( self, request: analytics_admin.CreateExpandedDataSetRequest, @@ -1664,6 +1806,27 @@ def post_create_google_ads_link( """ return response + def pre_create_key_event( + self, + request: analytics_admin.CreateKeyEventRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.CreateKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for create_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_measurement_protocol_secret( self, request: analytics_admin.CreateMeasurementProtocolSecretRequest, @@ -1810,29 +1973,6 @@ def post_create_sk_ad_network_conversion_value_schema( """ return response - def pre_create_subproperty( - self, - request: analytics_admin.CreateSubpropertyRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[analytics_admin.CreateSubpropertyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_subproperty - - Override in a subclass to manipulate the request or metadata - before they are sent to the AnalyticsAdminService server. - """ - return request, metadata - - def post_create_subproperty( - self, response: analytics_admin.CreateSubpropertyResponse - ) -> analytics_admin.CreateSubpropertyResponse: - """Post-rpc interceptor for create_subproperty - - Override in a subclass to manipulate the response - after it is returned by the AnalyticsAdminService server but before - it is returned to user code. - """ - return response - def pre_create_subproperty_event_filter( self, request: analytics_admin.CreateSubpropertyEventFilterRequest, @@ -1894,6 +2034,18 @@ def pre_delete_ad_sense_link( """ return request, metadata + def pre_delete_big_query_link( + self, + request: analytics_admin.DeleteBigQueryLinkRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.DeleteBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + def pre_delete_calculated_metric( self, request: analytics_admin.DeleteCalculatedMetricRequest, @@ -2000,6 +2152,18 @@ def pre_delete_event_create_rule( """ return request, metadata + def pre_delete_event_edit_rule( + self, + request: analytics_admin.DeleteEventEditRuleRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.DeleteEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + def pre_delete_expanded_data_set( self, request: analytics_admin.DeleteExpandedDataSetRequest, @@ -2036,6 +2200,18 @@ def pre_delete_google_ads_link( """ return request, metadata + def pre_delete_key_event( + self, + request: analytics_admin.DeleteKeyEventRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.DeleteKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + def pre_delete_measurement_protocol_secret( self, request: analytics_admin.DeleteMeasurementProtocolSecretRequest, @@ -2629,6 +2805,29 @@ def post_get_event_create_rule( """ return response + def pre_get_event_edit_rule( + self, + request: analytics_admin.GetEventEditRuleRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.GetEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_event_edit_rule( + self, response: event_create_and_edit.EventEditRule + ) -> event_create_and_edit.EventEditRule: + """Post-rpc interceptor for get_event_edit_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_expanded_data_set( self, request: analytics_admin.GetExpandedDataSetRequest, @@ -2700,6 +2899,27 @@ def post_get_google_signals_settings( """ return response + def pre_get_key_event( + self, + request: analytics_admin.GetKeyEventRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.GetKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for get_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_measurement_protocol_secret( self, request: analytics_admin.GetMeasurementProtocolSecretRequest, @@ -3220,6 +3440,29 @@ def post_list_event_create_rules( """ return response + def pre_list_event_edit_rules( + self, + request: analytics_admin.ListEventEditRulesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.ListEventEditRulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_event_edit_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_event_edit_rules( + self, response: analytics_admin.ListEventEditRulesResponse + ) -> analytics_admin.ListEventEditRulesResponse: + """Post-rpc interceptor for list_event_edit_rules + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_expanded_data_sets( self, request: analytics_admin.ListExpandedDataSetsRequest, @@ -3289,6 +3532,29 @@ def post_list_google_ads_links( """ return response + def pre_list_key_events( + self, + request: analytics_admin.ListKeyEventsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.ListKeyEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_key_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_key_events( + self, response: analytics_admin.ListKeyEventsResponse + ) -> analytics_admin.ListKeyEventsResponse: + """Post-rpc interceptor for list_key_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_measurement_protocol_secrets( self, request: analytics_admin.ListMeasurementProtocolSecretsRequest, @@ -3461,6 +3727,41 @@ def post_provision_account_ticket( """ return response + def pre_provision_subproperty( + self, + request: analytics_admin.ProvisionSubpropertyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.ProvisionSubpropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for provision_subproperty + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_provision_subproperty( + self, response: analytics_admin.ProvisionSubpropertyResponse + ) -> analytics_admin.ProvisionSubpropertyResponse: + """Post-rpc interceptor for provision_subproperty + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + + def pre_reorder_event_edit_rules( + self, + request: analytics_admin.ReorderEventEditRulesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.ReorderEventEditRulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for reorder_event_edit_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + def pre_run_access_report( self, request: analytics_admin.RunAccessReportRequest, @@ -3627,11 +3928,34 @@ def post_update_audience( """ return response - def pre_update_calculated_metric( + def pre_update_big_query_link( self, - request: analytics_admin.UpdateCalculatedMetricRequest, + request: analytics_admin.UpdateBigQueryLinkRequest, metadata: Sequence[Tuple[str, str]], - ) -> Tuple[ + ) -> Tuple[analytics_admin.UpdateBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_big_query_link( + self, response: resources.BigQueryLink + ) -> resources.BigQueryLink: + """Post-rpc interceptor for update_big_query_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + + def pre_update_calculated_metric( + self, + request: analytics_admin.UpdateCalculatedMetricRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ analytics_admin.UpdateCalculatedMetricRequest, Sequence[Tuple[str, str]] ]: """Pre-rpc interceptor for update_calculated_metric @@ -3892,6 +4216,29 @@ def post_update_event_create_rule( """ return response + def pre_update_event_edit_rule( + self, + request: analytics_admin.UpdateEventEditRuleRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.UpdateEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_event_edit_rule( + self, response: event_create_and_edit.EventEditRule + ) -> event_create_and_edit.EventEditRule: + """Post-rpc interceptor for update_event_edit_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_expanded_data_set( self, request: analytics_admin.UpdateExpandedDataSetRequest, @@ -3963,6 +4310,27 @@ def post_update_google_signals_settings( """ return response + def pre_update_key_event( + self, + request: analytics_admin.UpdateKeyEventRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[analytics_admin.UpdateKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for update_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_measurement_protocol_secret( self, request: analytics_admin.UpdateMeasurementProtocolSecretRequest, @@ -5450,6 +5818,103 @@ def __call__( resp = self._interceptor.post_create_audience(resp) return resp + class _CreateBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateBigQueryLink") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.CreateBigQueryLinkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.BigQueryLink: + r"""Call the create big query link method over HTTP. + + Args: + request (~.analytics_admin.CreateBigQueryLinkRequest): + The request object. Request message for + CreateBigQueryLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=properties/*}/bigQueryLinks", + "body": "bigquery_link", + }, + ] + request, metadata = self._interceptor.pre_create_big_query_link( + request, metadata + ) + pb_request = analytics_admin.CreateBigQueryLinkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.BigQueryLink() + pb_resp = resources.BigQueryLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_link(resp) + return resp + class _CreateCalculatedMetric(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("CreateCalculatedMetric") @@ -6455,6 +6920,115 @@ def __call__( resp = self._interceptor.post_create_event_create_rule(resp) return resp + class _CreateEventEditRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateEventEditRule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.CreateEventEditRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Call the create event edit rule method over HTTP. + + Args: + request (~.analytics_admin.CreateEventEditRuleRequest): + The request object. Request message for + CreateEventEditRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules", + "body": "event_edit_rule", + }, + ] + request, metadata = self._interceptor.pre_create_event_edit_rule( + request, metadata + ) + pb_request = analytics_admin.CreateEventEditRuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = event_create_and_edit.EventEditRule() + pb_resp = event_create_and_edit.EventEditRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event_edit_rule(resp) + return resp + class _CreateExpandedDataSet(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("CreateExpandedDataSet") @@ -6746,9 +7320,9 @@ def __call__( resp = self._interceptor.post_create_google_ads_link(resp) return resp - class _CreateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + class _CreateKeyEvent(AnalyticsAdminServiceRestStub): def __hash__(self): - return hash("CreateMeasurementProtocolSecret") + return hash("CreateKeyEvent") __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @@ -6762,48 +7336,42 @@ def _get_unset_required_fields(cls, message_dict): def __call__( self, - request: analytics_admin.CreateMeasurementProtocolSecretRequest, + request: analytics_admin.CreateKeyEventRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.MeasurementProtocolSecret: - r"""Call the create measurement - protocol secret method over HTTP. + ) -> resources.KeyEvent: + r"""Call the create key event method over HTTP. - Args: - request (~.analytics_admin.CreateMeasurementProtocolSecretRequest): - The request object. Request message for - CreateMeasurementProtocolSecret RPC - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + Args: + request (~.analytics_admin.CreateKeyEventRequest): + The request object. Request message for CreateKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - Returns: - ~.resources.MeasurementProtocolSecret: - A secret value used for sending hits - to Measurement Protocol. + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. """ http_options: List[Dict[str, str]] = [ { "method": "post", - "uri": "/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets", - "body": "measurement_protocol_secret", + "uri": "/v1alpha/{parent=properties/*}/keyEvents", + "body": "key_event", }, ] - ( - request, - metadata, - ) = self._interceptor.pre_create_measurement_protocol_secret( + request, metadata = self._interceptor.pre_create_key_event( request, metadata ) - pb_request = analytics_admin.CreateMeasurementProtocolSecretRequest.pb( - request - ) + pb_request = analytics_admin.CreateKeyEventRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body @@ -6842,11 +7410,114 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.MeasurementProtocolSecret() - pb_resp = resources.MeasurementProtocolSecret.pb(resp) + resp = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_measurement_protocol_secret(resp) + resp = self._interceptor.post_create_key_event(resp) + return resp + + class _CreateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateMeasurementProtocolSecret") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.CreateMeasurementProtocolSecretRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Call the create measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.CreateMeasurementProtocolSecretRequest): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets", + "body": "measurement_protocol_secret", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_create_measurement_protocol_secret( + request, metadata + ) + pb_request = analytics_admin.CreateMeasurementProtocolSecretRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_measurement_protocol_secret(resp) return resp class _CreateProperty(AnalyticsAdminServiceRestStub): @@ -7350,103 +8021,6 @@ def __call__( ) return resp - class _CreateSubproperty(AnalyticsAdminServiceRestStub): - def __hash__(self): - return hash("CreateSubproperty") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return { - k: v - for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() - if k not in message_dict - } - - def __call__( - self, - request: analytics_admin.CreateSubpropertyRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.CreateSubpropertyResponse: - r"""Call the create subproperty method over HTTP. - - Args: - request (~.analytics_admin.CreateSubpropertyRequest): - The request object. Request message for CreateSubproperty - RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.analytics_admin.CreateSubpropertyResponse: - Response message for - CreateSubproperty RPC. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "post", - "uri": "/v1alpha/properties:createSubproperty", - "body": "*", - }, - ] - request, metadata = self._interceptor.pre_create_subproperty( - request, metadata - ) - pb_request = analytics_admin.CreateSubpropertyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - uri = transcoded_request["uri"] - method = transcoded_request["method"] - - # Jsonify the query params - query_params = json.loads( - json_format.MessageToJson( - transcoded_request["query_params"], - use_integers_for_enums=True, - ) - ) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers["Content-Type"] = "application/json" - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = analytics_admin.CreateSubpropertyResponse() - pb_resp = analytics_admin.CreateSubpropertyResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_subproperty(resp) - return resp - class _CreateSubpropertyEventFilter(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("CreateSubpropertyEventFilter") @@ -7775,6 +8349,82 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + class _DeleteBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteBigQueryLink") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.DeleteBigQueryLinkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete big query link method over HTTP. + + Args: + request (~.analytics_admin.DeleteBigQueryLinkRequest): + The request object. Request message for + DeleteBigQueryLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=properties/*/bigQueryLinks/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_link( + request, metadata + ) + pb_request = analytics_admin.DeleteBigQueryLinkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + class _DeleteCalculatedMetric(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("DeleteCalculatedMetric") @@ -8394,9 +9044,85 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - class _DeleteExpandedDataSet(AnalyticsAdminServiceRestStub): + class _DeleteEventEditRule(AnalyticsAdminServiceRestStub): def __hash__(self): - return hash("DeleteExpandedDataSet") + return hash("DeleteEventEditRule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.DeleteEventEditRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete event edit rule method over HTTP. + + Args: + request (~.analytics_admin.DeleteEventEditRuleRequest): + The request object. Request message for + DeleteEventEditRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_event_edit_rule( + request, metadata + ) + pb_request = analytics_admin.DeleteEventEditRuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteExpandedDataSet(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteExpandedDataSet") __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @@ -8622,6 +9348,82 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + class _DeleteKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteKeyEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.DeleteKeyEventRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete key event method over HTTP. + + Args: + request (~.analytics_admin.DeleteKeyEventRequest): + The request object. Request message for DeleteKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=properties/*/keyEvents/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_key_event( + request, metadata + ) + pb_request = analytics_admin.DeleteKeyEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + class _DeleteMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("DeleteMeasurementProtocolSecret") @@ -11061,6 +11863,108 @@ def __call__( resp = self._interceptor.post_get_event_create_rule(resp) return resp + class _GetEventEditRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetEventEditRule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.GetEventEditRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Call the get event edit rule method over HTTP. + + Args: + request (~.analytics_admin.GetEventEditRuleRequest): + The request object. Request message for GetEventEditRule + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}", + }, + ] + request, metadata = self._interceptor.pre_get_event_edit_rule( + request, metadata + ) + pb_request = analytics_admin.GetEventEditRuleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = event_create_and_edit.EventEditRule() + pb_resp = event_create_and_edit.EventEditRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event_edit_rule(resp) + return resp + class _GetExpandedDataSet(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("GetExpandedDataSet") @@ -11334,9 +12238,9 @@ def __call__( resp = self._interceptor.post_get_google_signals_settings(resp) return resp - class _GetMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + class _GetKeyEvent(AnalyticsAdminServiceRestStub): def __hash__(self): - return hash("GetMeasurementProtocolSecret") + return hash("GetKeyEvent") __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @@ -11350,42 +12254,38 @@ def _get_unset_required_fields(cls, message_dict): def __call__( self, - request: analytics_admin.GetMeasurementProtocolSecretRequest, + request: analytics_admin.GetKeyEventRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.MeasurementProtocolSecret: - r"""Call the get measurement protocol - secret method over HTTP. + ) -> resources.KeyEvent: + r"""Call the get key event method over HTTP. - Args: - request (~.analytics_admin.GetMeasurementProtocolSecretRequest): - The request object. Request message for - GetMeasurementProtocolSecret RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + Args: + request (~.analytics_admin.GetKeyEventRequest): + The request object. Request message for GetKeyEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. - Returns: - ~.resources.MeasurementProtocolSecret: - A secret value used for sending hits - to Measurement Protocol. + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. """ http_options: List[Dict[str, str]] = [ { "method": "get", - "uri": "/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}", + "uri": "/v1alpha/{name=properties/*/keyEvents/*}", }, ] - request, metadata = self._interceptor.pre_get_measurement_protocol_secret( - request, metadata - ) - pb_request = analytics_admin.GetMeasurementProtocolSecretRequest.pb(request) + request, metadata = self._interceptor.pre_get_key_event(request, metadata) + pb_request = analytics_admin.GetKeyEventRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) uri = transcoded_request["uri"] @@ -11418,16 +12318,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.MeasurementProtocolSecret() - pb_resp = resources.MeasurementProtocolSecret.pb(resp) + resp = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_measurement_protocol_secret(resp) + resp = self._interceptor.post_get_key_event(resp) return resp - class _GetProperty(AnalyticsAdminServiceRestStub): + class _GetMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): def __hash__(self): - return hash("GetProperty") + return hash("GetMeasurementProtocolSecret") __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @@ -11441,15 +12341,106 @@ def _get_unset_required_fields(cls, message_dict): def __call__( self, - request: analytics_admin.GetPropertyRequest, + request: analytics_admin.GetMeasurementProtocolSecretRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Property: - r"""Call the get property method over HTTP. + ) -> resources.MeasurementProtocolSecret: + r"""Call the get measurement protocol + secret method over HTTP. - Args: + Args: + request (~.analytics_admin.GetMeasurementProtocolSecretRequest): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}", + }, + ] + request, metadata = self._interceptor.pre_get_measurement_protocol_secret( + request, metadata + ) + pb_request = analytics_admin.GetMeasurementProtocolSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_measurement_protocol_secret(resp) + return resp + + class _GetProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetProperty") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.GetPropertyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Property: + r"""Call the get property method over HTTP. + + Args: request (~.analytics_admin.GetPropertyRequest): The request object. Request message for GetProperty RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, @@ -13320,6 +14311,96 @@ def __call__( resp = self._interceptor.post_list_event_create_rules(resp) return resp + class _ListEventEditRules(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListEventEditRules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.ListEventEditRulesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ListEventEditRulesResponse: + r"""Call the list event edit rules method over HTTP. + + Args: + request (~.analytics_admin.ListEventEditRulesRequest): + The request object. Request message for + ListEventEditRules RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListEventEditRulesResponse: + Response message for + ListEventEditRules RPC. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules", + }, + ] + request, metadata = self._interceptor.pre_list_event_edit_rules( + request, metadata + ) + pb_request = analytics_admin.ListEventEditRulesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ListEventEditRulesResponse() + pb_resp = analytics_admin.ListEventEditRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_event_edit_rules(resp) + return resp + class _ListExpandedDataSets(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("ListExpandedDataSets") @@ -13590,6 +14671,93 @@ def __call__( resp = self._interceptor.post_list_google_ads_links(resp) return resp + class _ListKeyEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListKeyEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.ListKeyEventsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ListKeyEventsResponse: + r"""Call the list key events method over HTTP. + + Args: + request (~.analytics_admin.ListKeyEventsRequest): + The request object. Request message for ListKeyEvents RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListKeyEventsResponse: + Response message for ListKeyEvents + RPC. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=properties/*}/keyEvents", + }, + ] + request, metadata = self._interceptor.pre_list_key_events(request, metadata) + pb_request = analytics_admin.ListKeyEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ListKeyEventsResponse() + pb_resp = analytics_admin.ListKeyEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_key_events(resp) + return resp + class _ListMeasurementProtocolSecrets(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("ListMeasurementProtocolSecrets") @@ -14102,16 +15270,198 @@ def __call__( http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1alpha/{parent=properties/*}/subpropertyEventFilters", + "method": "get", + "uri": "/v1alpha/{parent=properties/*}/subpropertyEventFilters", + }, + ] + request, metadata = self._interceptor.pre_list_subproperty_event_filters( + request, metadata + ) + pb_request = analytics_admin.ListSubpropertyEventFiltersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ListSubpropertyEventFiltersResponse() + pb_resp = analytics_admin.ListSubpropertyEventFiltersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_subproperty_event_filters(resp) + return resp + + class _ProvisionAccountTicket(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ProvisionAccountTicket") + + def __call__( + self, + request: analytics_admin.ProvisionAccountTicketRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Call the provision account ticket method over HTTP. + + Args: + request (~.analytics_admin.ProvisionAccountTicketRequest): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/accounts:provisionAccountTicket", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_provision_account_ticket( + request, metadata + ) + pb_request = analytics_admin.ProvisionAccountTicketRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ProvisionAccountTicketResponse() + pb_resp = analytics_admin.ProvisionAccountTicketResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_provision_account_ticket(resp) + return resp + + class _ProvisionSubproperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ProvisionSubproperty") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.ProvisionSubpropertyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionSubpropertyResponse: + r"""Call the provision subproperty method over HTTP. + + Args: + request (~.analytics_admin.ProvisionSubpropertyRequest): + The request object. Request message for CreateSubproperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ProvisionSubpropertyResponse: + Response message for + ProvisionSubproperty RPC. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/properties:provisionSubproperty", + "body": "*", }, ] - request, metadata = self._interceptor.pre_list_subproperty_event_filters( + request, metadata = self._interceptor.pre_provision_subproperty( request, metadata ) - pb_request = analytics_admin.ListSubpropertyEventFiltersRequest.pb(request) + pb_request = analytics_admin.ProvisionSubpropertyRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) uri = transcoded_request["uri"] method = transcoded_request["method"] @@ -14134,6 +15484,7 @@ def __call__( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -14142,55 +15493,59 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = analytics_admin.ListSubpropertyEventFiltersResponse() - pb_resp = analytics_admin.ListSubpropertyEventFiltersResponse.pb(resp) + resp = analytics_admin.ProvisionSubpropertyResponse() + pb_resp = analytics_admin.ProvisionSubpropertyResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_subproperty_event_filters(resp) + resp = self._interceptor.post_provision_subproperty(resp) return resp - class _ProvisionAccountTicket(AnalyticsAdminServiceRestStub): + class _ReorderEventEditRules(AnalyticsAdminServiceRestStub): def __hash__(self): - return hash("ProvisionAccountTicket") + return hash("ReorderEventEditRules") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } def __call__( self, - request: analytics_admin.ProvisionAccountTicketRequest, + request: analytics_admin.ReorderEventEditRulesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> analytics_admin.ProvisionAccountTicketResponse: - r"""Call the provision account ticket method over HTTP. + ): + r"""Call the reorder event edit rules method over HTTP. Args: - request (~.analytics_admin.ProvisionAccountTicketRequest): + request (~.analytics_admin.ReorderEventEditRulesRequest): The request object. Request message for - ProvisionAccountTicket RPC. + ReorderEventEditRules RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. - - Returns: - ~.analytics_admin.ProvisionAccountTicketResponse: - Response message for - ProvisionAccountTicket RPC. - """ http_options: List[Dict[str, str]] = [ { "method": "post", - "uri": "/v1alpha/accounts:provisionAccountTicket", + "uri": "/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules:reorder", "body": "*", }, ] - request, metadata = self._interceptor.pre_provision_account_ticket( + request, metadata = self._interceptor.pre_reorder_event_edit_rules( request, metadata ) - pb_request = analytics_admin.ProvisionAccountTicketRequest.pb(request) + pb_request = analytics_admin.ReorderEventEditRulesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body @@ -14208,6 +15563,7 @@ def __call__( use_integers_for_enums=True, ) ) + query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" @@ -14227,14 +15583,6 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - # Return the response - resp = analytics_admin.ProvisionAccountTicketResponse() - pb_resp = analytics_admin.ProvisionAccountTicketResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_provision_account_ticket(resp) - return resp - class _RunAccessReport(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("RunAccessReport") @@ -14928,6 +16276,105 @@ def __call__( resp = self._interceptor.post_update_audience(resp) return resp + class _UpdateBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateBigQueryLink") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.UpdateBigQueryLinkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.BigQueryLink: + r"""Call the update big query link method over HTTP. + + Args: + request (~.analytics_admin.UpdateBigQueryLinkRequest): + The request object. Request message for + UpdateBigQueryLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{bigquery_link.name=properties/*/bigQueryLinks/*}", + "body": "bigquery_link", + }, + ] + request, metadata = self._interceptor.pre_update_big_query_link( + request, metadata + ) + pb_request = analytics_admin.UpdateBigQueryLinkRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.BigQueryLink() + pb_resp = resources.BigQueryLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_link(resp) + return resp + class _UpdateCalculatedMetric(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("UpdateCalculatedMetric") @@ -15849,41 +17296,152 @@ def __call__( r"""Call the update enhanced measurement settings method over HTTP. - Args: - request (~.analytics_admin.UpdateEnhancedMeasurementSettingsRequest): - The request object. Request message for - UpdateEnhancedMeasurementSettings RPC. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + Args: + request (~.analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + The request object. Request message for + UpdateEnhancedMeasurementSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{enhanced_measurement_settings.name=properties/*/dataStreams/*/enhancedMeasurementSettings}", + "body": "enhanced_measurement_settings", + }, + ] + ( + request, + metadata, + ) = self._interceptor.pre_update_enhanced_measurement_settings( + request, metadata + ) + pb_request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.EnhancedMeasurementSettings() + pb_resp = resources.EnhancedMeasurementSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_enhanced_measurement_settings(resp) + return resp + + class _UpdateEventCreateRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateEventCreateRule") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.UpdateEventCreateRuleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Call the update event create rule method over HTTP. + + Args: + request (~.analytics_admin.UpdateEventCreateRuleRequest): + The request object. Request message for + UpdateEventCreateRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. - Returns: - ~.resources.EnhancedMeasurementSettings: - Singleton resource under a web - DataStream, configuring measurement of - additional site interactions and - content. + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. """ http_options: List[Dict[str, str]] = [ { "method": "patch", - "uri": "/v1alpha/{enhanced_measurement_settings.name=properties/*/dataStreams/*/enhancedMeasurementSettings}", - "body": "enhanced_measurement_settings", + "uri": "/v1alpha/{event_create_rule.name=properties/*/dataStreams/*/eventCreateRules/*}", + "body": "event_create_rule", }, ] - ( - request, - metadata, - ) = self._interceptor.pre_update_enhanced_measurement_settings( + request, metadata = self._interceptor.pre_update_event_create_rule( request, metadata ) - pb_request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.pb( - request - ) + pb_request = analytics_admin.UpdateEventCreateRuleRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body @@ -15922,16 +17480,16 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = resources.EnhancedMeasurementSettings() - pb_resp = resources.EnhancedMeasurementSettings.pb(resp) + resp = event_create_and_edit.EventCreateRule() + pb_resp = event_create_and_edit.EventCreateRule.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_enhanced_measurement_settings(resp) + resp = self._interceptor.post_update_event_create_rule(resp) return resp - class _UpdateEventCreateRule(AnalyticsAdminServiceRestStub): + class _UpdateEventEditRule(AnalyticsAdminServiceRestStub): def __hash__(self): - return hash("UpdateEventCreateRule") + return hash("UpdateEventEditRule") __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "updateMask": {}, @@ -15947,18 +17505,18 @@ def _get_unset_required_fields(cls, message_dict): def __call__( self, - request: analytics_admin.UpdateEventCreateRuleRequest, + request: analytics_admin.UpdateEventEditRuleRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> event_create_and_edit.EventCreateRule: - r"""Call the update event create rule method over HTTP. + ) -> event_create_and_edit.EventEditRule: + r"""Call the update event edit rule method over HTTP. Args: - request (~.analytics_admin.UpdateEventCreateRuleRequest): + request (~.analytics_admin.UpdateEventEditRuleRequest): The request object. Request message for - UpdateEventCreateRule RPC. + UpdateEventEditRule RPC. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -15966,35 +17524,35 @@ def __call__( sent along with the request as metadata. Returns: - ~.event_create_and_edit.EventCreateRule: - An Event Create Rule defines - conditions that will trigger the - creation of an entirely new event based - upon matched criteria of a source event. - Additional mutations of the parameters - from the source event can be defined. - - Unlike Event Edit rules, Event Creation - Rules have no defined order. They will - all be run independently. - - Event Edit and Event Create rules can't - be used to modify an event created from - an Event Create rule. + ~.event_create_and_edit.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. """ http_options: List[Dict[str, str]] = [ { "method": "patch", - "uri": "/v1alpha/{event_create_rule.name=properties/*/dataStreams/*/eventCreateRules/*}", - "body": "event_create_rule", + "uri": "/v1alpha/{event_edit_rule.name=properties/*/dataStreams/*/eventEditRules/*}", + "body": "event_edit_rule", }, ] - request, metadata = self._interceptor.pre_update_event_create_rule( + request, metadata = self._interceptor.pre_update_event_edit_rule( request, metadata ) - pb_request = analytics_admin.UpdateEventCreateRuleRequest.pb(request) + pb_request = analytics_admin.UpdateEventEditRuleRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body @@ -16033,11 +17591,11 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = event_create_and_edit.EventCreateRule() - pb_resp = event_create_and_edit.EventCreateRule.pb(resp) + resp = event_create_and_edit.EventEditRule() + pb_resp = event_create_and_edit.EventEditRule.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_event_create_rule(resp) + resp = self._interceptor.post_update_event_edit_rule(resp) return resp class _UpdateExpandedDataSet(AnalyticsAdminServiceRestStub): @@ -16338,6 +17896,105 @@ def __call__( resp = self._interceptor.post_update_google_signals_settings(resp) return resp + class _UpdateKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateKeyEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: analytics_admin.UpdateKeyEventRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyEvent: + r"""Call the update key event method over HTTP. + + Args: + request (~.analytics_admin.UpdateKeyEventRequest): + The request object. Request message for UpdateKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{key_event.name=properties/*/keyEvents/*}", + "body": "key_event", + }, + ] + request, metadata = self._interceptor.pre_update_key_event( + request, metadata + ) + pb_request = analytics_admin.UpdateKeyEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_key_event(resp) + return resp + class _UpdateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): def __hash__(self): return hash("UpdateMeasurementProtocolSecret") @@ -16973,6 +18630,14 @@ def create_audience( # In C++ this would require a dynamic_cast return self._CreateAudience(self._session, self._host, self._interceptor) # type: ignore + @property + def create_big_query_link( + self, + ) -> Callable[[analytics_admin.CreateBigQueryLinkRequest], resources.BigQueryLink]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + @property def create_calculated_metric( self, @@ -17073,6 +18738,17 @@ def create_event_create_rule( # In C++ this would require a dynamic_cast return self._CreateEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + @property + def create_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + event_create_and_edit.EventEditRule, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEventEditRule(self._session, self._host, self._interceptor) # type: ignore + @property def create_expanded_data_set( self, @@ -17102,6 +18778,14 @@ def create_google_ads_link( # In C++ this would require a dynamic_cast return self._CreateGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + @property + def create_key_event( + self, + ) -> Callable[[analytics_admin.CreateKeyEventRequest], resources.KeyEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateKeyEvent(self._session, self._host, self._interceptor) # type: ignore + @property def create_measurement_protocol_secret( self, @@ -17164,17 +18848,6 @@ def create_sk_ad_network_conversion_value_schema( # In C++ this would require a dynamic_cast return self._CreateSKAdNetworkConversionValueSchema(self._session, self._host, self._interceptor) # type: ignore - @property - def create_subproperty( - self, - ) -> Callable[ - [analytics_admin.CreateSubpropertyRequest], - analytics_admin.CreateSubpropertyResponse, - ]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateSubproperty(self._session, self._host, self._interceptor) # type: ignore - @property def create_subproperty_event_filter( self, @@ -17210,6 +18883,14 @@ def delete_ad_sense_link( # In C++ this would require a dynamic_cast return self._DeleteAdSenseLink(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_big_query_link( + self, + ) -> Callable[[analytics_admin.DeleteBigQueryLinkRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + @property def delete_calculated_metric( self, @@ -17279,6 +18960,14 @@ def delete_event_create_rule( # In C++ this would require a dynamic_cast return self._DeleteEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_event_edit_rule( + self, + ) -> Callable[[analytics_admin.DeleteEventEditRuleRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEventEditRule(self._session, self._host, self._interceptor) # type: ignore + @property def delete_expanded_data_set( self, @@ -17303,6 +18992,14 @@ def delete_google_ads_link( # In C++ this would require a dynamic_cast return self._DeleteGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_key_event( + self, + ) -> Callable[[analytics_admin.DeleteKeyEventRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteKeyEvent(self._session, self._host, self._interceptor) # type: ignore + @property def delete_measurement_protocol_secret( self, @@ -17561,6 +19258,16 @@ def get_event_create_rule( # In C++ this would require a dynamic_cast return self._GetEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + @property + def get_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], event_create_and_edit.EventEditRule + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEventEditRule(self._session, self._host, self._interceptor) # type: ignore + @property def get_expanded_data_set( self, @@ -17590,6 +19297,14 @@ def get_google_signals_settings( # In C++ this would require a dynamic_cast return self._GetGoogleSignalsSettings(self._session, self._host, self._interceptor) # type: ignore + @property + def get_key_event( + self, + ) -> Callable[[analytics_admin.GetKeyEventRequest], resources.KeyEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetKeyEvent(self._session, self._host, self._interceptor) # type: ignore + @property def get_measurement_protocol_secret( self, @@ -17826,6 +19541,17 @@ def list_event_create_rules( # In C++ this would require a dynamic_cast return self._ListEventCreateRules(self._session, self._host, self._interceptor) # type: ignore + @property + def list_event_edit_rules( + self, + ) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + analytics_admin.ListEventEditRulesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEventEditRules(self._session, self._host, self._interceptor) # type: ignore + @property def list_expanded_data_sets( self, @@ -17859,6 +19585,16 @@ def list_google_ads_links( # In C++ this would require a dynamic_cast return self._ListGoogleAdsLinks(self._session, self._host, self._interceptor) # type: ignore + @property + def list_key_events( + self, + ) -> Callable[ + [analytics_admin.ListKeyEventsRequest], analytics_admin.ListKeyEventsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListKeyEvents(self._session, self._host, self._interceptor) # type: ignore + @property def list_measurement_protocol_secrets( self, @@ -17935,6 +19671,25 @@ def provision_account_ticket( # In C++ this would require a dynamic_cast return self._ProvisionAccountTicket(self._session, self._host, self._interceptor) # type: ignore + @property + def provision_subproperty( + self, + ) -> Callable[ + [analytics_admin.ProvisionSubpropertyRequest], + analytics_admin.ProvisionSubpropertyResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ProvisionSubproperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def reorder_event_edit_rules( + self, + ) -> Callable[[analytics_admin.ReorderEventEditRulesRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReorderEventEditRules(self._session, self._host, self._interceptor) # type: ignore + @property def run_access_report( self, @@ -18005,6 +19760,14 @@ def update_audience( # In C++ this would require a dynamic_cast return self._UpdateAudience(self._session, self._host, self._interceptor) # type: ignore + @property + def update_big_query_link( + self, + ) -> Callable[[analytics_admin.UpdateBigQueryLinkRequest], resources.BigQueryLink]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + @property def update_calculated_metric( self, @@ -18116,6 +19879,17 @@ def update_event_create_rule( # In C++ this would require a dynamic_cast return self._UpdateEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + @property + def update_event_edit_rule( + self, + ) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + event_create_and_edit.EventEditRule, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEventEditRule(self._session, self._host, self._interceptor) # type: ignore + @property def update_expanded_data_set( self, @@ -18148,6 +19922,14 @@ def update_google_signals_settings( # In C++ this would require a dynamic_cast return self._UpdateGoogleSignalsSettings(self._session, self._host, self._interceptor) # type: ignore + @property + def update_key_event( + self, + ) -> Callable[[analytics_admin.UpdateKeyEventRequest], resources.KeyEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateKeyEvent(self._session, self._host, self._interceptor) # type: ignore + @property def update_measurement_protocol_secret( self, diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/__init__.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/__init__.py index aa5f7ff96098..5248eee2b7f0 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/__init__.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/__init__.py @@ -53,6 +53,7 @@ CreateAccessBindingRequest, CreateAdSenseLinkRequest, CreateAudienceRequest, + CreateBigQueryLinkRequest, CreateCalculatedMetricRequest, CreateChannelGroupRequest, CreateConnectedSiteTagRequest, @@ -64,9 +65,11 @@ CreateDisplayVideo360AdvertiserLinkProposalRequest, CreateDisplayVideo360AdvertiserLinkRequest, CreateEventCreateRuleRequest, + CreateEventEditRuleRequest, CreateExpandedDataSetRequest, CreateFirebaseLinkRequest, CreateGoogleAdsLinkRequest, + CreateKeyEventRequest, CreateMeasurementProtocolSecretRequest, CreatePropertyRequest, CreateRollupPropertyRequest, @@ -75,11 +78,10 @@ CreateSearchAds360LinkRequest, CreateSKAdNetworkConversionValueSchemaRequest, CreateSubpropertyEventFilterRequest, - CreateSubpropertyRequest, - CreateSubpropertyResponse, DeleteAccessBindingRequest, DeleteAccountRequest, DeleteAdSenseLinkRequest, + DeleteBigQueryLinkRequest, DeleteCalculatedMetricRequest, DeleteChannelGroupRequest, DeleteConnectedSiteTagRequest, @@ -88,9 +90,11 @@ DeleteDisplayVideo360AdvertiserLinkProposalRequest, DeleteDisplayVideo360AdvertiserLinkRequest, DeleteEventCreateRuleRequest, + DeleteEventEditRuleRequest, DeleteExpandedDataSetRequest, DeleteFirebaseLinkRequest, DeleteGoogleAdsLinkRequest, + DeleteKeyEventRequest, DeleteMeasurementProtocolSecretRequest, DeletePropertyRequest, DeleteRollupPropertySourceLinkRequest, @@ -120,9 +124,11 @@ GetDisplayVideo360AdvertiserLinkRequest, GetEnhancedMeasurementSettingsRequest, GetEventCreateRuleRequest, + GetEventEditRuleRequest, GetExpandedDataSetRequest, GetGlobalSiteTagRequest, GetGoogleSignalsSettingsRequest, + GetKeyEventRequest, GetMeasurementProtocolSecretRequest, GetPropertyRequest, GetRollupPropertySourceLinkRequest, @@ -161,12 +167,16 @@ ListDisplayVideo360AdvertiserLinksResponse, ListEventCreateRulesRequest, ListEventCreateRulesResponse, + ListEventEditRulesRequest, + ListEventEditRulesResponse, ListExpandedDataSetsRequest, ListExpandedDataSetsResponse, ListFirebaseLinksRequest, ListFirebaseLinksResponse, ListGoogleAdsLinksRequest, ListGoogleAdsLinksResponse, + ListKeyEventsRequest, + ListKeyEventsResponse, ListMeasurementProtocolSecretsRequest, ListMeasurementProtocolSecretsResponse, ListPropertiesRequest, @@ -181,6 +191,9 @@ ListSubpropertyEventFiltersResponse, ProvisionAccountTicketRequest, ProvisionAccountTicketResponse, + ProvisionSubpropertyRequest, + ProvisionSubpropertyResponse, + ReorderEventEditRulesRequest, RunAccessReportRequest, RunAccessReportResponse, SearchChangeHistoryEventsRequest, @@ -191,6 +204,7 @@ UpdateAccountRequest, UpdateAttributionSettingsRequest, UpdateAudienceRequest, + UpdateBigQueryLinkRequest, UpdateCalculatedMetricRequest, UpdateChannelGroupRequest, UpdateConversionEventRequest, @@ -202,9 +216,11 @@ UpdateDisplayVideo360AdvertiserLinkRequest, UpdateEnhancedMeasurementSettingsRequest, UpdateEventCreateRuleRequest, + UpdateEventEditRuleRequest, UpdateExpandedDataSetRequest, UpdateGoogleAdsLinkRequest, UpdateGoogleSignalsSettingsRequest, + UpdateKeyEventRequest, UpdateMeasurementProtocolSecretRequest, UpdatePropertyRequest, UpdateSearchAds360LinkRequest, @@ -230,7 +246,12 @@ ChannelGroupFilterExpressionList, GroupingRule, ) -from .event_create_and_edit import EventCreateRule, MatchingCondition, ParameterMutation +from .event_create_and_edit import ( + EventCreateRule, + EventEditRule, + MatchingCondition, + ParameterMutation, +) from .expanded_data_set import ( ExpandedDataSet, ExpandedDataSetFilter, @@ -271,6 +292,7 @@ GoogleSignalsSettings, GoogleSignalsState, IndustryCategory, + KeyEvent, LinkProposalInitiatingProduct, LinkProposalState, LinkProposalStatusDetails, @@ -330,6 +352,7 @@ "CreateAccessBindingRequest", "CreateAdSenseLinkRequest", "CreateAudienceRequest", + "CreateBigQueryLinkRequest", "CreateCalculatedMetricRequest", "CreateChannelGroupRequest", "CreateConnectedSiteTagRequest", @@ -341,9 +364,11 @@ "CreateDisplayVideo360AdvertiserLinkProposalRequest", "CreateDisplayVideo360AdvertiserLinkRequest", "CreateEventCreateRuleRequest", + "CreateEventEditRuleRequest", "CreateExpandedDataSetRequest", "CreateFirebaseLinkRequest", "CreateGoogleAdsLinkRequest", + "CreateKeyEventRequest", "CreateMeasurementProtocolSecretRequest", "CreatePropertyRequest", "CreateRollupPropertyRequest", @@ -352,11 +377,10 @@ "CreateSearchAds360LinkRequest", "CreateSKAdNetworkConversionValueSchemaRequest", "CreateSubpropertyEventFilterRequest", - "CreateSubpropertyRequest", - "CreateSubpropertyResponse", "DeleteAccessBindingRequest", "DeleteAccountRequest", "DeleteAdSenseLinkRequest", + "DeleteBigQueryLinkRequest", "DeleteCalculatedMetricRequest", "DeleteChannelGroupRequest", "DeleteConnectedSiteTagRequest", @@ -365,9 +389,11 @@ "DeleteDisplayVideo360AdvertiserLinkProposalRequest", "DeleteDisplayVideo360AdvertiserLinkRequest", "DeleteEventCreateRuleRequest", + "DeleteEventEditRuleRequest", "DeleteExpandedDataSetRequest", "DeleteFirebaseLinkRequest", "DeleteGoogleAdsLinkRequest", + "DeleteKeyEventRequest", "DeleteMeasurementProtocolSecretRequest", "DeletePropertyRequest", "DeleteRollupPropertySourceLinkRequest", @@ -397,9 +423,11 @@ "GetDisplayVideo360AdvertiserLinkRequest", "GetEnhancedMeasurementSettingsRequest", "GetEventCreateRuleRequest", + "GetEventEditRuleRequest", "GetExpandedDataSetRequest", "GetGlobalSiteTagRequest", "GetGoogleSignalsSettingsRequest", + "GetKeyEventRequest", "GetMeasurementProtocolSecretRequest", "GetPropertyRequest", "GetRollupPropertySourceLinkRequest", @@ -438,12 +466,16 @@ "ListDisplayVideo360AdvertiserLinksResponse", "ListEventCreateRulesRequest", "ListEventCreateRulesResponse", + "ListEventEditRulesRequest", + "ListEventEditRulesResponse", "ListExpandedDataSetsRequest", "ListExpandedDataSetsResponse", "ListFirebaseLinksRequest", "ListFirebaseLinksResponse", "ListGoogleAdsLinksRequest", "ListGoogleAdsLinksResponse", + "ListKeyEventsRequest", + "ListKeyEventsResponse", "ListMeasurementProtocolSecretsRequest", "ListMeasurementProtocolSecretsResponse", "ListPropertiesRequest", @@ -458,6 +490,9 @@ "ListSubpropertyEventFiltersResponse", "ProvisionAccountTicketRequest", "ProvisionAccountTicketResponse", + "ProvisionSubpropertyRequest", + "ProvisionSubpropertyResponse", + "ReorderEventEditRulesRequest", "RunAccessReportRequest", "RunAccessReportResponse", "SearchChangeHistoryEventsRequest", @@ -468,6 +503,7 @@ "UpdateAccountRequest", "UpdateAttributionSettingsRequest", "UpdateAudienceRequest", + "UpdateBigQueryLinkRequest", "UpdateCalculatedMetricRequest", "UpdateChannelGroupRequest", "UpdateConversionEventRequest", @@ -479,9 +515,11 @@ "UpdateDisplayVideo360AdvertiserLinkRequest", "UpdateEnhancedMeasurementSettingsRequest", "UpdateEventCreateRuleRequest", + "UpdateEventEditRuleRequest", "UpdateExpandedDataSetRequest", "UpdateGoogleAdsLinkRequest", "UpdateGoogleSignalsSettingsRequest", + "UpdateKeyEventRequest", "UpdateMeasurementProtocolSecretRequest", "UpdatePropertyRequest", "UpdateSearchAds360LinkRequest", @@ -503,6 +541,7 @@ "ChannelGroupFilterExpressionList", "GroupingRule", "EventCreateRule", + "EventEditRule", "MatchingCondition", "ParameterMutation", "ExpandedDataSet", @@ -535,6 +574,7 @@ "GlobalSiteTag", "GoogleAdsLink", "GoogleSignalsSettings", + "KeyEvent", "LinkProposalStatusDetails", "MeasurementProtocolSecret", "PostbackWindow", diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/analytics_admin.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/analytics_admin.py index ea94cd377823..6178315944ed 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/analytics_admin.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/analytics_admin.py @@ -88,6 +88,12 @@ "DeleteConversionEventRequest", "ListConversionEventsRequest", "ListConversionEventsResponse", + "CreateKeyEventRequest", + "UpdateKeyEventRequest", + "GetKeyEventRequest", + "DeleteKeyEventRequest", + "ListKeyEventsRequest", + "ListKeyEventsResponse", "GetDisplayVideo360AdvertiserLinkRequest", "ListDisplayVideo360AdvertiserLinksRequest", "ListDisplayVideo360AdvertiserLinksResponse", @@ -171,9 +177,12 @@ "SetAutomatedGa4ConfigurationOptOutResponse", "FetchAutomatedGa4ConfigurationOptOutRequest", "FetchAutomatedGa4ConfigurationOptOutResponse", + "CreateBigQueryLinkRequest", "GetBigQueryLinkRequest", "ListBigQueryLinksRequest", "ListBigQueryLinksResponse", + "UpdateBigQueryLinkRequest", + "DeleteBigQueryLinkRequest", "GetEnhancedMeasurementSettingsRequest", "UpdateEnhancedMeasurementSettingsRequest", "GetDataRedactionSettingsRequest", @@ -196,6 +205,13 @@ "GetEventCreateRuleRequest", "ListEventCreateRulesRequest", "ListEventCreateRulesResponse", + "CreateEventEditRuleRequest", + "UpdateEventEditRuleRequest", + "DeleteEventEditRuleRequest", + "GetEventEditRuleRequest", + "ListEventEditRulesRequest", + "ListEventEditRulesResponse", + "ReorderEventEditRulesRequest", "CreateRollupPropertyRequest", "CreateRollupPropertyResponse", "GetRollupPropertySourceLinkRequest", @@ -203,8 +219,8 @@ "ListRollupPropertySourceLinksResponse", "CreateRollupPropertySourceLinkRequest", "DeleteRollupPropertySourceLinkRequest", - "CreateSubpropertyRequest", - "CreateSubpropertyResponse", + "ProvisionSubpropertyRequest", + "ProvisionSubpropertyResponse", "CreateSubpropertyEventFilterRequest", "GetSubpropertyEventFilterRequest", "ListSubpropertyEventFiltersRequest", @@ -768,8 +784,9 @@ class CreateFirebaseLinkRequest(proto.Message): Attributes: parent (str): - Required. Format: properties/{property_id} Example: - properties/1234 + Required. Format: properties/{property_id} + + Example: ``properties/1234`` firebase_link (google.analytics.admin_v1alpha.types.FirebaseLink): Required. The Firebase link to create. """ @@ -792,7 +809,8 @@ class DeleteFirebaseLinkRequest(proto.Message): name (str): Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} - Example: properties/1234/firebaseLinks/5678 + + Example: ``properties/1234/firebaseLinks/5678`` """ name: str = proto.Field( @@ -806,8 +824,9 @@ class ListFirebaseLinksRequest(proto.Message): Attributes: parent (str): - Required. Format: properties/{property_id} Example: - properties/1234 + Required. Format: properties/{property_id} + + Example: ``properties/1234`` page_size (int): The maximum number of resources to return. The service may return fewer than this value, @@ -874,7 +893,8 @@ class GetGlobalSiteTagRequest(proto.Message): Required. The name of the site tag to lookup. Note that site tags are singletons and do not have unique IDs. Format: properties/{property_id}/dataStreams/{stream_id}/globalSiteTag - Example: "properties/123/dataStreams/456/globalSiteTag". + + Example: ``properties/123/dataStreams/456/globalSiteTag`` """ name: str = proto.Field( @@ -1011,9 +1031,10 @@ class GetDataSharingSettingsRequest(proto.Message): Attributes: name (str): - Required. The name of the settings to lookup. - Format: accounts/{account}/dataSharingSettings - Example: "accounts/1000/dataSharingSettings". + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` """ name: str = proto.Field( @@ -1121,15 +1142,16 @@ class SearchChangeHistoryEventsRequest(proto.Message): Attributes: account (str): - Required. The account resource for which to - return change history resources. Format: - accounts/{account} Example: "accounts/100". + Required. The account resource for which to return change + history resources. Format: accounts/{account} + + Example: ``accounts/100`` property (str): - Optional. Resource name for a child property. - If set, only return changes made to this - property or its child resources. Format: - properties/{propertyId} - Example: "properties/100". + Optional. Resource name for a child property. If set, only + return changes made to this property or its child resources. + Format: properties/{propertyId} + + Example: ``properties/100`` resource_type (MutableSequence[google.analytics.admin_v1alpha.types.ChangeHistoryResourceType]): Optional. If set, only return changes if they are for a resource that matches at least one of @@ -1726,6 +1748,148 @@ def raw_page(self): ) +class CreateKeyEventRequest(proto.Message): + r"""Request message for CreateKeyEvent RPC + + Attributes: + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to create. + parent (str): + Required. The resource name of the parent + property where this Key Event will be created. + Format: properties/123 + """ + + key_event: resources.KeyEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateKeyEventRequest(proto.Message): + r"""Request message for UpdateKeyEvent RPC + + Attributes: + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + key_event: resources.KeyEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetKeyEventRequest(proto.Message): + r"""Request message for GetKeyEvent RPC + + Attributes: + name (str): + Required. The resource name of the Key Event to retrieve. + Format: properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteKeyEventRequest(proto.Message): + r"""Request message for DeleteKeyEvent RPC + + Attributes: + name (str): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListKeyEventsRequest(proto.Message): + r"""Request message for ListKeyEvents RPC + + Attributes: + parent (str): + Required. The resource name of the parent + property. Example: 'properties/123' + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListKeyEvents`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListKeyEvents`` must match the call that provided the page + token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListKeyEventsResponse(proto.Message): + r"""Response message for ListKeyEvents RPC. + + Attributes: + key_events (MutableSequence[google.analytics.admin_v1alpha.types.KeyEvent]): + The requested Key Events + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + key_events: MutableSequence[resources.KeyEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + class GetDisplayVideo360AdvertiserLinkRequest(proto.Message): r"""Request message for GetDisplayVideo360AdvertiserLink RPC. @@ -2486,7 +2650,7 @@ class CreateCalculatedMetricRequest(proto.Message): resource name. This value should be 1-80 characters and valid characters - are `[a-zA-Z0-9_]`, no spaces allowed. calculated_metric_id + are /[a-zA-Z0-9_]/, no spaces allowed. calculated_metric_id must be unique between all calculated metrics under a property. The calculated_metric_id is used when referencing this calculated metric from external APIs, for example, @@ -3660,6 +3824,27 @@ class FetchAutomatedGa4ConfigurationOptOutResponse(proto.Message): ) +class CreateBigQueryLinkRequest(proto.Message): + r"""Request message for CreateBigQueryLink RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The BigQueryLink to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + bigquery_link: resources.BigQueryLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.BigQueryLink, + ) + + class GetBigQueryLinkRequest(proto.Message): r"""Request message for GetBigQueryLink RPC. @@ -3740,6 +3925,48 @@ def raw_page(self): ) +class UpdateBigQueryLinkRequest(proto.Message): + r"""Request message for UpdateBigQueryLink RPC. + + Attributes: + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + bigquery_link: resources.BigQueryLink = proto.Field( + proto.MESSAGE, + number=1, + message=resources.BigQueryLink, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteBigQueryLinkRequest(proto.Message): + r"""Request message for DeleteBigQueryLink RPC. + + Attributes: + name (str): + Required. The BigQueryLink to delete. + Example format: + properties/1234/bigQueryLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class GetEnhancedMeasurementSettingsRequest(proto.Message): r"""Request message for GetEnhancedMeasurementSettings RPC. @@ -4221,6 +4448,176 @@ def raw_page(self): ) +class CreateEventEditRuleRequest(proto.Message): + r"""Request message for CreateEventEditRule RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_edit_rule: event_create_and_edit.EventEditRule = proto.Field( + proto.MESSAGE, + number=2, + message=event_create_and_edit.EventEditRule, + ) + + +class UpdateEventEditRuleRequest(proto.Message): + r"""Request message for UpdateEventEditRule RPC. + + Attributes: + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to update. The resource's + ``name`` field is used to identify the EventEditRule to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + event_edit_rule: event_create_and_edit.EventEditRule = proto.Field( + proto.MESSAGE, + number=1, + message=event_create_and_edit.EventEditRule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEventEditRuleRequest(proto.Message): + r"""Request message for DeleteEventEditRule RPC. + + Attributes: + name (str): + Required. Example format: + properties/123/dataStreams/456/eventEditRules/789 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEventEditRuleRequest(proto.Message): + r"""Request message for GetEventEditRule RPC. + + Attributes: + name (str): + Required. The name of the EventEditRule to + get. Example format: + properties/123/dataStreams/456/eventEditRules/789 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEventEditRulesRequest(proto.Message): + r"""Request message for ListEventEditRules RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + page_size (int): + Optional. The maximum number of resources to + return. If unspecified, at most 50 resources + will be returned. The maximum value is 200 + (higher values will be coerced to the maximum). + page_token (str): + Optional. A page token, received from a previous + ``ListEventEditRules`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListEventEditRules`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEventEditRulesResponse(proto.Message): + r"""Response message for ListEventEditRules RPC. + + Attributes: + event_edit_rules (MutableSequence[google.analytics.admin_v1alpha.types.EventEditRule]): + List of EventEditRules. These will be ordered + stably, but in an arbitrary order. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + event_edit_rules: MutableSequence[ + event_create_and_edit.EventEditRule + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=event_create_and_edit.EventEditRule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ReorderEventEditRulesRequest(proto.Message): + r"""Request message for ReorderEventEditRules RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + event_edit_rules (MutableSequence[str]): + Required. EventEditRule resource names for + the specified data stream, in the needed + processing order. All EventEditRules for the + stream must be present in the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_edit_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class CreateRollupPropertyRequest(proto.Message): r"""Request message for CreateRollupProperty RPC. @@ -4390,14 +4787,10 @@ class DeleteRollupPropertySourceLinkRequest(proto.Message): ) -class CreateSubpropertyRequest(proto.Message): +class ProvisionSubpropertyRequest(proto.Message): r"""Request message for CreateSubproperty RPC. Attributes: - parent (str): - Required. The ordinary property for which to create a - subproperty. Format: properties/property_id Example: - properties/123 subproperty (google.analytics.admin_v1alpha.types.Property): Required. The subproperty to create. subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): @@ -4405,10 +4798,6 @@ class CreateSubpropertyRequest(proto.Message): create on an ordinary property. """ - parent: str = proto.Field( - proto.STRING, - number=1, - ) subproperty: resources.Property = proto.Field( proto.MESSAGE, number=2, @@ -4423,8 +4812,8 @@ class CreateSubpropertyRequest(proto.Message): ) -class CreateSubpropertyResponse(proto.Message): - r"""Response message for CreateSubproperty RPC. +class ProvisionSubpropertyResponse(proto.Message): + r"""Response message for ProvisionSubproperty RPC. Attributes: subproperty (google.analytics.admin_v1alpha.types.Property): diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/audience.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/audience.py index b1f3905dd649..fad860d1132e 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/audience.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/audience.py @@ -18,6 +18,7 @@ from typing import MutableMapping, MutableSequence from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -712,6 +713,9 @@ class Audience(proto.Message): Required. Immutable. Unordered list. Filter clauses that define the Audience. All clauses will be AND’ed together. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the Audience was + created. """ class AudienceExclusionDurationMode(proto.Enum): @@ -767,6 +771,11 @@ class AudienceExclusionDurationMode(proto.Enum): number=8, message="AudienceFilterClause", ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/channel_group.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/channel_group.py index 66494ae6dbf7..43d2c51386fb 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/channel_group.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/channel_group.py @@ -268,6 +268,15 @@ class ChannelGroup(proto.Message): is the Default Channel Group predefined by Google Analytics. Display name and grouping rules cannot be updated for this channel group. + primary (bool): + Optional. If true, this channel group will be used as the + default channel group for reports. Only one channel group + can be set as ``primary`` at any time. If the ``primary`` + field gets set on a channel group, it will get unset on the + previous primary channel group. + + The Google Analytics predefined channel group is the primary + by default. """ name: str = proto.Field( @@ -291,6 +300,10 @@ class ChannelGroup(proto.Message): proto.BOOL, number=5, ) + primary: bool = proto.Field( + proto.BOOL, + number=6, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/event_create_and_edit.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/event_create_and_edit.py index 6a4701ae4a98..c47f879d4ae0 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/event_create_and_edit.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/event_create_and_edit.py @@ -24,6 +24,7 @@ manifest={ "ParameterMutation", "EventCreateRule", + "EventEditRule", "MatchingCondition", }, ) @@ -130,6 +131,71 @@ class EventCreateRule(proto.Message): ) +class EventEditRule(proto.Message): + r"""An Event Edit Rule defines conditions that will trigger the + creation of an entirely new event based upon matched criteria of + a source event. Additional mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit Rules are applied in their + defined order. + + Event Edit rules can't be used to modify an event created from + an Event Create rule. + + Attributes: + name (str): + Identifier. Resource name for this EventEditRule resource. + Format: + properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule} + display_name (str): + Required. The display name of this event edit + rule. Maximum of 255 characters. + event_conditions (MutableSequence[google.analytics.admin_v1alpha.types.MatchingCondition]): + Required. Conditions on the source event must + match for this rule to be applied. Must have at + least one condition, and can have up to 10 max. + parameter_mutations (MutableSequence[google.analytics.admin_v1alpha.types.ParameterMutation]): + Required. Parameter mutations define + parameter behavior on the new event, and are + applied in order. A maximum of 20 mutations can + be applied. + processing_order (int): + Output only. The order for which this rule + will be processed. Rules with an order value + lower than this will be processed before this + rule, rules with an order value higher than this + will be processed after this rule. New event + edit rules will be assigned an order value at + the end of the order. + + This value does not apply to event create rules. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + event_conditions: MutableSequence["MatchingCondition"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="MatchingCondition", + ) + parameter_mutations: MutableSequence["ParameterMutation"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="ParameterMutation", + ) + processing_order: int = proto.Field( + proto.INT64, + number=5, + ) + + class MatchingCondition(proto.Message): r"""Defines a condition for when an Event Edit or Event Creation rule applies to an event. diff --git a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/resources.py b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/resources.py index 914ae9dc615d..dee751dedb76 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/resources.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1alpha/types/resources.py @@ -63,6 +63,7 @@ "SearchAds360Link", "LinkProposalStatusDetails", "ConversionEvent", + "KeyEvent", "GoogleSignalsSettings", "CustomDimension", "CustomMetric", @@ -268,6 +269,8 @@ class ChangeHistoryResourceType(proto.Enum): ExpandedDataSet resource CHANNEL_GROUP (22): ChannelGroup resource + BIGQUERY_LINK (23): + BigQuery link resource ENHANCED_MEASUREMENT_SETTINGS (24): EnhancedMeasurementSettings resource DATA_REDACTION_SETTINGS (25): @@ -301,6 +304,7 @@ class ChangeHistoryResourceType(proto.Enum): ATTRIBUTION_SETTINGS = 20 EXPANDED_DATA_SET = 21 CHANNEL_GROUP = 22 + BIGQUERY_LINK = 23 ENHANCED_MEASUREMENT_SETTINGS = 24 DATA_REDACTION_SETTINGS = 25 SKADNETWORK_CONVERSION_VALUE_SCHEMA = 26 @@ -474,6 +478,11 @@ class Account(proto.Message): is soft-deleted or not. Deleted accounts are excluded from List results unless specifically requested. + gmp_organization (str): + Output only. The URI for a Google Marketing Platform + organization resource. Only set when this account is + connected to a GMP organization. Format: + marketingplatformadmin.googleapis.com/organizations/{org_id} """ name: str = proto.Field( @@ -502,6 +511,10 @@ class Account(proto.Message): proto.BOOL, number=6, ) + gmp_organization: str = proto.Field( + proto.STRING, + number=7, + ) class Property(proto.Message): @@ -2147,6 +2160,119 @@ class DefaultConversionValue(proto.Message): ) +class KeyEvent(proto.Message): + r"""A key event in a Google Analytics property. + + Attributes: + name (str): + Output only. Resource name of this key event. Format: + properties/{property}/keyEvents/{key_event} + event_name (str): + Immutable. The event name for this key event. + Examples: 'click', 'purchase' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this key event was + created in the property. + deletable (bool): + Output only. If set to true, this event can + be deleted. + custom (bool): + Output only. If set to true, this key event + refers to a custom event. If set to false, this + key event refers to a default event in GA. + Default events typically have special meaning in + GA. Default events are usually created for you + by the GA system, but in some cases can be + created by property admins. Custom events count + towards the maximum number of custom key events + that may be created per property. + counting_method (google.analytics.admin_v1alpha.types.KeyEvent.CountingMethod): + Required. The method by which Key Events will + be counted across multiple events within a + session. + default_value (google.analytics.admin_v1alpha.types.KeyEvent.DefaultValue): + Optional. Defines a default value/currency + for a key event. + """ + + class CountingMethod(proto.Enum): + r"""The method by which Key Events will be counted across + multiple events within a session. + + Values: + COUNTING_METHOD_UNSPECIFIED (0): + Counting method not specified. + ONCE_PER_EVENT (1): + Each Event instance is considered a Key + Event. + ONCE_PER_SESSION (2): + An Event instance is considered a Key Event + at most once per session per user. + """ + COUNTING_METHOD_UNSPECIFIED = 0 + ONCE_PER_EVENT = 1 + ONCE_PER_SESSION = 2 + + class DefaultValue(proto.Message): + r"""Defines a default value/currency for a key event. + + Attributes: + numeric_value (float): + Required. This will be used to populate the "value" + parameter for all occurrences of this Key Event (specified + by event_name) where that parameter is unset. + currency_code (str): + Required. When an occurrence of this Key Event (specified by + event_name) has no set currency this currency will be + applied as the default. Must be in ISO 4217 currency code + format. + + See https://en.wikipedia.org/wiki/ISO_4217 for more + information. + """ + + numeric_value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + currency_code: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + deletable: bool = proto.Field( + proto.BOOL, + number=4, + ) + custom: bool = proto.Field( + proto.BOOL, + number=5, + ) + counting_method: CountingMethod = proto.Field( + proto.ENUM, + number=6, + enum=CountingMethod, + ) + default_value: DefaultValue = proto.Field( + proto.MESSAGE, + number=7, + message=DefaultValue, + ) + + class GoogleSignalsSettings(proto.Message): r"""Settings values for Google Signals. This is a singleton resource. @@ -2852,6 +2978,12 @@ class BigQueryLink(proto.Message): excluded_events (MutableSequence[str]): The list of event names that will be excluded from exports. + dataset_location (str): + Required. Immutable. The geographic location + where the created BigQuery dataset should + reside. See + https://cloud.google.com/bigquery/docs/locations + for supported locations. """ name: str = proto.Field( @@ -2891,6 +3023,10 @@ class BigQueryLink(proto.Message): proto.STRING, number=8, ) + dataset_location: str = proto.Field( + proto.STRING, + number=10, + ) class EnhancedMeasurementSettings(proto.Message): diff --git a/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py b/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py index f56358e27bf1..558c8aab67c5 100644 --- a/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py +++ b/packages/google-analytics-admin/google/analytics/admin_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.22.9" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json b/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json index 4d71e33bddd5..5b91879363a3 100644 --- a/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json +++ b/packages/google-analytics-admin/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-admin", - "version": "0.22.9" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-analytics-admin/scripts/fixup_admin_v1alpha_keywords.py b/packages/google-analytics-admin/scripts/fixup_admin_v1alpha_keywords.py index 3a2bd3eeaf1a..f64a22e0acb1 100644 --- a/packages/google-analytics-admin/scripts/fixup_admin_v1alpha_keywords.py +++ b/packages/google-analytics-admin/scripts/fixup_admin_v1alpha_keywords.py @@ -52,6 +52,7 @@ class adminCallTransformer(cst.CSTTransformer): 'create_access_binding': ('parent', 'access_binding', ), 'create_ad_sense_link': ('parent', 'adsense_link', ), 'create_audience': ('parent', 'audience', ), + 'create_big_query_link': ('parent', 'bigquery_link', ), 'create_calculated_metric': ('parent', 'calculated_metric_id', 'calculated_metric', ), 'create_channel_group': ('parent', 'channel_group', ), 'create_connected_site_tag': ('connected_site_tag', 'property', ), @@ -62,20 +63,22 @@ class adminCallTransformer(cst.CSTTransformer): 'create_display_video360_advertiser_link': ('parent', 'display_video_360_advertiser_link', ), 'create_display_video360_advertiser_link_proposal': ('parent', 'display_video_360_advertiser_link_proposal', ), 'create_event_create_rule': ('parent', 'event_create_rule', ), + 'create_event_edit_rule': ('parent', 'event_edit_rule', ), 'create_expanded_data_set': ('parent', 'expanded_data_set', ), 'create_firebase_link': ('parent', 'firebase_link', ), 'create_google_ads_link': ('parent', 'google_ads_link', ), + 'create_key_event': ('key_event', 'parent', ), 'create_measurement_protocol_secret': ('parent', 'measurement_protocol_secret', ), 'create_property': ('property', ), 'create_rollup_property': ('rollup_property', 'source_properties', ), 'create_rollup_property_source_link': ('parent', 'rollup_property_source_link', ), 'create_search_ads360_link': ('parent', 'search_ads_360_link', ), 'create_sk_ad_network_conversion_value_schema': ('parent', 'skadnetwork_conversion_value_schema', ), - 'create_subproperty': ('parent', 'subproperty', 'subproperty_event_filter', ), 'create_subproperty_event_filter': ('parent', 'subproperty_event_filter', ), 'delete_access_binding': ('name', ), 'delete_account': ('name', ), 'delete_ad_sense_link': ('name', ), + 'delete_big_query_link': ('name', ), 'delete_calculated_metric': ('name', ), 'delete_channel_group': ('name', ), 'delete_connected_site_tag': ('property', 'tag_id', ), @@ -84,9 +87,11 @@ class adminCallTransformer(cst.CSTTransformer): 'delete_display_video360_advertiser_link': ('name', ), 'delete_display_video360_advertiser_link_proposal': ('name', ), 'delete_event_create_rule': ('name', ), + 'delete_event_edit_rule': ('name', ), 'delete_expanded_data_set': ('name', ), 'delete_firebase_link': ('name', ), 'delete_google_ads_link': ('name', ), + 'delete_key_event': ('name', ), 'delete_measurement_protocol_secret': ('name', ), 'delete_property': ('name', ), 'delete_rollup_property_source_link': ('name', ), @@ -114,9 +119,11 @@ class adminCallTransformer(cst.CSTTransformer): 'get_display_video360_advertiser_link_proposal': ('name', ), 'get_enhanced_measurement_settings': ('name', ), 'get_event_create_rule': ('name', ), + 'get_event_edit_rule': ('name', ), 'get_expanded_data_set': ('name', ), 'get_global_site_tag': ('name', ), 'get_google_signals_settings': ('name', ), + 'get_key_event': ('name', ), 'get_measurement_protocol_secret': ('name', ), 'get_property': ('name', ), 'get_rollup_property_source_link': ('name', ), @@ -139,9 +146,11 @@ class adminCallTransformer(cst.CSTTransformer): 'list_display_video360_advertiser_link_proposals': ('parent', 'page_size', 'page_token', ), 'list_display_video360_advertiser_links': ('parent', 'page_size', 'page_token', ), 'list_event_create_rules': ('parent', 'page_size', 'page_token', ), + 'list_event_edit_rules': ('parent', 'page_size', 'page_token', ), 'list_expanded_data_sets': ('parent', 'page_size', 'page_token', ), 'list_firebase_links': ('parent', 'page_size', 'page_token', ), 'list_google_ads_links': ('parent', 'page_size', 'page_token', ), + 'list_key_events': ('parent', 'page_size', 'page_token', ), 'list_measurement_protocol_secrets': ('parent', 'page_size', 'page_token', ), 'list_properties': ('filter', 'page_size', 'page_token', 'show_deleted', ), 'list_rollup_property_source_links': ('parent', 'page_size', 'page_token', ), @@ -149,6 +158,8 @@ class adminCallTransformer(cst.CSTTransformer): 'list_sk_ad_network_conversion_value_schemas': ('parent', 'page_size', 'page_token', ), 'list_subproperty_event_filters': ('parent', 'page_size', 'page_token', ), 'provision_account_ticket': ('account', 'redirect_uri', ), + 'provision_subproperty': ('subproperty', 'subproperty_event_filter', ), + 'reorder_event_edit_rules': ('parent', 'event_edit_rules', ), 'run_access_report': ('entity', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'time_zone', 'order_bys', 'return_entity_quota', 'include_all_users', 'expand_groups', ), 'search_change_history_events': ('account', 'property', 'resource_type', 'action', 'actor_email', 'earliest_change_time', 'latest_change_time', 'page_size', 'page_token', ), 'set_automated_ga4_configuration_opt_out': ('property', 'opt_out', ), @@ -156,6 +167,7 @@ class adminCallTransformer(cst.CSTTransformer): 'update_account': ('account', 'update_mask', ), 'update_attribution_settings': ('attribution_settings', 'update_mask', ), 'update_audience': ('audience', 'update_mask', ), + 'update_big_query_link': ('bigquery_link', 'update_mask', ), 'update_calculated_metric': ('calculated_metric', 'update_mask', ), 'update_channel_group': ('channel_group', 'update_mask', ), 'update_conversion_event': ('conversion_event', 'update_mask', ), @@ -167,9 +179,11 @@ class adminCallTransformer(cst.CSTTransformer): 'update_display_video360_advertiser_link': ('update_mask', 'display_video_360_advertiser_link', ), 'update_enhanced_measurement_settings': ('enhanced_measurement_settings', 'update_mask', ), 'update_event_create_rule': ('event_create_rule', 'update_mask', ), + 'update_event_edit_rule': ('event_edit_rule', 'update_mask', ), 'update_expanded_data_set': ('expanded_data_set', 'update_mask', ), 'update_google_ads_link': ('update_mask', 'google_ads_link', ), 'update_google_signals_settings': ('google_signals_settings', 'update_mask', ), + 'update_key_event': ('key_event', 'update_mask', ), 'update_measurement_protocol_secret': ('measurement_protocol_secret', 'update_mask', ), 'update_property': ('property', 'update_mask', ), 'update_search_ads360_link': ('update_mask', 'search_ads_360_link', ), diff --git a/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py b/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py index b81a44f5eed5..c117f372bc0b 100644 --- a/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py +++ b/packages/google-analytics-admin/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py @@ -1235,6 +1235,7 @@ def test_get_account(request_type, transport: str = "grpc"): display_name="display_name_value", region_code="region_code_value", deleted=True, + gmp_organization="gmp_organization_value", ) response = client.get_account(request) @@ -1250,6 +1251,7 @@ def test_get_account(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.region_code == "region_code_value" assert response.deleted is True + assert response.gmp_organization == "gmp_organization_value" def test_get_account_empty_call(): @@ -1352,6 +1354,7 @@ async def test_get_account_empty_call_async(): display_name="display_name_value", region_code="region_code_value", deleted=True, + gmp_organization="gmp_organization_value", ) ) response = await client.get_account() @@ -1423,6 +1426,7 @@ async def test_get_account_async( display_name="display_name_value", region_code="region_code_value", deleted=True, + gmp_organization="gmp_organization_value", ) ) response = await client.get_account(request) @@ -1439,6 +1443,7 @@ async def test_get_account_async( assert response.display_name == "display_name_value" assert response.region_code == "region_code_value" assert response.deleted is True + assert response.gmp_organization == "gmp_organization_value" @pytest.mark.asyncio @@ -2370,6 +2375,7 @@ def test_update_account(request_type, transport: str = "grpc"): display_name="display_name_value", region_code="region_code_value", deleted=True, + gmp_organization="gmp_organization_value", ) response = client.update_account(request) @@ -2385,6 +2391,7 @@ def test_update_account(request_type, transport: str = "grpc"): assert response.display_name == "display_name_value" assert response.region_code == "region_code_value" assert response.deleted is True + assert response.gmp_organization == "gmp_organization_value" def test_update_account_empty_call(): @@ -2483,6 +2490,7 @@ async def test_update_account_empty_call_async(): display_name="display_name_value", region_code="region_code_value", deleted=True, + gmp_organization="gmp_organization_value", ) ) response = await client.update_account() @@ -2554,6 +2562,7 @@ async def test_update_account_async( display_name="display_name_value", region_code="region_code_value", deleted=True, + gmp_organization="gmp_organization_value", ) ) response = await client.update_account(request) @@ -2570,6 +2579,7 @@ async def test_update_account_async( assert response.display_name == "display_name_value" assert response.region_code == "region_code_value" assert response.deleted is True + assert response.gmp_organization == "gmp_organization_value" @pytest.mark.asyncio @@ -17568,11 +17578,11 @@ async def test_list_conversion_events_async_pages(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, + analytics_admin.CreateKeyEventRequest, dict, ], ) -def test_get_display_video360_advertiser_link(request_type, transport: str = "grpc"): +def test_create_key_event(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17583,31 +17593,33 @@ def test_get_display_video360_advertiser_link(request_type, transport: str = "gr request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink( + call.return_value = resources.KeyEvent( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) - response = client.get_display_video360_advertiser_link(request) + response = client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CreateKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert isinstance(response, resources.KeyEvent) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT -def test_get_display_video360_advertiser_link_empty_call(): +def test_create_key_event_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -17616,19 +17628,17 @@ def test_get_display_video360_advertiser_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_display_video360_advertiser_link() + client.create_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.CreateKeyEventRequest() -def test_get_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): +def test_create_key_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -17639,26 +17649,24 @@ def test_get_display_video360_advertiser_link_non_empty_request_with_auto_popula # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest( - name="name_value", + request = analytics_admin.CreateKeyEventRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_display_video360_advertiser_link(request=request) + client.create_key_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest( - name="name_value", + assert args[0] == analytics_admin.CreateKeyEventRequest( + parent="parent_value", ) -def test_get_display_video360_advertiser_link_use_cached_wrapped_rpc(): +def test_create_key_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -17672,10 +17680,7 @@ def test_get_display_video360_advertiser_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_display_video360_advertiser_link - in client._transport._wrapped_methods - ) + assert client._transport.create_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -17683,15 +17688,15 @@ def test_get_display_video360_advertiser_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_display_video360_advertiser_link + client._transport.create_key_event ] = mock_rpc request = {} - client.get_display_video360_advertiser_link(request) + client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_display_video360_advertiser_link(request) + client.create_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17699,7 +17704,7 @@ def test_get_display_video360_advertiser_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_empty_call_async(): +async def test_create_key_event_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -17708,25 +17713,25 @@ async def test_get_display_video360_advertiser_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink( + resources.KeyEvent( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) ) - response = await client.get_display_video360_advertiser_link() + response = await client.create_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.CreateKeyEventRequest() @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_async_use_cached_wrapped_rpc( +async def test_create_key_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -17743,23 +17748,23 @@ async def test_get_display_video360_advertiser_link_async_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._client._transport.get_display_video360_advertiser_link + client._client._transport.create_key_event in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_display_video360_advertiser_link + client._client._transport.create_key_event ] = mock_object request = {} - await client.get_display_video360_advertiser_link(request) + await client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_display_video360_advertiser_link(request) + await client.create_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17767,9 +17772,8 @@ async def test_get_display_video360_advertiser_link_async_use_cached_wrapped_rpc @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, +async def test_create_key_event_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.CreateKeyEventRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17781,54 +17785,54 @@ async def test_get_display_video360_advertiser_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink( + resources.KeyEvent( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) ) - response = await client.get_display_video360_advertiser_link(request) + response = await client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CreateKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert isinstance(response, resources.KeyEvent) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_async_from_dict(): - await test_get_display_video360_advertiser_link_async(request_type=dict) +async def test_create_key_event_async_from_dict(): + await test_create_key_event_async(request_type=dict) -def test_get_display_video360_advertiser_link_field_headers(): +def test_create_key_event_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CreateKeyEventRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value = resources.DisplayVideo360AdvertiserLink() - client.get_display_video360_advertiser_link(request) + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: + call.return_value = resources.KeyEvent() + client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17839,30 +17843,26 @@ def test_get_display_video360_advertiser_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_field_headers_async(): +async def test_create_key_event_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CreateKeyEventRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink() - ) - await client.get_display_video360_advertiser_link(request) + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -17873,37 +17873,39 @@ async def test_get_display_video360_advertiser_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_display_video360_advertiser_link_flattened(): +def test_create_key_event_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink() + call.return_value = resources.KeyEvent() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_display_video360_advertiser_link( - name="name_value", + client.create_key_event( + parent="parent_value", + key_event=resources.KeyEvent(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].key_event + mock_val = resources.KeyEvent(name="name_value") assert arg == mock_val -def test_get_display_video360_advertiser_link_flattened_error(): +def test_create_key_event_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -17911,45 +17913,46 @@ def test_get_display_video360_advertiser_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_display_video360_advertiser_link( - analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), - name="name_value", + client.create_key_event( + analytics_admin.CreateKeyEventRequest(), + parent="parent_value", + key_event=resources.KeyEvent(name="name_value"), ) @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_flattened_async(): +async def test_create_key_event_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink() + call.return_value = resources.KeyEvent() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_display_video360_advertiser_link( - name="name_value", + response = await client.create_key_event( + parent="parent_value", + key_event=resources.KeyEvent(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].key_event + mock_val = resources.KeyEvent(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_flattened_error_async(): +async def test_create_key_event_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -17957,20 +17960,21 @@ async def test_get_display_video360_advertiser_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_display_video360_advertiser_link( - analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), - name="name_value", + await client.create_key_event( + analytics_admin.CreateKeyEventRequest(), + parent="parent_value", + key_event=resources.KeyEvent(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + analytics_admin.UpdateKeyEventRequest, dict, ], ) -def test_list_display_video360_advertiser_links(request_type, transport: str = "grpc"): +def test_update_key_event(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17981,27 +17985,33 @@ def test_list_display_video360_advertiser_links(request_type, transport: str = " request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - next_page_token="next_page_token_value", + call.return_value = resources.KeyEvent( + name="name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) - response = client.list_display_video360_advertiser_links(request) + response = client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + request = analytics_admin.UpdateKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.KeyEvent) + assert response.name == "name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT -def test_list_display_video360_advertiser_links_empty_call(): +def test_update_key_event_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -18010,19 +18020,17 @@ def test_list_display_video360_advertiser_links_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_display_video360_advertiser_links() + client.update_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + assert args[0] == analytics_admin.UpdateKeyEventRequest() -def test_list_display_video360_advertiser_links_non_empty_request_with_auto_populated_field(): +def test_update_key_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -18033,28 +18041,20 @@ def test_list_display_video360_advertiser_links_non_empty_request_with_auto_popu # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( - parent="parent_value", - page_token="page_token_value", - ) + request = analytics_admin.UpdateKeyEventRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_display_video360_advertiser_links(request=request) + client.update_key_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( - parent="parent_value", - page_token="page_token_value", - ) + assert args[0] == analytics_admin.UpdateKeyEventRequest() -def test_list_display_video360_advertiser_links_use_cached_wrapped_rpc(): +def test_update_key_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18068,10 +18068,7 @@ def test_list_display_video360_advertiser_links_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_display_video360_advertiser_links - in client._transport._wrapped_methods - ) + assert client._transport.update_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -18079,15 +18076,15 @@ def test_list_display_video360_advertiser_links_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_display_video360_advertiser_links + client._transport.update_key_event ] = mock_rpc request = {} - client.list_display_video360_advertiser_links(request) + client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_display_video360_advertiser_links(request) + client.update_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18095,7 +18092,7 @@ def test_list_display_video360_advertiser_links_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_empty_call_async(): +async def test_update_key_event_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -18104,23 +18101,25 @@ async def test_list_display_video360_advertiser_links_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - next_page_token="next_page_token_value", + resources.KeyEvent( + name="name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) ) - response = await client.list_display_video360_advertiser_links() + response = await client.update_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + assert args[0] == analytics_admin.UpdateKeyEventRequest() @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_async_use_cached_wrapped_rpc( +async def test_update_key_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -18137,23 +18136,23 @@ async def test_list_display_video360_advertiser_links_async_use_cached_wrapped_r # Ensure method has been cached assert ( - client._client._transport.list_display_video360_advertiser_links + client._client._transport.update_key_event in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_display_video360_advertiser_links + client._client._transport.update_key_event ] = mock_object request = {} - await client.list_display_video360_advertiser_links(request) + await client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_display_video360_advertiser_links(request) + await client.update_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18161,9 +18160,8 @@ async def test_list_display_video360_advertiser_links_async_use_cached_wrapped_r @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, +async def test_update_key_event_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.UpdateKeyEventRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18175,50 +18173,54 @@ async def test_list_display_video360_advertiser_links_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - next_page_token="next_page_token_value", + resources.KeyEvent( + name="name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) ) - response = await client.list_display_video360_advertiser_links(request) + response = await client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + request = analytics_admin.UpdateKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.KeyEvent) + assert response.name == "name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_async_from_dict(): - await test_list_display_video360_advertiser_links_async(request_type=dict) +async def test_update_key_event_async_from_dict(): + await test_update_key_event_async(request_type=dict) -def test_list_display_video360_advertiser_links_field_headers(): +def test_update_key_event_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + request = analytics_admin.UpdateKeyEventRequest() - request.parent = "parent_value" + request.key_event.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: - call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() - client.list_display_video360_advertiser_links(request) + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: + call.return_value = resources.KeyEvent() + client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -18229,30 +18231,26 @@ def test_list_display_video360_advertiser_links_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "key_event.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_field_headers_async(): +async def test_update_key_event_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + request = analytics_admin.UpdateKeyEventRequest() - request.parent = "parent_value" + request.key_event.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() - ) - await client.list_display_video360_advertiser_links(request) + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -18263,37 +18261,39 @@ async def test_list_display_video360_advertiser_links_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "key_event.name=name_value", ) in kw["metadata"] -def test_list_display_video360_advertiser_links_flattened(): +def test_update_key_event_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + call.return_value = resources.KeyEvent() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_display_video360_advertiser_links( - parent="parent_value", + client.update_key_event( + key_event=resources.KeyEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].key_event + mock_val = resources.KeyEvent(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_list_display_video360_advertiser_links_flattened_error(): +def test_update_key_event_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18301,45 +18301,46 @@ def test_list_display_video360_advertiser_links_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_display_video360_advertiser_links( - analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), - parent="parent_value", + client.update_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_flattened_async(): +async def test_update_key_event_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + call.return_value = resources.KeyEvent() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_display_video360_advertiser_links( - parent="parent_value", + response = await client.update_key_event( + key_event=resources.KeyEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].key_event + mock_val = resources.KeyEvent(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_flattened_error_async(): +async def test_update_key_event_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18347,382 +18348,168 @@ async def test_list_display_video360_advertiser_links_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_display_video360_advertiser_links( - analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), - parent="parent_value", + await client.update_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_display_video360_advertiser_links_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetKeyEventRequest, + dict, + ], +) +def test_get_key_event(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[], - next_page_token="def", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - ), - RuntimeError, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_display_video360_advertiser_links( - request={}, retry=retry, timeout=timeout + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name="name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) + response = client.get_key_event(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetKeyEventRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, resources.DisplayVideo360AdvertiserLink) for i in results - ) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == "name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT -def test_list_display_video360_advertiser_links_pages(transport_name: str = "grpc"): +def test_get_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[], - next_page_token="def", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.list_display_video360_advertiser_links(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.get_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest() -@pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_async_pager(): - client = AnalyticsAdminServiceAsyncClient( +def test_get_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.GetKeyEventRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[], - next_page_token="def", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - async_pager = await client.list_display_video360_advertiser_links( - request={}, + client.get_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest( + name="name_value", ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - assert len(responses) == 6 - assert all( - isinstance(i, resources.DisplayVideo360AdvertiserLink) for i in responses + +def test_get_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.get_key_event] = mock_rpc + request = {} + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 @pytest.mark.asyncio -async def test_list_display_video360_advertiser_links_async_pages(): +async def test_get_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_display_video360_advertiser_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[], - next_page_token="def", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_display_video360_advertiser_links(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, - dict, - ], -) -def test_create_display_video360_advertiser_link(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - ) - response = client.create_display_video360_advertiser_link(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" - - -def test_create_display_video360_advertiser_link_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_display_video360_advertiser_link() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() - - -def test_create_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( - parent="parent_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_display_video360_advertiser_link(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( - parent="parent_value", - ) - - -def test_create_display_video360_advertiser_link_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_display_video360_advertiser_link - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_display_video360_advertiser_link - ] = mock_rpc - request = {} - client.create_display_video360_advertiser_link(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_display_video360_advertiser_link(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink( + resources.KeyEvent( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) ) - response = await client.create_display_video360_advertiser_link() + response = await client.get_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.GetKeyEventRequest() @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_async_use_cached_wrapped_rpc( +async def test_get_key_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -18739,23 +18526,23 @@ async def test_create_display_video360_advertiser_link_async_use_cached_wrapped_ # Ensure method has been cached assert ( - client._client._transport.create_display_video360_advertiser_link + client._client._transport.get_key_event in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_display_video360_advertiser_link + client._client._transport.get_key_event ] = mock_object request = {} - await client.create_display_video360_advertiser_link(request) + await client.get_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_display_video360_advertiser_link(request) + await client.get_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18763,9 +18550,8 @@ async def test_create_display_video360_advertiser_link_async_use_cached_wrapped_ @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, +async def test_get_key_event_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetKeyEventRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18777,54 +18563,54 @@ async def test_create_display_video360_advertiser_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink( + resources.KeyEvent( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) ) - response = await client.create_display_video360_advertiser_link(request) + response = await client.get_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.GetKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert isinstance(response, resources.KeyEvent) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_async_from_dict(): - await test_create_display_video360_advertiser_link_async(request_type=dict) +async def test_get_key_event_async_from_dict(): + await test_get_key_event_async(request_type=dict) -def test_create_display_video360_advertiser_link_field_headers(): +def test_get_key_event_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.GetKeyEventRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value = resources.DisplayVideo360AdvertiserLink() - client.create_display_video360_advertiser_link(request) + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: + call.return_value = resources.KeyEvent() + client.get_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -18835,30 +18621,26 @@ def test_create_display_video360_advertiser_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_field_headers_async(): +async def test_get_key_event_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.GetKeyEventRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink() - ) - await client.create_display_video360_advertiser_link(request) + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.get_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -18869,43 +18651,35 @@ async def test_create_display_video360_advertiser_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_display_video360_advertiser_link_flattened(): +def test_get_key_event_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink() + call.return_value = resources.KeyEvent() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_display_video360_advertiser_link( - parent="parent_value", - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), + client.get_key_event( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].display_video_360_advertiser_link - mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_display_video360_advertiser_link_flattened_error(): +def test_get_key_event_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18913,54 +18687,41 @@ def test_create_display_video360_advertiser_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_display_video360_advertiser_link( - analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), - parent="parent_value", - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), + client.get_key_event( + analytics_admin.GetKeyEventRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_flattened_async(): +async def test_get_key_event_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_key_event), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink() + call.return_value = resources.KeyEvent() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_display_video360_advertiser_link( - parent="parent_value", - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), + response = await client.get_key_event( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].display_video_360_advertiser_link - mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_flattened_error_async(): +async def test_get_key_event_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18968,23 +18729,20 @@ async def test_create_display_video360_advertiser_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_display_video360_advertiser_link( - analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), - parent="parent_value", - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), + await client.get_key_event( + analytics_admin.GetKeyEventRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, + analytics_admin.DeleteKeyEventRequest, dict, ], ) -def test_delete_display_video360_advertiser_link(request_type, transport: str = "grpc"): +def test_delete_key_event(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18995,24 +18753,22 @@ def test_delete_display_video360_advertiser_link(request_type, transport: str = request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_display_video360_advertiser_link(request) + response = client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.DeleteKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. assert response is None -def test_delete_display_video360_advertiser_link_empty_call(): +def test_delete_key_event_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -19021,19 +18777,17 @@ def test_delete_display_video360_advertiser_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_display_video360_advertiser_link() + client.delete_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.DeleteKeyEventRequest() -def test_delete_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): +def test_delete_key_event_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -19044,26 +18798,24 @@ def test_delete_display_video360_advertiser_link_non_empty_request_with_auto_pop # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( + request = analytics_admin.DeleteKeyEventRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_display_video360_advertiser_link(request=request) + client.delete_key_event(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( + assert args[0] == analytics_admin.DeleteKeyEventRequest( name="name_value", ) -def test_delete_display_video360_advertiser_link_use_cached_wrapped_rpc(): +def test_delete_key_event_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19077,10 +18829,7 @@ def test_delete_display_video360_advertiser_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_display_video360_advertiser_link - in client._transport._wrapped_methods - ) + assert client._transport.delete_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -19088,15 +18837,15 @@ def test_delete_display_video360_advertiser_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_display_video360_advertiser_link + client._transport.delete_key_event ] = mock_rpc request = {} - client.delete_display_video360_advertiser_link(request) + client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_display_video360_advertiser_link(request) + client.delete_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19104,7 +18853,7 @@ def test_delete_display_video360_advertiser_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_empty_call_async(): +async def test_delete_key_event_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -19113,19 +18862,17 @@ async def test_delete_display_video360_advertiser_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_display_video360_advertiser_link() + response = await client.delete_key_event() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.DeleteKeyEventRequest() @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_async_use_cached_wrapped_rpc( +async def test_delete_key_event_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -19142,23 +18889,23 @@ async def test_delete_display_video360_advertiser_link_async_use_cached_wrapped_ # Ensure method has been cached assert ( - client._client._transport.delete_display_video360_advertiser_link + client._client._transport.delete_key_event in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_display_video360_advertiser_link + client._client._transport.delete_key_event ] = mock_object request = {} - await client.delete_display_video360_advertiser_link(request) + await client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_display_video360_advertiser_link(request) + await client.delete_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19166,9 +18913,8 @@ async def test_delete_display_video360_advertiser_link_async_use_cached_wrapped_ @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, +async def test_delete_key_event_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.DeleteKeyEventRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19180,17 +18926,15 @@ async def test_delete_display_video360_advertiser_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_display_video360_advertiser_link(request) + response = await client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.DeleteKeyEventRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -19198,27 +18942,25 @@ async def test_delete_display_video360_advertiser_link_async( @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_async_from_dict(): - await test_delete_display_video360_advertiser_link_async(request_type=dict) +async def test_delete_key_event_async_from_dict(): + await test_delete_key_event_async(request_type=dict) -def test_delete_display_video360_advertiser_link_field_headers(): +def test_delete_key_event_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.DeleteKeyEventRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: call.return_value = None - client.delete_display_video360_advertiser_link(request) + client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -19234,23 +18976,21 @@ def test_delete_display_video360_advertiser_link_field_headers(): @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_field_headers_async(): +async def test_delete_key_event_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.DeleteKeyEventRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_display_video360_advertiser_link(request) + await client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -19265,20 +19005,18 @@ async def test_delete_display_video360_advertiser_link_field_headers_async(): ) in kw["metadata"] -def test_delete_display_video360_advertiser_link_flattened(): +def test_delete_key_event_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_display_video360_advertiser_link( + client.delete_key_event( name="name_value", ) @@ -19291,7 +19029,7 @@ def test_delete_display_video360_advertiser_link_flattened(): assert arg == mock_val -def test_delete_display_video360_advertiser_link_flattened_error(): +def test_delete_key_event_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19299,29 +19037,27 @@ def test_delete_display_video360_advertiser_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_display_video360_advertiser_link( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), + client.delete_key_event( + analytics_admin.DeleteKeyEventRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_flattened_async(): +async def test_delete_key_event_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_key_event), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_display_video360_advertiser_link( + response = await client.delete_key_event( name="name_value", ) @@ -19335,7 +19071,7 @@ async def test_delete_display_video360_advertiser_link_flattened_async(): @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_flattened_error_async(): +async def test_delete_key_event_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19343,8 +19079,8 @@ async def test_delete_display_video360_advertiser_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_display_video360_advertiser_link( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), + await client.delete_key_event( + analytics_admin.DeleteKeyEventRequest(), name="name_value", ) @@ -19352,11 +19088,11 @@ async def test_delete_display_video360_advertiser_link_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, + analytics_admin.ListKeyEventsRequest, dict, ], ) -def test_update_display_video360_advertiser_link(request_type, transport: str = "grpc"): +def test_list_key_events(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19367,31 +19103,25 @@ def test_update_display_video360_advertiser_link(request_type, transport: str = request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + call.return_value = analytics_admin.ListKeyEventsResponse( + next_page_token="next_page_token_value", ) - response = client.update_display_video360_advertiser_link(request) + response = client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.ListKeyEventsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert isinstance(response, pagers.ListKeyEventsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_display_video360_advertiser_link_empty_call(): +def test_list_key_events_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -19400,19 +19130,17 @@ def test_update_display_video360_advertiser_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_display_video360_advertiser_link() + client.list_key_events() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.ListKeyEventsRequest() -def test_update_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): +def test_list_key_events_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -19423,22 +19151,26 @@ def test_update_display_video360_advertiser_link_non_empty_request_with_auto_pop # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.ListKeyEventsRequest( + parent="parent_value", + page_token="page_token_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_display_video360_advertiser_link(request=request) + client.list_key_events(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.ListKeyEventsRequest( + parent="parent_value", + page_token="page_token_value", + ) -def test_update_display_video360_advertiser_link_use_cached_wrapped_rpc(): +def test_list_key_events_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19452,26 +19184,21 @@ def test_update_display_video360_advertiser_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_display_video360_advertiser_link - in client._transport._wrapped_methods - ) + assert client._transport.list_key_events in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_display_video360_advertiser_link - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_key_events] = mock_rpc request = {} - client.update_display_video360_advertiser_link(request) + client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_display_video360_advertiser_link(request) + client.list_key_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19479,7 +19206,7 @@ def test_update_display_video360_advertiser_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_empty_call_async(): +async def test_list_key_events_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -19488,25 +19215,21 @@ async def test_update_display_video360_advertiser_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + analytics_admin.ListKeyEventsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_display_video360_advertiser_link() + response = await client.list_key_events() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == analytics_admin.ListKeyEventsRequest() @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_async_use_cached_wrapped_rpc( +async def test_list_key_events_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -19523,23 +19246,23 @@ async def test_update_display_video360_advertiser_link_async_use_cached_wrapped_ # Ensure method has been cached assert ( - client._client._transport.update_display_video360_advertiser_link + client._client._transport.list_key_events in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_display_video360_advertiser_link + client._client._transport.list_key_events ] = mock_object request = {} - await client.update_display_video360_advertiser_link(request) + await client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_display_video360_advertiser_link(request) + await client.list_key_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19547,9 +19270,8 @@ async def test_update_display_video360_advertiser_link_async_use_cached_wrapped_ @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, +async def test_list_key_events_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.ListKeyEventsRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19561,54 +19283,46 @@ async def test_update_display_video360_advertiser_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + analytics_admin.ListKeyEventsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_display_video360_advertiser_link(request) + response = await client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.ListKeyEventsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert isinstance(response, pagers.ListKeyEventsAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_async_from_dict(): - await test_update_display_video360_advertiser_link_async(request_type=dict) +async def test_list_key_events_async_from_dict(): + await test_list_key_events_async(request_type=dict) -def test_update_display_video360_advertiser_link_field_headers(): +def test_list_key_events_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.ListKeyEventsRequest() - request.display_video_360_advertiser_link.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: - call.return_value = resources.DisplayVideo360AdvertiserLink() - client.update_display_video360_advertiser_link(request) + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: + call.return_value = analytics_admin.ListKeyEventsResponse() + client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -19619,30 +19333,28 @@ def test_update_display_video360_advertiser_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "display_video_360_advertiser_link.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_field_headers_async(): +async def test_list_key_events_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.ListKeyEventsRequest() - request.display_video_360_advertiser_link.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink() + analytics_admin.ListKeyEventsResponse() ) - await client.update_display_video360_advertiser_link(request) + await client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -19653,43 +19365,35 @@ async def test_update_display_video360_advertiser_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "display_video_360_advertiser_link.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_display_video360_advertiser_link_flattened(): +def test_list_key_events_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink() + call.return_value = analytics_admin.ListKeyEventsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_display_video360_advertiser_link( - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_key_events( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].display_video_360_advertiser_link - mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_update_display_video360_advertiser_link_flattened_error(): +def test_list_key_events_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19697,54 +19401,43 @@ def test_update_display_video360_advertiser_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_display_video360_advertiser_link( - analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_key_events( + analytics_admin.ListKeyEventsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_flattened_async(): +async def test_list_key_events_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_display_video360_advertiser_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLink() + call.return_value = analytics_admin.ListKeyEventsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLink() + analytics_admin.ListKeyEventsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_display_video360_advertiser_link( - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.list_key_events( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].display_video_360_advertiser_link - mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_display_video360_advertiser_link_flattened_error_async(): +async def test_list_key_events_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19752,25 +19445,214 @@ async def test_update_display_video360_advertiser_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_display_video360_advertiser_link( - analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" + await client.list_key_events( + analytics_admin.ListKeyEventsRequest(), + parent="parent_value", + ) + + +def test_list_key_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token="abc", ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token="def", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token="ghi", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_key_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyEvent) for i in results) + + +def test_list_key_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_key_events), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token="abc", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token="def", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token="ghi", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_key_events(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_key_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token="abc", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token="def", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token="ghi", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_key_events( + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.KeyEvent) for i in responses) + + +@pytest.mark.asyncio +async def test_list_key_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token="abc", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token="def", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token="ghi", + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_key_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_get_display_video360_advertiser_link_proposal( - request_type, transport: str = "grpc" -): +def test_get_display_video360_advertiser_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19782,32 +19664,30 @@ def test_get_display_video360_advertiser_link_proposal( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( + call.return_value = resources.DisplayVideo360AdvertiserLink( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", ) - response = client.get_display_video360_advertiser_link_proposal(request) + response = client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) assert response.name == "name_value" assert response.advertiser_id == "advertiser_id_value" assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" -def test_get_display_video360_advertiser_link_proposal_empty_call(): +def test_get_display_video360_advertiser_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -19817,20 +19697,18 @@ def test_get_display_video360_advertiser_link_proposal_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_display_video360_advertiser_link_proposal() + client.get_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() -def test_get_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): +def test_get_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -19841,28 +19719,26 @@ def test_get_display_video360_advertiser_link_proposal_non_empty_request_with_au # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_display_video360_advertiser_link_proposal(request=request) + client.get_display_video360_advertiser_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[ - 0 - ] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest( name="name_value", ) -def test_get_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): +def test_get_display_video360_advertiser_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -19877,7 +19753,7 @@ def test_get_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_display_video360_advertiser_link_proposal + client._transport.get_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -19887,15 +19763,15 @@ def test_get_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_display_video360_advertiser_link_proposal + client._transport.get_display_video360_advertiser_link ] = mock_rpc request = {} - client.get_display_video360_advertiser_link_proposal(request) + client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_display_video360_advertiser_link_proposal(request) + client.get_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19903,7 +19779,7 @@ def test_get_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_empty_call_async(): +async def test_get_display_video360_advertiser_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -19913,27 +19789,24 @@ async def test_get_display_video360_advertiser_link_proposal_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal( + resources.DisplayVideo360AdvertiserLink( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", ) ) - response = await client.get_display_video360_advertiser_link_proposal() + response = await client.get_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( +async def test_get_display_video360_advertiser_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -19950,23 +19823,23 @@ async def test_get_display_video360_advertiser_link_proposal_async_use_cached_wr # Ensure method has been cached assert ( - client._client._transport.get_display_video360_advertiser_link_proposal + client._client._transport.get_display_video360_advertiser_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_display_video360_advertiser_link_proposal + client._client._transport.get_display_video360_advertiser_link ] = mock_object request = {} - await client.get_display_video360_advertiser_link_proposal(request) + await client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_display_video360_advertiser_link_proposal(request) + await client.get_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19974,9 +19847,9 @@ async def test_get_display_video360_advertiser_link_proposal_async_use_cached_wr @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_async( +async def test_get_display_video360_advertiser_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, + request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -19989,55 +19862,53 @@ async def test_get_display_video360_advertiser_link_proposal_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal( + resources.DisplayVideo360AdvertiserLink( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", ) ) - response = await client.get_display_video360_advertiser_link_proposal(request) + response = await client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) assert response.name == "name_value" assert response.advertiser_id == "advertiser_id_value" assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_async_from_dict(): - await test_get_display_video360_advertiser_link_proposal_async(request_type=dict) +async def test_get_display_video360_advertiser_link_async_from_dict(): + await test_get_display_video360_advertiser_link_async(request_type=dict) -def test_get_display_video360_advertiser_link_proposal_field_headers(): +def test_get_display_video360_advertiser_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.get_display_video360_advertiser_link_proposal(request) + call.return_value = resources.DisplayVideo360AdvertiserLink() + client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -20053,25 +19924,25 @@ def test_get_display_video360_advertiser_link_proposal_field_headers(): @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_field_headers_async(): +async def test_get_display_video360_advertiser_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal() + resources.DisplayVideo360AdvertiserLink() ) - await client.get_display_video360_advertiser_link_proposal(request) + await client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -20086,20 +19957,20 @@ async def test_get_display_video360_advertiser_link_proposal_field_headers_async ) in kw["metadata"] -def test_get_display_video360_advertiser_link_proposal_flattened(): +def test_get_display_video360_advertiser_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + call.return_value = resources.DisplayVideo360AdvertiserLink() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_display_video360_advertiser_link_proposal( + client.get_display_video360_advertiser_link( name="name_value", ) @@ -20112,7 +19983,7 @@ def test_get_display_video360_advertiser_link_proposal_flattened(): assert arg == mock_val -def test_get_display_video360_advertiser_link_proposal_flattened_error(): +def test_get_display_video360_advertiser_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -20120,31 +19991,31 @@ def test_get_display_video360_advertiser_link_proposal_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_display_video360_advertiser_link_proposal( - analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + client.get_display_video360_advertiser_link( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_flattened_async(): +async def test_get_display_video360_advertiser_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + type(client.transport.get_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + call.return_value = resources.DisplayVideo360AdvertiserLink() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal() + resources.DisplayVideo360AdvertiserLink() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_display_video360_advertiser_link_proposal( + response = await client.get_display_video360_advertiser_link( name="name_value", ) @@ -20158,7 +20029,7 @@ async def test_get_display_video360_advertiser_link_proposal_flattened_async(): @pytest.mark.asyncio -async def test_get_display_video360_advertiser_link_proposal_flattened_error_async(): +async def test_get_display_video360_advertiser_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -20166,8 +20037,8 @@ async def test_get_display_video360_advertiser_link_proposal_flattened_error_asy # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_display_video360_advertiser_link_proposal( - analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + await client.get_display_video360_advertiser_link( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), name="name_value", ) @@ -20175,13 +20046,11 @@ async def test_get_display_video360_advertiser_link_proposal_flattened_error_asy @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, dict, ], ) -def test_list_display_video360_advertiser_link_proposals( - request_type, transport: str = "grpc" -): +def test_list_display_video360_advertiser_links(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20193,29 +20062,26 @@ def test_list_display_video360_advertiser_link_proposals( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - next_page_token="next_page_token_value", - ) + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + next_page_token="next_page_token_value", ) - response = client.list_display_video360_advertiser_link_proposals(request) + response = client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsPager) + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksPager) assert response.next_page_token == "next_page_token_value" -def test_list_display_video360_advertiser_link_proposals_empty_call(): +def test_list_display_video360_advertiser_links_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -20225,22 +20091,18 @@ def test_list_display_video360_advertiser_link_proposals_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_display_video360_advertiser_link_proposals() + client.list_display_video360_advertiser_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ) + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() -def test_list_display_video360_advertiser_link_proposals_non_empty_request_with_auto_populated_field(): +def test_list_display_video360_advertiser_links_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -20251,31 +20113,28 @@ def test_list_display_video360_advertiser_link_proposals_non_empty_request_with_ # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( parent="parent_value", page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_display_video360_advertiser_link_proposals(request=request) + client.list_display_video360_advertiser_links(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[ - 0 - ] == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( parent="parent_value", page_token="page_token_value", ) -def test_list_display_video360_advertiser_link_proposals_use_cached_wrapped_rpc(): +def test_list_display_video360_advertiser_links_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20290,7 +20149,7 @@ def test_list_display_video360_advertiser_link_proposals_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._transport.list_display_video360_advertiser_link_proposals + client._transport.list_display_video360_advertiser_links in client._transport._wrapped_methods ) @@ -20300,15 +20159,15 @@ def test_list_display_video360_advertiser_link_proposals_use_cached_wrapped_rpc( "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_display_video360_advertiser_link_proposals + client._transport.list_display_video360_advertiser_links ] = mock_rpc request = {} - client.list_display_video360_advertiser_link_proposals(request) + client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_display_video360_advertiser_link_proposals(request) + client.list_display_video360_advertiser_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20316,7 +20175,7 @@ def test_list_display_video360_advertiser_link_proposals_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_empty_call_async(): +async def test_list_display_video360_advertiser_links_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -20326,26 +20185,22 @@ async def test_list_display_video360_advertiser_link_proposals_empty_call_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_display_video360_advertiser_link_proposals() + response = await client.list_display_video360_advertiser_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ) + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_async_use_cached_wrapped_rpc( +async def test_list_display_video360_advertiser_links_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -20362,23 +20217,23 @@ async def test_list_display_video360_advertiser_link_proposals_async_use_cached_ # Ensure method has been cached assert ( - client._client._transport.list_display_video360_advertiser_link_proposals + client._client._transport.list_display_video360_advertiser_links in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_display_video360_advertiser_link_proposals + client._client._transport.list_display_video360_advertiser_links ] = mock_object request = {} - await client.list_display_video360_advertiser_link_proposals(request) + await client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_display_video360_advertiser_link_proposals(request) + await client.list_display_video360_advertiser_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20386,9 +20241,9 @@ async def test_list_display_video360_advertiser_link_proposals_async_use_cached_ @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_async( +async def test_list_display_video360_advertiser_links_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -20401,55 +20256,49 @@ async def test_list_display_video360_advertiser_link_proposals_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_display_video360_advertiser_link_proposals(request) + response = await client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager - ) + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_async_from_dict(): - await test_list_display_video360_advertiser_link_proposals_async(request_type=dict) +async def test_list_display_video360_advertiser_links_async_from_dict(): + await test_list_display_video360_advertiser_links_async(request_type=dict) -def test_list_display_video360_advertiser_link_proposals_field_headers(): +def test_list_display_video360_advertiser_links_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: - call.return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() - ) - client.list_display_video360_advertiser_link_proposals(request) + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -20465,26 +20314,25 @@ def test_list_display_video360_advertiser_link_proposals_field_headers(): @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_field_headers_async(): +async def test_list_display_video360_advertiser_links_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() ) - await client.list_display_video360_advertiser_link_proposals(request) + await client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -20499,23 +20347,20 @@ async def test_list_display_video360_advertiser_link_proposals_field_headers_asy ) in kw["metadata"] -def test_list_display_video360_advertiser_link_proposals_flattened(): +def test_list_display_video360_advertiser_links_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() - ) + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_display_video360_advertiser_link_proposals( + client.list_display_video360_advertiser_links( parent="parent_value", ) @@ -20528,7 +20373,7 @@ def test_list_display_video360_advertiser_link_proposals_flattened(): assert arg == mock_val -def test_list_display_video360_advertiser_link_proposals_flattened_error(): +def test_list_display_video360_advertiser_links_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -20536,34 +20381,31 @@ def test_list_display_video360_advertiser_link_proposals_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_display_video360_advertiser_link_proposals( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + client.list_display_video360_advertiser_links( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_flattened_async(): +async def test_list_display_video360_advertiser_links_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() - ) + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_display_video360_advertiser_link_proposals( + response = await client.list_display_video360_advertiser_links( parent="parent_value", ) @@ -20577,7 +20419,7 @@ async def test_list_display_video360_advertiser_link_proposals_flattened_async() @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_flattened_error_async(): +async def test_list_display_video360_advertiser_links_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -20585,15 +20427,13 @@ async def test_list_display_video360_advertiser_link_proposals_flattened_error_a # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_display_video360_advertiser_link_proposals( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + await client.list_display_video360_advertiser_links( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), parent="parent_value", ) -def test_list_display_video360_advertiser_link_proposals_pager( - transport_name: str = "grpc", -): +def test_list_display_video360_advertiser_links_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -20601,33 +20441,32 @@ def test_list_display_video360_advertiser_link_proposals_pager( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="abc", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[], + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], next_page_token="def", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="ghi", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], ), RuntimeError, @@ -20639,7 +20478,7 @@ def test_list_display_video360_advertiser_link_proposals_pager( expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_display_video360_advertiser_link_proposals( + pager = client.list_display_video360_advertiser_links( request={}, retry=retry, timeout=timeout ) @@ -20650,14 +20489,11 @@ def test_list_display_video360_advertiser_link_proposals_pager( results = list(pager) assert len(results) == 6 assert all( - isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) - for i in results + isinstance(i, resources.DisplayVideo360AdvertiserLink) for i in results ) -def test_list_display_video360_advertiser_link_proposals_pages( - transport_name: str = "grpc", -): +def test_list_display_video360_advertiser_links_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -20665,85 +20501,82 @@ def test_list_display_video360_advertiser_link_proposals_pages( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), - "__call__", + type(client.transport.list_display_video360_advertiser_links), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="abc", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[], + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], next_page_token="def", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="ghi", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), - ], - ), - RuntimeError, - ) - pages = list( - client.list_display_video360_advertiser_link_proposals(request={}).pages + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + RuntimeError, ) + pages = list(client.list_display_video360_advertiser_links(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_async_pager(): +async def test_list_display_video360_advertiser_links_async_pager(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), + type(client.transport.list_display_video360_advertiser_links), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="abc", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[], + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], next_page_token="def", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="ghi", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], ), RuntimeError, ) - async_pager = await client.list_display_video360_advertiser_link_proposals( + async_pager = await client.list_display_video360_advertiser_links( request={}, ) assert async_pager.next_page_token == "abc" @@ -20753,47 +20586,46 @@ async def test_list_display_video360_advertiser_link_proposals_async_pager(): assert len(responses) == 6 assert all( - isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) - for i in responses + isinstance(i, resources.DisplayVideo360AdvertiserLink) for i in responses ) @pytest.mark.asyncio -async def test_list_display_video360_advertiser_link_proposals_async_pages(): +async def test_list_display_video360_advertiser_links_async_pages(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_display_video360_advertiser_link_proposals), + type(client.transport.list_display_video360_advertiser_links), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="abc", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[], + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], next_page_token="def", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), ], next_page_token="ghi", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), ], ), RuntimeError, @@ -20802,7 +20634,7 @@ async def test_list_display_video360_advertiser_link_proposals_async_pages(): # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 async for page_ in ( # pragma: no branch - await client.list_display_video360_advertiser_link_proposals(request={}) + await client.list_display_video360_advertiser_links(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -20812,13 +20644,11 @@ async def test_list_display_video360_advertiser_link_proposals_async_pages(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_create_display_video360_advertiser_link_proposal( - request_type, transport: str = "grpc" -): +def test_create_display_video360_advertiser_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20830,33 +20660,30 @@ def test_create_display_video360_advertiser_link_proposal( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( + call.return_value = resources.DisplayVideo360AdvertiserLink( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", ) - response = client.create_display_video360_advertiser_link_proposal(request) + response = client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) assert response.name == "name_value" assert response.advertiser_id == "advertiser_id_value" assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" -def test_create_display_video360_advertiser_link_proposal_empty_call(): +def test_create_display_video360_advertiser_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -20866,22 +20693,18 @@ def test_create_display_video360_advertiser_link_proposal_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_display_video360_advertiser_link_proposal() + client.create_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() -def test_create_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): +def test_create_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -20892,29 +20715,26 @@ def test_create_display_video360_advertiser_link_proposal_non_empty_request_with # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_display_video360_advertiser_link_proposal(request=request) + client.create_display_video360_advertiser_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[ - 0 - ] == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( parent="parent_value", ) -def test_create_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): +def test_create_display_video360_advertiser_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -20929,7 +20749,7 @@ def test_create_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._transport.create_display_video360_advertiser_link_proposal + client._transport.create_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -20939,15 +20759,15 @@ def test_create_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_display_video360_advertiser_link_proposal + client._transport.create_display_video360_advertiser_link ] = mock_rpc request = {} - client.create_display_video360_advertiser_link_proposal(request) + client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_display_video360_advertiser_link_proposal(request) + client.create_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20955,7 +20775,7 @@ def test_create_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_empty_call_async(): +async def test_create_display_video360_advertiser_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -20965,29 +20785,24 @@ async def test_create_display_video360_advertiser_link_proposal_empty_call_async # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal( + resources.DisplayVideo360AdvertiserLink( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", ) ) - response = await client.create_display_video360_advertiser_link_proposal() + response = await client.create_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( +async def test_create_display_video360_advertiser_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -21004,23 +20819,23 @@ async def test_create_display_video360_advertiser_link_proposal_async_use_cached # Ensure method has been cached assert ( - client._client._transport.create_display_video360_advertiser_link_proposal + client._client._transport.create_display_video360_advertiser_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_display_video360_advertiser_link_proposal + client._client._transport.create_display_video360_advertiser_link ] = mock_object request = {} - await client.create_display_video360_advertiser_link_proposal(request) + await client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_display_video360_advertiser_link_proposal(request) + await client.create_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21028,9 +20843,9 @@ async def test_create_display_video360_advertiser_link_proposal_async_use_cached @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_async( +async def test_create_display_video360_advertiser_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, + request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21043,59 +20858,53 @@ async def test_create_display_video360_advertiser_link_proposal_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal( + resources.DisplayVideo360AdvertiserLink( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", ) ) - response = await client.create_display_video360_advertiser_link_proposal( - request - ) + response = await client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) assert response.name == "name_value" assert response.advertiser_id == "advertiser_id_value" assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_async_from_dict(): - await test_create_display_video360_advertiser_link_proposal_async(request_type=dict) +async def test_create_display_video360_advertiser_link_async_from_dict(): + await test_create_display_video360_advertiser_link_async(request_type=dict) -def test_create_display_video360_advertiser_link_proposal_field_headers(): +def test_create_display_video360_advertiser_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.create_display_video360_advertiser_link_proposal(request) + call.return_value = resources.DisplayVideo360AdvertiserLink() + client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -21111,26 +20920,25 @@ def test_create_display_video360_advertiser_link_proposal_field_headers(): @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_field_headers_async(): +async def test_create_display_video360_advertiser_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal() + resources.DisplayVideo360AdvertiserLink() ) - await client.create_display_video360_advertiser_link_proposal(request) + await client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -21145,23 +20953,22 @@ async def test_create_display_video360_advertiser_link_proposal_field_headers_as ) in kw["metadata"] -def test_create_display_video360_advertiser_link_proposal_flattened(): +def test_create_display_video360_advertiser_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + call.return_value = resources.DisplayVideo360AdvertiserLink() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_display_video360_advertiser_link_proposal( + client.create_display_video360_advertiser_link( parent="parent_value", - display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( name="name_value" ), ) @@ -21173,12 +20980,12 @@ def test_create_display_video360_advertiser_link_proposal_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].display_video_360_advertiser_link_proposal - mock_val = resources.DisplayVideo360AdvertiserLinkProposal(name="name_value") + arg = args[0].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") assert arg == mock_val -def test_create_display_video360_advertiser_link_proposal_flattened_error(): +def test_create_display_video360_advertiser_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21186,37 +20993,36 @@ def test_create_display_video360_advertiser_link_proposal_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_display_video360_advertiser_link_proposal( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + client.create_display_video360_advertiser_link( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), parent="parent_value", - display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( name="name_value" ), ) @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_flattened_async(): +async def test_create_display_video360_advertiser_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.create_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + call.return_value = resources.DisplayVideo360AdvertiserLink() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DisplayVideo360AdvertiserLinkProposal() + resources.DisplayVideo360AdvertiserLink() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_display_video360_advertiser_link_proposal( + response = await client.create_display_video360_advertiser_link( parent="parent_value", - display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( name="name_value" ), ) @@ -21228,13 +21034,13 @@ async def test_create_display_video360_advertiser_link_proposal_flattened_async( arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].display_video_360_advertiser_link_proposal - mock_val = resources.DisplayVideo360AdvertiserLinkProposal(name="name_value") + arg = args[0].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_create_display_video360_advertiser_link_proposal_flattened_error_async(): +async def test_create_display_video360_advertiser_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21242,10 +21048,10 @@ async def test_create_display_video360_advertiser_link_proposal_flattened_error_ # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_display_video360_advertiser_link_proposal( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + await client.create_display_video360_advertiser_link( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), parent="parent_value", - display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( name="name_value" ), ) @@ -21254,13 +21060,11 @@ async def test_create_display_video360_advertiser_link_proposal_flattened_error_ @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_delete_display_video360_advertiser_link_proposal( - request_type, transport: str = "grpc" -): +def test_delete_display_video360_advertiser_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -21272,24 +21076,23 @@ def test_delete_display_video360_advertiser_link_proposal( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_display_video360_advertiser_link_proposal(request) + response = client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. assert response is None -def test_delete_display_video360_advertiser_link_proposal_empty_call(): +def test_delete_display_video360_advertiser_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -21299,22 +21102,18 @@ def test_delete_display_video360_advertiser_link_proposal_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_display_video360_advertiser_link_proposal() + client.delete_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() -def test_delete_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): +def test_delete_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -21325,29 +21124,26 @@ def test_delete_display_video360_advertiser_link_proposal_non_empty_request_with # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_display_video360_advertiser_link_proposal(request=request) + client.delete_display_video360_advertiser_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[ - 0 - ] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( name="name_value", ) -def test_delete_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): +def test_delete_display_video360_advertiser_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21362,7 +21158,7 @@ def test_delete_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._transport.delete_display_video360_advertiser_link_proposal + client._transport.delete_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -21372,15 +21168,15 @@ def test_delete_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_display_video360_advertiser_link_proposal + client._transport.delete_display_video360_advertiser_link ] = mock_rpc request = {} - client.delete_display_video360_advertiser_link_proposal(request) + client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_display_video360_advertiser_link_proposal(request) + client.delete_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21388,7 +21184,7 @@ def test_delete_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_empty_call_async(): +async def test_delete_display_video360_advertiser_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -21398,22 +21194,18 @@ async def test_delete_display_video360_advertiser_link_proposal_empty_call_async # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_display_video360_advertiser_link_proposal() + response = await client.delete_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( +async def test_delete_display_video360_advertiser_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -21430,23 +21222,23 @@ async def test_delete_display_video360_advertiser_link_proposal_async_use_cached # Ensure method has been cached assert ( - client._client._transport.delete_display_video360_advertiser_link_proposal + client._client._transport.delete_display_video360_advertiser_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_display_video360_advertiser_link_proposal + client._client._transport.delete_display_video360_advertiser_link ] = mock_object request = {} - await client.delete_display_video360_advertiser_link_proposal(request) + await client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_display_video360_advertiser_link_proposal(request) + await client.delete_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21454,9 +21246,9 @@ async def test_delete_display_video360_advertiser_link_proposal_async_use_cached @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_async( +async def test_delete_display_video360_advertiser_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, + request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21469,19 +21261,16 @@ async def test_delete_display_video360_advertiser_link_proposal_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_display_video360_advertiser_link_proposal( - request - ) + response = await client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -21489,28 +21278,27 @@ async def test_delete_display_video360_advertiser_link_proposal_async( @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_async_from_dict(): - await test_delete_display_video360_advertiser_link_proposal_async(request_type=dict) +async def test_delete_display_video360_advertiser_link_async_from_dict(): + await test_delete_display_video360_advertiser_link_async(request_type=dict) -def test_delete_display_video360_advertiser_link_proposal_field_headers(): +def test_delete_display_video360_advertiser_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: call.return_value = None - client.delete_display_video360_advertiser_link_proposal(request) + client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -21526,24 +21314,23 @@ def test_delete_display_video360_advertiser_link_proposal_field_headers(): @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_field_headers_async(): +async def test_delete_display_video360_advertiser_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_display_video360_advertiser_link_proposal(request) + await client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -21558,21 +21345,20 @@ async def test_delete_display_video360_advertiser_link_proposal_field_headers_as ) in kw["metadata"] -def test_delete_display_video360_advertiser_link_proposal_flattened(): +def test_delete_display_video360_advertiser_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_display_video360_advertiser_link_proposal( + client.delete_display_video360_advertiser_link( name="name_value", ) @@ -21585,7 +21371,7 @@ def test_delete_display_video360_advertiser_link_proposal_flattened(): assert arg == mock_val -def test_delete_display_video360_advertiser_link_proposal_flattened_error(): +def test_delete_display_video360_advertiser_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21593,22 +21379,21 @@ def test_delete_display_video360_advertiser_link_proposal_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_display_video360_advertiser_link_proposal( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + client.delete_display_video360_advertiser_link( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_flattened_async(): +async def test_delete_display_video360_advertiser_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.delete_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -21616,7 +21401,7 @@ async def test_delete_display_video360_advertiser_link_proposal_flattened_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_display_video360_advertiser_link_proposal( + response = await client.delete_display_video360_advertiser_link( name="name_value", ) @@ -21630,7 +21415,7 @@ async def test_delete_display_video360_advertiser_link_proposal_flattened_async( @pytest.mark.asyncio -async def test_delete_display_video360_advertiser_link_proposal_flattened_error_async(): +async def test_delete_display_video360_advertiser_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21638,8 +21423,8 @@ async def test_delete_display_video360_advertiser_link_proposal_flattened_error_ # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_display_video360_advertiser_link_proposal( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + await client.delete_display_video360_advertiser_link( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), name="name_value", ) @@ -21647,13 +21432,11 @@ async def test_delete_display_video360_advertiser_link_proposal_flattened_error_ @pytest.mark.parametrize( "request_type", [ - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_approve_display_video360_advertiser_link_proposal( - request_type, transport: str = "grpc" -): +def test_update_display_video360_advertiser_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -21665,28 +21448,30 @@ def test_approve_display_video360_advertiser_link_proposal( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + call.return_value = resources.DisplayVideo360AdvertiserLink( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) - response = client.approve_display_video360_advertiser_link_proposal(request) + response = client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse - ) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_approve_display_video360_advertiser_link_proposal_empty_call(): +def test_update_display_video360_advertiser_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -21696,22 +21481,18 @@ def test_approve_display_video360_advertiser_link_proposal_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.approve_display_video360_advertiser_link_proposal() + client.update_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() -def test_approve_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): +def test_update_display_video360_advertiser_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -21722,29 +21503,22 @@ def test_approve_display_video360_advertiser_link_proposal_non_empty_request_wit # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( - name="name_value", - ) + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.approve_display_video360_advertiser_link_proposal(request=request) + client.update_display_video360_advertiser_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[ - 0 - ] == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( - name="name_value", - ) + assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() -def test_approve_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): +def test_update_display_video360_advertiser_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -21759,7 +21533,7 @@ def test_approve_display_video360_advertiser_link_proposal_use_cached_wrapped_rp # Ensure method has been cached assert ( - client._transport.approve_display_video360_advertiser_link_proposal + client._transport.update_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -21769,15 +21543,15 @@ def test_approve_display_video360_advertiser_link_proposal_use_cached_wrapped_rp "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.approve_display_video360_advertiser_link_proposal + client._transport.update_display_video360_advertiser_link ] = mock_rpc request = {} - client.approve_display_video360_advertiser_link_proposal(request) + client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.approve_display_video360_advertiser_link_proposal(request) + client.update_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21785,7 +21559,7 @@ def test_approve_display_video360_advertiser_link_proposal_use_cached_wrapped_rp @pytest.mark.asyncio -async def test_approve_display_video360_advertiser_link_proposal_empty_call_async(): +async def test_update_display_video360_advertiser_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -21795,24 +21569,24 @@ async def test_approve_display_video360_advertiser_link_proposal_empty_call_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + resources.DisplayVideo360AdvertiserLink( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + ) ) - response = await client.approve_display_video360_advertiser_link_proposal() + response = await client.update_display_video360_advertiser_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( - args[0] - == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ) + assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() @pytest.mark.asyncio -async def test_approve_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( +async def test_update_display_video360_advertiser_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -21829,23 +21603,23 @@ async def test_approve_display_video360_advertiser_link_proposal_async_use_cache # Ensure method has been cached assert ( - client._client._transport.approve_display_video360_advertiser_link_proposal + client._client._transport.update_display_video360_advertiser_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.approve_display_video360_advertiser_link_proposal + client._client._transport.update_display_video360_advertiser_link ] = mock_object request = {} - await client.approve_display_video360_advertiser_link_proposal(request) + await client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.approve_display_video360_advertiser_link_proposal(request) + await client.update_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21853,9 +21627,9 @@ async def test_approve_display_video360_advertiser_link_proposal_async_use_cache @pytest.mark.asyncio -async def test_approve_display_video360_advertiser_link_proposal_async( +async def test_update_display_video360_advertiser_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -21868,56 +21642,53 @@ async def test_approve_display_video360_advertiser_link_proposal_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() - ) - response = await client.approve_display_video360_advertiser_link_proposal( - request + resources.DisplayVideo360AdvertiserLink( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + ) ) + response = await client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse - ) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" @pytest.mark.asyncio -async def test_approve_display_video360_advertiser_link_proposal_async_from_dict(): - await test_approve_display_video360_advertiser_link_proposal_async( - request_type=dict - ) +async def test_update_display_video360_advertiser_link_async_from_dict(): + await test_update_display_video360_advertiser_link_async(request_type=dict) -def test_approve_display_video360_advertiser_link_proposal_field_headers(): +def test_update_display_video360_advertiser_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() - request.name = "name_value" + request.display_video_360_advertiser_link.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: - call.return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() - ) - client.approve_display_video360_advertiser_link_proposal(request) + call.return_value = resources.DisplayVideo360AdvertiserLink() + client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -21928,31 +21699,30 @@ def test_approve_display_video360_advertiser_link_proposal_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "display_video_360_advertiser_link.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_approve_display_video360_advertiser_link_proposal_field_headers_async(): +async def test_update_display_video360_advertiser_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() - request.name = "name_value" + request.display_video_360_advertiser_link.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.update_display_video360_advertiser_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + resources.DisplayVideo360AdvertiserLink() ) - await client.approve_display_video360_advertiser_link_proposal(request) + await client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -21963,18 +21733,122 @@ async def test_approve_display_video360_advertiser_link_proposal_field_headers_a _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "display_video_360_advertiser_link.name=name_value", ) in kw["metadata"] +def test_update_display_video360_advertiser_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_display_video360_advertiser_link( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_display_video360_advertiser_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_display_video360_advertiser_link( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DisplayVideo360AdvertiserLink() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_display_video360_advertiser_link( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_display_video360_advertiser_link( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_cancel_display_video360_advertiser_link_proposal( +def test_get_display_video360_advertiser_link_proposal( request_type, transport: str = "grpc" ): client = AnalyticsAdminServiceClient( @@ -21988,8 +21862,7 @@ def test_cancel_display_video360_advertiser_link_proposal( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( @@ -21998,12 +21871,12 @@ def test_cancel_display_video360_advertiser_link_proposal( advertiser_display_name="advertiser_display_name_value", validation_email="validation_email_value", ) - response = client.cancel_display_video360_advertiser_link_proposal(request) + response = client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -22014,7 +21887,7 @@ def test_cancel_display_video360_advertiser_link_proposal( assert response.validation_email == "validation_email_value" -def test_cancel_display_video360_advertiser_link_proposal_empty_call(): +def test_get_display_video360_advertiser_link_proposal_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -22024,22 +21897,20 @@ def test_cancel_display_video360_advertiser_link_proposal_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.cancel_display_video360_advertiser_link_proposal() + client.get_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] assert ( - args[0] - == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() ) -def test_cancel_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): +def test_get_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -22050,29 +21921,28 @@ def test_cancel_display_video360_advertiser_link_proposal_non_empty_request_with # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.cancel_display_video360_advertiser_link_proposal(request=request) + client.get_display_video360_advertiser_link_proposal(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[ 0 - ] == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( + ] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) -def test_cancel_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): +def test_get_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22087,7 +21957,7 @@ def test_cancel_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._transport.cancel_display_video360_advertiser_link_proposal + client._transport.get_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -22097,15 +21967,15 @@ def test_cancel_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.cancel_display_video360_advertiser_link_proposal + client._transport.get_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.cancel_display_video360_advertiser_link_proposal(request) + client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.cancel_display_video360_advertiser_link_proposal(request) + client.get_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -22113,7 +21983,7 @@ def test_cancel_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc @pytest.mark.asyncio -async def test_cancel_display_video360_advertiser_link_proposal_empty_call_async(): +async def test_get_display_video360_advertiser_link_proposal_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -22123,8 +21993,7 @@ async def test_cancel_display_video360_advertiser_link_proposal_empty_call_async # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -22135,17 +22004,16 @@ async def test_cancel_display_video360_advertiser_link_proposal_empty_call_async validation_email="validation_email_value", ) ) - response = await client.cancel_display_video360_advertiser_link_proposal() + response = await client.get_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] assert ( - args[0] - == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() ) @pytest.mark.asyncio -async def test_cancel_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( +async def test_get_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -22162,23 +22030,23 @@ async def test_cancel_display_video360_advertiser_link_proposal_async_use_cached # Ensure method has been cached assert ( - client._client._transport.cancel_display_video360_advertiser_link_proposal + client._client._transport.get_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.cancel_display_video360_advertiser_link_proposal + client._client._transport.get_display_video360_advertiser_link_proposal ] = mock_object request = {} - await client.cancel_display_video360_advertiser_link_proposal(request) + await client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.cancel_display_video360_advertiser_link_proposal(request) + await client.get_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -22186,9 +22054,9 @@ async def test_cancel_display_video360_advertiser_link_proposal_async_use_cached @pytest.mark.asyncio -async def test_cancel_display_video360_advertiser_link_proposal_async( +async def test_get_display_video360_advertiser_link_proposal_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, + request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -22201,8 +22069,7 @@ async def test_cancel_display_video360_advertiser_link_proposal_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -22213,14 +22080,12 @@ async def test_cancel_display_video360_advertiser_link_proposal_async( validation_email="validation_email_value", ) ) - response = await client.cancel_display_video360_advertiser_link_proposal( - request - ) + response = await client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -22232,28 +22097,27 @@ async def test_cancel_display_video360_advertiser_link_proposal_async( @pytest.mark.asyncio -async def test_cancel_display_video360_advertiser_link_proposal_async_from_dict(): - await test_cancel_display_video360_advertiser_link_proposal_async(request_type=dict) +async def test_get_display_video360_advertiser_link_proposal_async_from_dict(): + await test_get_display_video360_advertiser_link_proposal_async(request_type=dict) -def test_cancel_display_video360_advertiser_link_proposal_field_headers(): +def test_get_display_video360_advertiser_link_proposal_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.cancel_display_video360_advertiser_link_proposal(request) + client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -22269,26 +22133,25 @@ def test_cancel_display_video360_advertiser_link_proposal_field_headers(): @pytest.mark.asyncio -async def test_cancel_display_video360_advertiser_link_proposal_field_headers_async(): +async def test_get_display_video360_advertiser_link_proposal_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.cancel_display_video360_advertiser_link_proposal), - "__call__", + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.DisplayVideo360AdvertiserLinkProposal() ) - await client.cancel_display_video360_advertiser_link_proposal(request) + await client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -22303,14 +22166,102 @@ async def test_cancel_display_video360_advertiser_link_proposal_field_headers_as ) in kw["metadata"] +def test_get_display_video360_advertiser_link_proposal_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_display_video360_advertiser_link_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_display_video360_advertiser_link_proposal_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_display_video360_advertiser_link_proposal( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DisplayVideo360AdvertiserLinkProposal() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_display_video360_advertiser_link_proposal( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_display_video360_advertiser_link_proposal( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateCustomDimensionRequest, + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict, ], ) -def test_create_custom_dimension(request_type, transport: str = "grpc"): +def test_list_display_video360_advertiser_link_proposals( + request_type, transport: str = "grpc" +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22322,36 +22273,29 @@ def test_create_custom_dimension(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension( - name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + call.return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token="next_page_token_value", + ) ) - response = client.create_custom_dimension(request) + response = client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateCustomDimensionRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) - assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsPager) + assert response.next_page_token == "next_page_token_value" -def test_create_custom_dimension_empty_call(): +def test_list_display_video360_advertiser_link_proposals_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -22361,18 +22305,22 @@ def test_create_custom_dimension_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_custom_dimension() + client.list_display_video360_advertiser_link_proposals() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + ) -def test_create_custom_dimension_non_empty_request_with_auto_populated_field(): +def test_list_display_video360_advertiser_link_proposals_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -22383,26 +22331,31 @@ def test_create_custom_dimension_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateCustomDimensionRequest( + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_custom_dimension(request=request) + client.list_display_video360_advertiser_link_proposals(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCustomDimensionRequest( + assert args[ + 0 + ] == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( parent="parent_value", + page_token="page_token_value", ) -def test_create_custom_dimension_use_cached_wrapped_rpc(): +def test_list_display_video360_advertiser_link_proposals_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22417,7 +22370,7 @@ def test_create_custom_dimension_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_custom_dimension + client._transport.list_display_video360_advertiser_link_proposals in client._transport._wrapped_methods ) @@ -22427,15 +22380,15 @@ def test_create_custom_dimension_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_custom_dimension + client._transport.list_display_video360_advertiser_link_proposals ] = mock_rpc request = {} - client.create_custom_dimension(request) + client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_dimension(request) + client.list_display_video360_advertiser_link_proposals(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -22443,7 +22396,7 @@ def test_create_custom_dimension_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_custom_dimension_empty_call_async(): +async def test_list_display_video360_advertiser_link_proposals_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -22453,27 +22406,26 @@ async def test_create_custom_dimension_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension( - name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_custom_dimension() + response = await client.list_display_video360_advertiser_link_proposals() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + ) @pytest.mark.asyncio -async def test_create_custom_dimension_async_use_cached_wrapped_rpc( +async def test_list_display_video360_advertiser_link_proposals_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -22490,23 +22442,23 @@ async def test_create_custom_dimension_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_custom_dimension + client._client._transport.list_display_video360_advertiser_link_proposals in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_custom_dimension + client._client._transport.list_display_video360_advertiser_link_proposals ] = mock_object request = {} - await client.create_custom_dimension(request) + await client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_custom_dimension(request) + await client.list_display_video360_advertiser_link_proposals(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -22514,9 +22466,9 @@ async def test_create_custom_dimension_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_custom_dimension_async( +async def test_list_display_video360_advertiser_link_proposals_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateCustomDimensionRequest, + request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -22529,59 +22481,55 @@ async def test_create_custom_dimension_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension( - name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_custom_dimension(request) + response = await client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateCustomDimensionRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) - assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert isinstance( + response, pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager + ) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_create_custom_dimension_async_from_dict(): - await test_create_custom_dimension_async(request_type=dict) +async def test_list_display_video360_advertiser_link_proposals_async_from_dict(): + await test_list_display_video360_advertiser_link_proposals_async(request_type=dict) -def test_create_custom_dimension_field_headers(): +def test_list_display_video360_advertiser_link_proposals_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateCustomDimensionRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: - call.return_value = resources.CustomDimension() - client.create_custom_dimension(request) + call.return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + ) + client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -22597,25 +22545,26 @@ def test_create_custom_dimension_field_headers(): @pytest.mark.asyncio -async def test_create_custom_dimension_field_headers_async(): +async def test_list_display_video360_advertiser_link_proposals_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateCustomDimensionRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension() + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() ) - await client.create_custom_dimension(request) + await client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -22630,22 +22579,24 @@ async def test_create_custom_dimension_field_headers_async(): ) in kw["metadata"] -def test_create_custom_dimension_flattened(): +def test_list_display_video360_advertiser_link_proposals_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension() + call.return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_custom_dimension( + client.list_display_video360_advertiser_link_proposals( parent="parent_value", - custom_dimension=resources.CustomDimension(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -22655,12 +22606,9 @@ def test_create_custom_dimension_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].custom_dimension - mock_val = resources.CustomDimension(name="name_value") - assert arg == mock_val -def test_create_custom_dimension_flattened_error(): +def test_list_display_video360_advertiser_link_proposals_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -22668,34 +22616,35 @@ def test_create_custom_dimension_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_custom_dimension( - analytics_admin.CreateCustomDimensionRequest(), + client.list_display_video360_advertiser_link_proposals( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), parent="parent_value", - custom_dimension=resources.CustomDimension(name="name_value"), ) @pytest.mark.asyncio -async def test_create_custom_dimension_flattened_async(): +async def test_list_display_video360_advertiser_link_proposals_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_dimension), "__call__" + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension() + call.return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + ) call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension() + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_custom_dimension( + response = await client.list_display_video360_advertiser_link_proposals( parent="parent_value", - custom_dimension=resources.CustomDimension(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -22705,13 +22654,10 @@ async def test_create_custom_dimension_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].custom_dimension - mock_val = resources.CustomDimension(name="name_value") - assert arg == mock_val @pytest.mark.asyncio -async def test_create_custom_dimension_flattened_error_async(): +async def test_list_display_video360_advertiser_link_proposals_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -22719,21 +22665,240 @@ async def test_create_custom_dimension_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_custom_dimension( - analytics_admin.CreateCustomDimensionRequest(), + await client.list_display_video360_advertiser_link_proposals( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), parent="parent_value", - custom_dimension=resources.CustomDimension(name="name_value"), ) +def test_list_display_video360_advertiser_link_proposals_pager( + transport_name: str = "grpc", +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="abc", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token="def", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_display_video360_advertiser_link_proposals( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) + for i in results + ) + + +def test_list_display_video360_advertiser_link_proposals_pages( + transport_name: str = "grpc", +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="abc", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token="def", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + pages = list( + client.list_display_video360_advertiser_link_proposals(request={}).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="abc", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token="def", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_display_video360_advertiser_link_proposals( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="abc", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token="def", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_display_video360_advertiser_link_proposals(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateCustomDimensionRequest, + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_update_custom_dimension(request_type, transport: str = "grpc"): +def test_create_display_video360_advertiser_link_proposal( + request_type, transport: str = "grpc" +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -22745,36 +22910,33 @@ def test_update_custom_dimension(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension( + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) - response = client.update_custom_dimension(request) + response = client.create_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateCustomDimensionRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" -def test_update_custom_dimension_empty_call(): +def test_create_display_video360_advertiser_link_proposal_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -22784,18 +22946,22 @@ def test_update_custom_dimension_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_custom_dimension() + client.create_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + ) -def test_update_custom_dimension_non_empty_request_with_auto_populated_field(): +def test_create_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -22806,22 +22972,29 @@ def test_update_custom_dimension_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateCustomDimensionRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + parent="parent_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_custom_dimension(request=request) + client.create_display_video360_advertiser_link_proposal(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + assert args[ + 0 + ] == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + parent="parent_value", + ) -def test_update_custom_dimension_use_cached_wrapped_rpc(): +def test_create_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -22836,7 +23009,7 @@ def test_update_custom_dimension_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_custom_dimension + client._transport.create_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -22846,15 +23019,15 @@ def test_update_custom_dimension_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_custom_dimension + client._transport.create_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.update_custom_dimension(request) + client.create_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_custom_dimension(request) + client.create_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -22862,7 +23035,7 @@ def test_update_custom_dimension_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_custom_dimension_empty_call_async(): +async def test_create_display_video360_advertiser_link_proposal_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -22872,27 +23045,29 @@ async def test_update_custom_dimension_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension( + resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) ) - response = await client.update_custom_dimension() + response = await client.create_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + ) @pytest.mark.asyncio -async def test_update_custom_dimension_async_use_cached_wrapped_rpc( +async def test_create_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -22909,23 +23084,23 @@ async def test_update_custom_dimension_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_custom_dimension + client._client._transport.create_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_custom_dimension + client._client._transport.create_display_video360_advertiser_link_proposal ] = mock_object request = {} - await client.update_custom_dimension(request) + await client.create_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_custom_dimension(request) + await client.create_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -22933,9 +23108,9 @@ async def test_update_custom_dimension_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_custom_dimension_async( +async def test_create_display_video360_advertiser_link_proposal_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateCustomDimensionRequest, + request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -22948,59 +23123,59 @@ async def test_update_custom_dimension_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension( + resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) ) - response = await client.update_custom_dimension(request) + response = await client.create_display_video360_advertiser_link_proposal( + request + ) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateCustomDimensionRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" @pytest.mark.asyncio -async def test_update_custom_dimension_async_from_dict(): - await test_update_custom_dimension_async(request_type=dict) +async def test_create_display_video360_advertiser_link_proposal_async_from_dict(): + await test_create_display_video360_advertiser_link_proposal_async(request_type=dict) -def test_update_custom_dimension_field_headers(): +def test_create_display_video360_advertiser_link_proposal_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateCustomDimensionRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() - request.custom_dimension.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: - call.return_value = resources.CustomDimension() - client.update_custom_dimension(request) + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + client.create_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -23011,30 +23186,31 @@ def test_update_custom_dimension_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "custom_dimension.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_custom_dimension_field_headers_async(): +async def test_create_display_video360_advertiser_link_proposal_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateCustomDimensionRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() - request.custom_dimension.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension() + resources.DisplayVideo360AdvertiserLinkProposal() ) - await client.update_custom_dimension(request) + await client.create_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -23045,41 +23221,44 @@ async def test_update_custom_dimension_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "custom_dimension.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_custom_dimension_flattened(): +def test_create_display_video360_advertiser_link_proposal_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension() + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_custom_dimension( - custom_dimension=resources.CustomDimension(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_display_video360_advertiser_link_proposal( + parent="parent_value", + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value" + ), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].custom_dimension - mock_val = resources.CustomDimension(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].display_video_360_advertiser_link_proposal + mock_val = resources.DisplayVideo360AdvertiserLinkProposal(name="name_value") assert arg == mock_val -def test_update_custom_dimension_flattened_error(): +def test_create_display_video360_advertiser_link_proposal_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -23087,50 +23266,55 @@ def test_update_custom_dimension_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_custom_dimension( - analytics_admin.UpdateCustomDimensionRequest(), - custom_dimension=resources.CustomDimension(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_display_video360_advertiser_link_proposal( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + parent="parent_value", + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value" + ), ) @pytest.mark.asyncio -async def test_update_custom_dimension_flattened_async(): +async def test_create_display_video360_advertiser_link_proposal_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_dimension), "__call__" + type(client.transport.create_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension() + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension() + resources.DisplayVideo360AdvertiserLinkProposal() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_custom_dimension( - custom_dimension=resources.CustomDimension(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.create_display_video360_advertiser_link_proposal( + parent="parent_value", + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value" + ), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].custom_dimension - mock_val = resources.CustomDimension(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].display_video_360_advertiser_link_proposal + mock_val = resources.DisplayVideo360AdvertiserLinkProposal(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_update_custom_dimension_flattened_error_async(): +async def test_create_display_video360_advertiser_link_proposal_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -23138,21 +23322,25 @@ async def test_update_custom_dimension_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_custom_dimension( - analytics_admin.UpdateCustomDimensionRequest(), - custom_dimension=resources.CustomDimension(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.create_display_video360_advertiser_link_proposal( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + parent="parent_value", + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value" + ), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListCustomDimensionsRequest, + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_list_custom_dimensions(request_type, transport: str = "grpc"): +def test_delete_display_video360_advertiser_link_proposal( + request_type, transport: str = "grpc" +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -23164,26 +23352,24 @@ def test_list_custom_dimensions(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCustomDimensionsResponse( - next_page_token="next_page_token_value", - ) - response = client.list_custom_dimensions(request) + call.return_value = None + response = client.delete_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListCustomDimensionsRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomDimensionsPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_custom_dimensions_empty_call(): +def test_delete_display_video360_advertiser_link_proposal_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -23193,18 +23379,22 @@ def test_list_custom_dimensions_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_custom_dimensions() + client.delete_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCustomDimensionsRequest() + assert ( + args[0] + == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + ) -def test_list_custom_dimensions_non_empty_request_with_auto_populated_field(): +def test_delete_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -23215,28 +23405,29 @@ def test_list_custom_dimensions_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListCustomDimensionsRequest( - parent="parent_value", - page_token="page_token_value", + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_custom_dimensions(request=request) + client.delete_display_video360_advertiser_link_proposal(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCustomDimensionsRequest( - parent="parent_value", - page_token="page_token_value", + assert args[ + 0 + ] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + name="name_value", ) -def test_list_custom_dimensions_use_cached_wrapped_rpc(): +def test_delete_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -23251,7 +23442,7 @@ def test_list_custom_dimensions_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_custom_dimensions + client._transport.delete_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -23261,15 +23452,15 @@ def test_list_custom_dimensions_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_custom_dimensions + client._transport.delete_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.list_custom_dimensions(request) + client.delete_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_custom_dimensions(request) + client.delete_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -23277,7 +23468,7 @@ def test_list_custom_dimensions_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_custom_dimensions_empty_call_async(): +async def test_delete_display_video360_advertiser_link_proposal_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -23287,22 +23478,22 @@ async def test_list_custom_dimensions_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomDimensionsResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_custom_dimensions() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCustomDimensionsRequest() + assert ( + args[0] + == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + ) @pytest.mark.asyncio -async def test_list_custom_dimensions_async_use_cached_wrapped_rpc( +async def test_delete_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -23319,23 +23510,23 @@ async def test_list_custom_dimensions_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_custom_dimensions + client._client._transport.delete_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_custom_dimensions + client._client._transport.delete_display_video360_advertiser_link_proposal ] = mock_object request = {} - await client.list_custom_dimensions(request) + await client.delete_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_custom_dimensions(request) + await client.delete_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -23343,9 +23534,9 @@ async def test_list_custom_dimensions_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_custom_dimensions_async( +async def test_delete_display_video360_advertiser_link_proposal_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListCustomDimensionsRequest, + request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23358,49 +23549,48 @@ async def test_list_custom_dimensions_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomDimensionsResponse( - next_page_token="next_page_token_value", - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_display_video360_advertiser_link_proposal( + request ) - response = await client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListCustomDimensionsRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomDimensionsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response is None @pytest.mark.asyncio -async def test_list_custom_dimensions_async_from_dict(): - await test_list_custom_dimensions_async(request_type=dict) +async def test_delete_display_video360_advertiser_link_proposal_async_from_dict(): + await test_delete_display_video360_advertiser_link_proposal_async(request_type=dict) -def test_list_custom_dimensions_field_headers(): +def test_delete_display_video360_advertiser_link_proposal_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListCustomDimensionsRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: - call.return_value = analytics_admin.ListCustomDimensionsResponse() - client.list_custom_dimensions(request) + call.return_value = None + client.delete_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -23411,30 +23601,29 @@ def test_list_custom_dimensions_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_custom_dimensions_field_headers_async(): +async def test_delete_display_video360_advertiser_link_proposal_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListCustomDimensionsRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomDimensionsResponse() - ) - await client.list_custom_dimensions(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -23445,37 +23634,38 @@ async def test_list_custom_dimensions_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_custom_dimensions_flattened(): +def test_delete_display_video360_advertiser_link_proposal_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCustomDimensionsResponse() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_custom_dimensions( - parent="parent_value", + client.delete_display_video360_advertiser_link_proposal( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_custom_dimensions_flattened_error(): +def test_delete_display_video360_advertiser_link_proposal_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -23483,45 +23673,44 @@ def test_list_custom_dimensions_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_custom_dimensions( - analytics_admin.ListCustomDimensionsRequest(), - parent="parent_value", + client.delete_display_video360_advertiser_link_proposal( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_custom_dimensions_flattened_async(): +async def test_delete_display_video360_advertiser_link_proposal_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" + type(client.transport.delete_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCustomDimensionsResponse() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomDimensionsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_custom_dimensions( - parent="parent_value", + response = await client.delete_display_video360_advertiser_link_proposal( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_custom_dimensions_flattened_error_async(): +async def test_delete_display_video360_advertiser_link_proposal_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -23529,222 +23718,22 @@ async def test_list_custom_dimensions_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_custom_dimensions( - analytics_admin.ListCustomDimensionsRequest(), - parent="parent_value", - ) - - -def test_list_custom_dimensions_pager(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - resources.CustomDimension(), - ], - next_page_token="abc", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[], - next_page_token="def", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_custom_dimensions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CustomDimension) for i in results) - - -def test_list_custom_dimensions_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_custom_dimensions), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - resources.CustomDimension(), - ], - next_page_token="abc", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[], - next_page_token="def", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - ], - ), - RuntimeError, - ) - pages = list(client.list_custom_dimensions(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_custom_dimensions_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_custom_dimensions), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - resources.CustomDimension(), - ], - next_page_token="abc", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[], - next_page_token="def", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_custom_dimensions( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.CustomDimension) for i in responses) - - -@pytest.mark.asyncio -async def test_list_custom_dimensions_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_custom_dimensions), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - resources.CustomDimension(), - ], - next_page_token="abc", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[], - next_page_token="def", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - ], - ), - RuntimeError, + await client.delete_display_video360_advertiser_link_proposal( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + name="name_value", ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_custom_dimensions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.ArchiveCustomDimensionRequest, + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_archive_custom_dimension(request_type, transport: str = "grpc"): +def test_approve_display_video360_advertiser_link_proposal( + request_type, transport: str = "grpc" +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -23756,23 +23745,28 @@ def test_archive_custom_dimension(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.archive_custom_dimension(request) + call.return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) + response = client.approve_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ArchiveCustomDimensionRequest() + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance( + response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse + ) -def test_archive_custom_dimension_empty_call(): +def test_approve_display_video360_advertiser_link_proposal_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -23782,18 +23776,22 @@ def test_archive_custom_dimension_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.archive_custom_dimension() + client.approve_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + ) -def test_archive_custom_dimension_non_empty_request_with_auto_populated_field(): +def test_approve_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -23804,26 +23802,29 @@ def test_archive_custom_dimension_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ArchiveCustomDimensionRequest( + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.archive_custom_dimension(request=request) + client.approve_display_video360_advertiser_link_proposal(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveCustomDimensionRequest( + assert args[ + 0 + ] == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) -def test_archive_custom_dimension_use_cached_wrapped_rpc(): +def test_approve_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -23838,7 +23839,7 @@ def test_archive_custom_dimension_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.archive_custom_dimension + client._transport.approve_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -23848,15 +23849,15 @@ def test_archive_custom_dimension_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.archive_custom_dimension + client._transport.approve_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.archive_custom_dimension(request) + client.approve_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.archive_custom_dimension(request) + client.approve_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -23864,7 +23865,7 @@ def test_archive_custom_dimension_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_archive_custom_dimension_empty_call_async(): +async def test_approve_display_video360_advertiser_link_proposal_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -23874,18 +23875,24 @@ async def test_archive_custom_dimension_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.archive_custom_dimension() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) + response = await client.approve_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + ) @pytest.mark.asyncio -async def test_archive_custom_dimension_async_use_cached_wrapped_rpc( +async def test_approve_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -23902,23 +23909,23 @@ async def test_archive_custom_dimension_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.archive_custom_dimension + client._client._transport.approve_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.archive_custom_dimension + client._client._transport.approve_display_video360_advertiser_link_proposal ] = mock_object request = {} - await client.archive_custom_dimension(request) + await client.approve_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.archive_custom_dimension(request) + await client.approve_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -23926,9 +23933,9 @@ async def test_archive_custom_dimension_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_archive_custom_dimension_async( +async def test_approve_display_video360_advertiser_link_proposal_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ArchiveCustomDimensionRequest, + request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -23941,44 +23948,56 @@ async def test_archive_custom_dimension_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.archive_custom_dimension(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) + response = await client.approve_display_video360_advertiser_link_proposal( + request + ) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ArchiveCustomDimensionRequest() + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance( + response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse + ) @pytest.mark.asyncio -async def test_archive_custom_dimension_async_from_dict(): - await test_archive_custom_dimension_async(request_type=dict) +async def test_approve_display_video360_advertiser_link_proposal_async_from_dict(): + await test_approve_display_video360_advertiser_link_proposal_async( + request_type=dict + ) -def test_archive_custom_dimension_field_headers(): +def test_approve_display_video360_advertiser_link_proposal_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ArchiveCustomDimensionRequest() + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: - call.return_value = None - client.archive_custom_dimension(request) + call.return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) + client.approve_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -23994,23 +24013,26 @@ def test_archive_custom_dimension_field_headers(): @pytest.mark.asyncio -async def test_archive_custom_dimension_field_headers_async(): +async def test_approve_display_video360_advertiser_link_proposal_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ArchiveCustomDimensionRequest() + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.approve_display_video360_advertiser_link_proposal), + "__call__", ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.archive_custom_dimension(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) + await client.approve_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -24025,139 +24047,54 @@ async def test_archive_custom_dimension_field_headers_async(): ) in kw["metadata"] -def test_archive_custom_dimension_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, + dict, + ], +) +def test_cancel_display_video360_advertiser_link_proposal( + request_type, transport: str = "grpc" +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.archive_custom_dimension( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_archive_custom_dimension_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.archive_custom_dimension( - analytics_admin.ArchiveCustomDimensionRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_archive_custom_dimension_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.archive_custom_dimension), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.archive_custom_dimension( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_archive_custom_dimension_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.archive_custom_dimension( - analytics_admin.ArchiveCustomDimensionRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetCustomDimensionRequest, - dict, - ], -) -def test_get_custom_dimension(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension( + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) - response = client.get_custom_dimension(request) + response = client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetCustomDimensionRequest() + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" -def test_get_custom_dimension_empty_call(): +def test_cancel_display_video360_advertiser_link_proposal_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -24167,18 +24104,22 @@ def test_get_custom_dimension_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_custom_dimension() + client.cancel_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + ) -def test_get_custom_dimension_non_empty_request_with_auto_populated_field(): +def test_cancel_display_video360_advertiser_link_proposal_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -24189,26 +24130,29 @@ def test_get_custom_dimension_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetCustomDimensionRequest( + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_custom_dimension(request=request) + client.cancel_display_video360_advertiser_link_proposal(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCustomDimensionRequest( + assert args[ + 0 + ] == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) -def test_get_custom_dimension_use_cached_wrapped_rpc(): +def test_cancel_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -24223,7 +24167,8 @@ def test_get_custom_dimension_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_custom_dimension in client._transport._wrapped_methods + client._transport.cancel_display_video360_advertiser_link_proposal + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -24232,15 +24177,15 @@ def test_get_custom_dimension_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_custom_dimension + client._transport.cancel_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.get_custom_dimension(request) + client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_custom_dimension(request) + client.cancel_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -24248,7 +24193,7 @@ def test_get_custom_dimension_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_custom_dimension_empty_call_async(): +async def test_cancel_display_video360_advertiser_link_proposal_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -24258,27 +24203,29 @@ async def test_get_custom_dimension_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension( + resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) ) - response = await client.get_custom_dimension() + response = await client.cancel_display_video360_advertiser_link_proposal() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCustomDimensionRequest() + assert ( + args[0] + == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + ) @pytest.mark.asyncio -async def test_get_custom_dimension_async_use_cached_wrapped_rpc( +async def test_cancel_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -24295,23 +24242,23 @@ async def test_get_custom_dimension_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_custom_dimension + client._client._transport.cancel_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_custom_dimension + client._client._transport.cancel_display_video360_advertiser_link_proposal ] = mock_object request = {} - await client.get_custom_dimension(request) + await client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_custom_dimension(request) + await client.cancel_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -24319,9 +24266,9 @@ async def test_get_custom_dimension_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_custom_dimension_async( +async def test_cancel_display_video360_advertiser_link_proposal_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetCustomDimensionRequest, + request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24334,59 +24281,59 @@ async def test_get_custom_dimension_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension( + resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) ) - response = await client.get_custom_dimension(request) + response = await client.cancel_display_video360_advertiser_link_proposal( + request + ) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetCustomDimensionRequest() + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" @pytest.mark.asyncio -async def test_get_custom_dimension_async_from_dict(): - await test_get_custom_dimension_async(request_type=dict) +async def test_cancel_display_video360_advertiser_link_proposal_async_from_dict(): + await test_cancel_display_video360_advertiser_link_proposal_async(request_type=dict) -def test_get_custom_dimension_field_headers(): +def test_cancel_display_video360_advertiser_link_proposal_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetCustomDimensionRequest() + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: - call.return_value = resources.CustomDimension() - client.get_custom_dimension(request) + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -24402,25 +24349,26 @@ def test_get_custom_dimension_field_headers(): @pytest.mark.asyncio -async def test_get_custom_dimension_field_headers_async(): +async def test_cancel_display_video360_advertiser_link_proposal_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetCustomDimensionRequest() + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" + type(client.transport.cancel_display_video360_advertiser_link_proposal), + "__call__", ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension() + resources.DisplayVideo360AdvertiserLinkProposal() ) - await client.get_custom_dimension(request) + await client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -24435,100 +24383,14 @@ async def test_get_custom_dimension_field_headers_async(): ) in kw["metadata"] -def test_get_custom_dimension_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_custom_dimension( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_get_custom_dimension_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_custom_dimension( - analytics_admin.GetCustomDimensionRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_get_custom_dimension_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_custom_dimension), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CustomDimension() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomDimension() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_custom_dimension( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_get_custom_dimension_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_custom_dimension( - analytics_admin.GetCustomDimensionRequest(), - name="name_value", - ) - - @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateCustomMetricRequest, + analytics_admin.CreateCustomDimensionRequest, dict, ], ) -def test_create_custom_metric(request_type, transport: str = "grpc"): +def test_create_custom_dimension(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -24540,42 +24402,36 @@ def test_create_custom_metric(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric( + call.return_value = resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) - response = client.create_custom_metric(request) + response = client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateCustomMetricRequest() + request = analytics_admin.CreateCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True -def test_create_custom_metric_empty_call(): +def test_create_custom_dimension_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -24585,18 +24441,18 @@ def test_create_custom_metric_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_custom_metric() + client.create_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCustomMetricRequest() + assert args[0] == analytics_admin.CreateCustomDimensionRequest() -def test_create_custom_metric_non_empty_request_with_auto_populated_field(): +def test_create_custom_dimension_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -24607,26 +24463,26 @@ def test_create_custom_metric_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateCustomMetricRequest( + request = analytics_admin.CreateCustomDimensionRequest( parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_custom_metric(request=request) + client.create_custom_dimension(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCustomMetricRequest( + assert args[0] == analytics_admin.CreateCustomDimensionRequest( parent="parent_value", ) -def test_create_custom_metric_use_cached_wrapped_rpc(): +def test_create_custom_dimension_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -24641,7 +24497,8 @@ def test_create_custom_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_custom_metric in client._transport._wrapped_methods + client._transport.create_custom_dimension + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -24650,15 +24507,15 @@ def test_create_custom_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_custom_metric + client._transport.create_custom_dimension ] = mock_rpc request = {} - client.create_custom_metric(request) + client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_metric(request) + client.create_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -24666,7 +24523,7 @@ def test_create_custom_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_custom_metric_empty_call_async(): +async def test_create_custom_dimension_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -24676,30 +24533,27 @@ async def test_create_custom_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric( + resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) ) - response = await client.create_custom_metric() + response = await client.create_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCustomMetricRequest() + assert args[0] == analytics_admin.CreateCustomDimensionRequest() @pytest.mark.asyncio -async def test_create_custom_metric_async_use_cached_wrapped_rpc( +async def test_create_custom_dimension_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -24716,23 +24570,23 @@ async def test_create_custom_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_custom_metric + client._client._transport.create_custom_dimension in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_custom_metric + client._client._transport.create_custom_dimension ] = mock_object request = {} - await client.create_custom_metric(request) + await client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_custom_metric(request) + await client.create_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -24740,9 +24594,9 @@ async def test_create_custom_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_custom_metric_async( +async def test_create_custom_dimension_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateCustomMetricRequest, + request_type=analytics_admin.CreateCustomDimensionRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24755,65 +24609,59 @@ async def test_create_custom_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric( + resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) ) - response = await client.create_custom_metric(request) + response = await client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateCustomMetricRequest() + request = analytics_admin.CreateCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True @pytest.mark.asyncio -async def test_create_custom_metric_async_from_dict(): - await test_create_custom_metric_async(request_type=dict) +async def test_create_custom_dimension_async_from_dict(): + await test_create_custom_dimension_async(request_type=dict) -def test_create_custom_metric_field_headers(): +def test_create_custom_dimension_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateCustomMetricRequest() + request = analytics_admin.CreateCustomDimensionRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: - call.return_value = resources.CustomMetric() - client.create_custom_metric(request) + call.return_value = resources.CustomDimension() + client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -24829,25 +24677,25 @@ def test_create_custom_metric_field_headers(): @pytest.mark.asyncio -async def test_create_custom_metric_field_headers_async(): +async def test_create_custom_dimension_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateCustomMetricRequest() + request = analytics_admin.CreateCustomDimensionRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric() + resources.CustomDimension() ) - await client.create_custom_metric(request) + await client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -24862,22 +24710,22 @@ async def test_create_custom_metric_field_headers_async(): ) in kw["metadata"] -def test_create_custom_metric_flattened(): +def test_create_custom_dimension_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric() + call.return_value = resources.CustomDimension() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_custom_metric( + client.create_custom_dimension( parent="parent_value", - custom_metric=resources.CustomMetric(name="name_value"), + custom_dimension=resources.CustomDimension(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -24887,12 +24735,12 @@ def test_create_custom_metric_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].custom_metric - mock_val = resources.CustomMetric(name="name_value") + arg = args[0].custom_dimension + mock_val = resources.CustomDimension(name="name_value") assert arg == mock_val -def test_create_custom_metric_flattened_error(): +def test_create_custom_dimension_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -24900,34 +24748,34 @@ def test_create_custom_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_custom_metric( - analytics_admin.CreateCustomMetricRequest(), + client.create_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), parent="parent_value", - custom_metric=resources.CustomMetric(name="name_value"), + custom_dimension=resources.CustomDimension(name="name_value"), ) @pytest.mark.asyncio -async def test_create_custom_metric_flattened_async(): +async def test_create_custom_dimension_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_custom_metric), "__call__" + type(client.transport.create_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric() + call.return_value = resources.CustomDimension() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric() + resources.CustomDimension() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_custom_metric( + response = await client.create_custom_dimension( parent="parent_value", - custom_metric=resources.CustomMetric(name="name_value"), + custom_dimension=resources.CustomDimension(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -24937,13 +24785,13 @@ async def test_create_custom_metric_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].custom_metric - mock_val = resources.CustomMetric(name="name_value") + arg = args[0].custom_dimension + mock_val = resources.CustomDimension(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_create_custom_metric_flattened_error_async(): +async def test_create_custom_dimension_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -24951,21 +24799,21 @@ async def test_create_custom_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_custom_metric( - analytics_admin.CreateCustomMetricRequest(), + await client.create_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), parent="parent_value", - custom_metric=resources.CustomMetric(name="name_value"), + custom_dimension=resources.CustomDimension(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateCustomMetricRequest, + analytics_admin.UpdateCustomDimensionRequest, dict, ], ) -def test_update_custom_metric(request_type, transport: str = "grpc"): +def test_update_custom_dimension(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -24977,42 +24825,36 @@ def test_update_custom_metric(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric( + call.return_value = resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) - response = client.update_custom_metric(request) + response = client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateCustomMetricRequest() + request = analytics_admin.UpdateCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True -def test_update_custom_metric_empty_call(): +def test_update_custom_dimension_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -25022,18 +24864,18 @@ def test_update_custom_metric_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_custom_metric() + client.update_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCustomMetricRequest() + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() -def test_update_custom_metric_non_empty_request_with_auto_populated_field(): +def test_update_custom_dimension_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -25044,22 +24886,22 @@ def test_update_custom_metric_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateCustomMetricRequest() + request = analytics_admin.UpdateCustomDimensionRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_custom_metric(request=request) + client.update_custom_dimension(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCustomMetricRequest() + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() -def test_update_custom_metric_use_cached_wrapped_rpc(): +def test_update_custom_dimension_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -25074,7 +24916,8 @@ def test_update_custom_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_custom_metric in client._transport._wrapped_methods + client._transport.update_custom_dimension + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -25083,15 +24926,15 @@ def test_update_custom_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_custom_metric + client._transport.update_custom_dimension ] = mock_rpc request = {} - client.update_custom_metric(request) + client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_custom_metric(request) + client.update_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -25099,7 +24942,7 @@ def test_update_custom_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_custom_metric_empty_call_async(): +async def test_update_custom_dimension_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -25109,30 +24952,27 @@ async def test_update_custom_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric( + resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) ) - response = await client.update_custom_metric() + response = await client.update_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCustomMetricRequest() + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() @pytest.mark.asyncio -async def test_update_custom_metric_async_use_cached_wrapped_rpc( +async def test_update_custom_dimension_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -25149,23 +24989,23 @@ async def test_update_custom_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_custom_metric + client._client._transport.update_custom_dimension in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_custom_metric + client._client._transport.update_custom_dimension ] = mock_object request = {} - await client.update_custom_metric(request) + await client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_custom_metric(request) + await client.update_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -25173,9 +25013,9 @@ async def test_update_custom_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_custom_metric_async( +async def test_update_custom_dimension_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateCustomMetricRequest, + request_type=analytics_admin.UpdateCustomDimensionRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -25188,65 +25028,59 @@ async def test_update_custom_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric( + resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) ) - response = await client.update_custom_metric(request) + response = await client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateCustomMetricRequest() + request = analytics_admin.UpdateCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True @pytest.mark.asyncio -async def test_update_custom_metric_async_from_dict(): - await test_update_custom_metric_async(request_type=dict) +async def test_update_custom_dimension_async_from_dict(): + await test_update_custom_dimension_async(request_type=dict) -def test_update_custom_metric_field_headers(): +def test_update_custom_dimension_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateCustomMetricRequest() + request = analytics_admin.UpdateCustomDimensionRequest() - request.custom_metric.name = "name_value" + request.custom_dimension.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: - call.return_value = resources.CustomMetric() - client.update_custom_metric(request) + call.return_value = resources.CustomDimension() + client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -25257,30 +25091,30 @@ def test_update_custom_metric_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "custom_metric.name=name_value", + "custom_dimension.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_custom_metric_field_headers_async(): +async def test_update_custom_dimension_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateCustomMetricRequest() + request = analytics_admin.UpdateCustomDimensionRequest() - request.custom_metric.name = "name_value" + request.custom_dimension.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric() + resources.CustomDimension() ) - await client.update_custom_metric(request) + await client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -25291,25 +25125,25 @@ async def test_update_custom_metric_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "custom_metric.name=name_value", + "custom_dimension.name=name_value", ) in kw["metadata"] -def test_update_custom_metric_flattened(): +def test_update_custom_dimension_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric() + call.return_value = resources.CustomDimension() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_custom_metric( - custom_metric=resources.CustomMetric(name="name_value"), + client.update_custom_dimension( + custom_dimension=resources.CustomDimension(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -25317,15 +25151,15 @@ def test_update_custom_metric_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].custom_metric - mock_val = resources.CustomMetric(name="name_value") + arg = args[0].custom_dimension + mock_val = resources.CustomDimension(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_update_custom_metric_flattened_error(): +def test_update_custom_dimension_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -25333,33 +25167,33 @@ def test_update_custom_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_custom_metric( - analytics_admin.UpdateCustomMetricRequest(), - custom_metric=resources.CustomMetric(name="name_value"), + client.update_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_custom_metric_flattened_async(): +async def test_update_custom_dimension_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_custom_metric), "__call__" + type(client.transport.update_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric() + call.return_value = resources.CustomDimension() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric() + resources.CustomDimension() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_custom_metric( - custom_metric=resources.CustomMetric(name="name_value"), + response = await client.update_custom_dimension( + custom_dimension=resources.CustomDimension(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -25367,8 +25201,8 @@ async def test_update_custom_metric_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].custom_metric - mock_val = resources.CustomMetric(name="name_value") + arg = args[0].custom_dimension + mock_val = resources.CustomDimension(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -25376,7 +25210,7 @@ async def test_update_custom_metric_flattened_async(): @pytest.mark.asyncio -async def test_update_custom_metric_flattened_error_async(): +async def test_update_custom_dimension_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -25384,9 +25218,9 @@ async def test_update_custom_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_custom_metric( - analytics_admin.UpdateCustomMetricRequest(), - custom_metric=resources.CustomMetric(name="name_value"), + await client.update_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -25394,11 +25228,11 @@ async def test_update_custom_metric_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListCustomMetricsRequest, + analytics_admin.ListCustomDimensionsRequest, dict, ], ) -def test_list_custom_metrics(request_type, transport: str = "grpc"): +def test_list_custom_dimensions(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -25410,26 +25244,26 @@ def test_list_custom_metrics(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCustomMetricsResponse( + call.return_value = analytics_admin.ListCustomDimensionsResponse( next_page_token="next_page_token_value", ) - response = client.list_custom_metrics(request) + response = client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListCustomMetricsRequest() + request = analytics_admin.ListCustomDimensionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomMetricsPager) + assert isinstance(response, pagers.ListCustomDimensionsPager) assert response.next_page_token == "next_page_token_value" -def test_list_custom_metrics_empty_call(): +def test_list_custom_dimensions_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -25439,18 +25273,18 @@ def test_list_custom_metrics_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_custom_metrics() + client.list_custom_dimensions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCustomMetricsRequest() + assert args[0] == analytics_admin.ListCustomDimensionsRequest() -def test_list_custom_metrics_non_empty_request_with_auto_populated_field(): +def test_list_custom_dimensions_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -25461,28 +25295,28 @@ def test_list_custom_metrics_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListCustomMetricsRequest( + request = analytics_admin.ListCustomDimensionsRequest( parent="parent_value", page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_custom_metrics(request=request) + client.list_custom_dimensions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCustomMetricsRequest( + assert args[0] == analytics_admin.ListCustomDimensionsRequest( parent="parent_value", page_token="page_token_value", ) -def test_list_custom_metrics_use_cached_wrapped_rpc(): +def test_list_custom_dimensions_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -25497,7 +25331,8 @@ def test_list_custom_metrics_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_custom_metrics in client._transport._wrapped_methods + client._transport.list_custom_dimensions + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -25506,15 +25341,15 @@ def test_list_custom_metrics_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_custom_metrics + client._transport.list_custom_dimensions ] = mock_rpc request = {} - client.list_custom_metrics(request) + client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_custom_metrics(request) + client.list_custom_dimensions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -25522,7 +25357,7 @@ def test_list_custom_metrics_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_custom_metrics_empty_call_async(): +async def test_list_custom_dimensions_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -25532,22 +25367,22 @@ async def test_list_custom_metrics_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomMetricsResponse( + analytics_admin.ListCustomDimensionsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_custom_metrics() + response = await client.list_custom_dimensions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCustomMetricsRequest() + assert args[0] == analytics_admin.ListCustomDimensionsRequest() @pytest.mark.asyncio -async def test_list_custom_metrics_async_use_cached_wrapped_rpc( +async def test_list_custom_dimensions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -25564,23 +25399,23 @@ async def test_list_custom_metrics_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_custom_metrics + client._client._transport.list_custom_dimensions in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_custom_metrics + client._client._transport.list_custom_dimensions ] = mock_object request = {} - await client.list_custom_metrics(request) + await client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_custom_metrics(request) + await client.list_custom_dimensions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -25588,9 +25423,9 @@ async def test_list_custom_metrics_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_custom_metrics_async( +async def test_list_custom_dimensions_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListCustomMetricsRequest, + request_type=analytics_admin.ListCustomDimensionsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -25603,49 +25438,49 @@ async def test_list_custom_metrics_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomMetricsResponse( + analytics_admin.ListCustomDimensionsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_custom_metrics(request) + response = await client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListCustomMetricsRequest() + request = analytics_admin.ListCustomDimensionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomMetricsAsyncPager) + assert isinstance(response, pagers.ListCustomDimensionsAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_list_custom_metrics_async_from_dict(): - await test_list_custom_metrics_async(request_type=dict) +async def test_list_custom_dimensions_async_from_dict(): + await test_list_custom_dimensions_async(request_type=dict) -def test_list_custom_metrics_field_headers(): +def test_list_custom_dimensions_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListCustomMetricsRequest() + request = analytics_admin.ListCustomDimensionsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: - call.return_value = analytics_admin.ListCustomMetricsResponse() - client.list_custom_metrics(request) + call.return_value = analytics_admin.ListCustomDimensionsResponse() + client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -25661,25 +25496,25 @@ def test_list_custom_metrics_field_headers(): @pytest.mark.asyncio -async def test_list_custom_metrics_field_headers_async(): +async def test_list_custom_dimensions_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListCustomMetricsRequest() + request = analytics_admin.ListCustomDimensionsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomMetricsResponse() + analytics_admin.ListCustomDimensionsResponse() ) - await client.list_custom_metrics(request) + await client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -25694,20 +25529,20 @@ async def test_list_custom_metrics_field_headers_async(): ) in kw["metadata"] -def test_list_custom_metrics_flattened(): +def test_list_custom_dimensions_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCustomMetricsResponse() + call.return_value = analytics_admin.ListCustomDimensionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_custom_metrics( + client.list_custom_dimensions( parent="parent_value", ) @@ -25720,7 +25555,7 @@ def test_list_custom_metrics_flattened(): assert arg == mock_val -def test_list_custom_metrics_flattened_error(): +def test_list_custom_dimensions_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -25728,31 +25563,31 @@ def test_list_custom_metrics_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_custom_metrics( - analytics_admin.ListCustomMetricsRequest(), + client.list_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_custom_metrics_flattened_async(): +async def test_list_custom_dimensions_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCustomMetricsResponse() + call.return_value = analytics_admin.ListCustomDimensionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCustomMetricsResponse() + analytics_admin.ListCustomDimensionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_custom_metrics( + response = await client.list_custom_dimensions( parent="parent_value", ) @@ -25766,7 +25601,7 @@ async def test_list_custom_metrics_flattened_async(): @pytest.mark.asyncio -async def test_list_custom_metrics_flattened_error_async(): +async def test_list_custom_dimensions_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -25774,13 +25609,13 @@ async def test_list_custom_metrics_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_custom_metrics( - analytics_admin.ListCustomMetricsRequest(), + await client.list_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), parent="parent_value", ) -def test_list_custom_metrics_pager(transport_name: str = "grpc"): +def test_list_custom_dimensions_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -25788,32 +25623,32 @@ def test_list_custom_metrics_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), ], next_page_token="abc", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[], + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], next_page_token="def", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), ], next_page_token="ghi", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), ], ), RuntimeError, @@ -25825,7 +25660,7 @@ def test_list_custom_metrics_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_custom_metrics(request={}, retry=retry, timeout=timeout) + pager = client.list_custom_dimensions(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -25833,10 +25668,10 @@ def test_list_custom_metrics_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.CustomMetric) for i in results) + assert all(isinstance(i, resources.CustomDimension) for i in results) -def test_list_custom_metrics_pages(transport_name: str = "grpc"): +def test_list_custom_dimensions_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -25844,82 +25679,82 @@ def test_list_custom_metrics_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), "__call__" + type(client.transport.list_custom_dimensions), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), ], next_page_token="abc", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[], + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], next_page_token="def", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), ], next_page_token="ghi", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), ], ), RuntimeError, ) - pages = list(client.list_custom_metrics(request={}).pages) + pages = list(client.list_custom_dimensions(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_custom_metrics_async_pager(): +async def test_list_custom_dimensions_async_pager(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), + type(client.transport.list_custom_dimensions), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), ], next_page_token="abc", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[], + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], next_page_token="def", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), ], next_page_token="ghi", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), ], ), RuntimeError, ) - async_pager = await client.list_custom_metrics( + async_pager = await client.list_custom_dimensions( request={}, ) assert async_pager.next_page_token == "abc" @@ -25928,45 +25763,45 @@ async def test_list_custom_metrics_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, resources.CustomMetric) for i in responses) + assert all(isinstance(i, resources.CustomDimension) for i in responses) @pytest.mark.asyncio -async def test_list_custom_metrics_async_pages(): +async def test_list_custom_dimensions_async_pages(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_custom_metrics), + type(client.transport.list_custom_dimensions), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), ], next_page_token="abc", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[], + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], next_page_token="def", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), ], next_page_token="ghi", ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), ], ), RuntimeError, @@ -25975,7 +25810,7 @@ async def test_list_custom_metrics_async_pages(): # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 async for page_ in ( # pragma: no branch - await client.list_custom_metrics(request={}) + await client.list_custom_dimensions(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -25985,11 +25820,11 @@ async def test_list_custom_metrics_async_pages(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ArchiveCustomMetricRequest, + analytics_admin.ArchiveCustomDimensionRequest, dict, ], ) -def test_archive_custom_metric(request_type, transport: str = "grpc"): +def test_archive_custom_dimension(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -26001,23 +25836,23 @@ def test_archive_custom_metric(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.archive_custom_metric(request) + response = client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ArchiveCustomMetricRequest() + request = analytics_admin.ArchiveCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. assert response is None -def test_archive_custom_metric_empty_call(): +def test_archive_custom_dimension_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -26027,18 +25862,18 @@ def test_archive_custom_metric_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.archive_custom_metric() + client.archive_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() -def test_archive_custom_metric_non_empty_request_with_auto_populated_field(): +def test_archive_custom_dimension_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -26049,26 +25884,26 @@ def test_archive_custom_metric_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ArchiveCustomMetricRequest( + request = analytics_admin.ArchiveCustomDimensionRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.archive_custom_metric(request=request) + client.archive_custom_dimension(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveCustomMetricRequest( + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest( name="name_value", ) -def test_archive_custom_metric_use_cached_wrapped_rpc(): +def test_archive_custom_dimension_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -26083,7 +25918,7 @@ def test_archive_custom_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.archive_custom_metric + client._transport.archive_custom_dimension in client._transport._wrapped_methods ) @@ -26093,15 +25928,15 @@ def test_archive_custom_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.archive_custom_metric + client._transport.archive_custom_dimension ] = mock_rpc request = {} - client.archive_custom_metric(request) + client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.archive_custom_metric(request) + client.archive_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -26109,7 +25944,7 @@ def test_archive_custom_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_archive_custom_metric_empty_call_async(): +async def test_archive_custom_dimension_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -26119,18 +25954,18 @@ async def test_archive_custom_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.archive_custom_metric() + response = await client.archive_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() @pytest.mark.asyncio -async def test_archive_custom_metric_async_use_cached_wrapped_rpc( +async def test_archive_custom_dimension_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -26147,23 +25982,23 @@ async def test_archive_custom_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.archive_custom_metric + client._client._transport.archive_custom_dimension in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.archive_custom_metric + client._client._transport.archive_custom_dimension ] = mock_object request = {} - await client.archive_custom_metric(request) + await client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.archive_custom_metric(request) + await client.archive_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -26171,9 +26006,9 @@ async def test_archive_custom_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_archive_custom_metric_async( +async def test_archive_custom_dimension_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ArchiveCustomMetricRequest, + request_type=analytics_admin.ArchiveCustomDimensionRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -26186,16 +26021,16 @@ async def test_archive_custom_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.archive_custom_metric(request) + response = await client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ArchiveCustomMetricRequest() + request = analytics_admin.ArchiveCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -26203,27 +26038,27 @@ async def test_archive_custom_metric_async( @pytest.mark.asyncio -async def test_archive_custom_metric_async_from_dict(): - await test_archive_custom_metric_async(request_type=dict) +async def test_archive_custom_dimension_async_from_dict(): + await test_archive_custom_dimension_async(request_type=dict) -def test_archive_custom_metric_field_headers(): +def test_archive_custom_dimension_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ArchiveCustomMetricRequest() + request = analytics_admin.ArchiveCustomDimensionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: call.return_value = None - client.archive_custom_metric(request) + client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -26239,23 +26074,23 @@ def test_archive_custom_metric_field_headers(): @pytest.mark.asyncio -async def test_archive_custom_metric_field_headers_async(): +async def test_archive_custom_dimension_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ArchiveCustomMetricRequest() + request = analytics_admin.ArchiveCustomDimensionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.archive_custom_metric(request) + await client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -26270,20 +26105,20 @@ async def test_archive_custom_metric_field_headers_async(): ) in kw["metadata"] -def test_archive_custom_metric_flattened(): +def test_archive_custom_dimension_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.archive_custom_metric( + client.archive_custom_dimension( name="name_value", ) @@ -26296,7 +26131,7 @@ def test_archive_custom_metric_flattened(): assert arg == mock_val -def test_archive_custom_metric_flattened_error(): +def test_archive_custom_dimension_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -26304,21 +26139,21 @@ def test_archive_custom_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.archive_custom_metric( - analytics_admin.ArchiveCustomMetricRequest(), + client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_archive_custom_metric_flattened_async(): +async def test_archive_custom_dimension_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.archive_custom_metric), "__call__" + type(client.transport.archive_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -26326,7 +26161,7 @@ async def test_archive_custom_metric_flattened_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.archive_custom_metric( + response = await client.archive_custom_dimension( name="name_value", ) @@ -26340,7 +26175,7 @@ async def test_archive_custom_metric_flattened_async(): @pytest.mark.asyncio -async def test_archive_custom_metric_flattened_error_async(): +async def test_archive_custom_dimension_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -26348,8 +26183,8 @@ async def test_archive_custom_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.archive_custom_metric( - analytics_admin.ArchiveCustomMetricRequest(), + await client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), name="name_value", ) @@ -26357,11 +26192,11 @@ async def test_archive_custom_metric_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetCustomMetricRequest, + analytics_admin.GetCustomDimensionRequest, dict, ], ) -def test_get_custom_metric(request_type, transport: str = "grpc"): +def test_get_custom_dimension(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -26373,42 +26208,36 @@ def test_get_custom_metric(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric( + call.return_value = resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) - response = client.get_custom_metric(request) + response = client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetCustomMetricRequest() + request = analytics_admin.GetCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True -def test_get_custom_metric_empty_call(): +def test_get_custom_dimension_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -26418,18 +26247,18 @@ def test_get_custom_metric_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_custom_metric() + client.get_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCustomMetricRequest() + assert args[0] == analytics_admin.GetCustomDimensionRequest() -def test_get_custom_metric_non_empty_request_with_auto_populated_field(): +def test_get_custom_dimension_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -26440,26 +26269,26 @@ def test_get_custom_metric_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetCustomMetricRequest( + request = analytics_admin.GetCustomDimensionRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_custom_metric(request=request) + client.get_custom_dimension(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCustomMetricRequest( + assert args[0] == analytics_admin.GetCustomDimensionRequest( name="name_value", ) -def test_get_custom_metric_use_cached_wrapped_rpc(): +def test_get_custom_dimension_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -26473,7 +26302,9 @@ def test_get_custom_metric_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_custom_metric in client._transport._wrapped_methods + assert ( + client._transport.get_custom_dimension in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -26481,15 +26312,15 @@ def test_get_custom_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_custom_metric + client._transport.get_custom_dimension ] = mock_rpc request = {} - client.get_custom_metric(request) + client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_custom_metric(request) + client.get_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -26497,7 +26328,7 @@ def test_get_custom_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_custom_metric_empty_call_async(): +async def test_get_custom_dimension_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -26507,30 +26338,27 @@ async def test_get_custom_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric( + resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) ) - response = await client.get_custom_metric() + response = await client.get_custom_dimension() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCustomMetricRequest() + assert args[0] == analytics_admin.GetCustomDimensionRequest() @pytest.mark.asyncio -async def test_get_custom_metric_async_use_cached_wrapped_rpc( +async def test_get_custom_dimension_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -26547,23 +26375,23 @@ async def test_get_custom_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_custom_metric + client._client._transport.get_custom_dimension in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_custom_metric + client._client._transport.get_custom_dimension ] = mock_object request = {} - await client.get_custom_metric(request) + await client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_custom_metric(request) + await client.get_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -26571,8 +26399,9 @@ async def test_get_custom_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_custom_metric_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.GetCustomMetricRequest +async def test_get_custom_dimension_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.GetCustomDimensionRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -26585,65 +26414,59 @@ async def test_get_custom_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric( + resources.CustomDimension( name="name_value", parameter_name="parameter_name_value", display_name="display_name_value", description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) ) - response = await client.get_custom_metric(request) + response = await client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetCustomMetricRequest() + request = analytics_admin.GetCustomDimensionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True @pytest.mark.asyncio -async def test_get_custom_metric_async_from_dict(): - await test_get_custom_metric_async(request_type=dict) +async def test_get_custom_dimension_async_from_dict(): + await test_get_custom_dimension_async(request_type=dict) -def test_get_custom_metric_field_headers(): +def test_get_custom_dimension_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetCustomMetricRequest() + request = analytics_admin.GetCustomDimensionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: - call.return_value = resources.CustomMetric() - client.get_custom_metric(request) + call.return_value = resources.CustomDimension() + client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -26659,25 +26482,25 @@ def test_get_custom_metric_field_headers(): @pytest.mark.asyncio -async def test_get_custom_metric_field_headers_async(): +async def test_get_custom_dimension_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetCustomMetricRequest() + request = analytics_admin.GetCustomDimensionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric() + resources.CustomDimension() ) - await client.get_custom_metric(request) + await client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -26692,20 +26515,20 @@ async def test_get_custom_metric_field_headers_async(): ) in kw["metadata"] -def test_get_custom_metric_flattened(): +def test_get_custom_dimension_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric() + call.return_value = resources.CustomDimension() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_custom_metric( + client.get_custom_dimension( name="name_value", ) @@ -26718,7 +26541,7 @@ def test_get_custom_metric_flattened(): assert arg == mock_val -def test_get_custom_metric_flattened_error(): +def test_get_custom_dimension_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -26726,31 +26549,31 @@ def test_get_custom_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_custom_metric( - analytics_admin.GetCustomMetricRequest(), + client.get_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_custom_metric_flattened_async(): +async def test_get_custom_dimension_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_custom_metric), "__call__" + type(client.transport.get_custom_dimension), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CustomMetric() + call.return_value = resources.CustomDimension() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CustomMetric() + resources.CustomDimension() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_custom_metric( + response = await client.get_custom_dimension( name="name_value", ) @@ -26764,7 +26587,7 @@ async def test_get_custom_metric_flattened_async(): @pytest.mark.asyncio -async def test_get_custom_metric_flattened_error_async(): +async def test_get_custom_dimension_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -26772,8 +26595,8 @@ async def test_get_custom_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_custom_metric( - analytics_admin.GetCustomMetricRequest(), + await client.get_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), name="name_value", ) @@ -26781,11 +26604,11 @@ async def test_get_custom_metric_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDataRetentionSettingsRequest, + analytics_admin.CreateCustomMetricRequest, dict, ], ) -def test_get_data_retention_settings(request_type, transport: str = "grpc"): +def test_create_custom_metric(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -26797,33 +26620,42 @@ def test_get_data_retention_settings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRetentionSettings( + call.return_value = resources.CustomMetric( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) - response = client.get_data_retention_settings(request) + response = client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDataRetentionSettingsRequest() + request = analytics_admin.CreateCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRetentionSettings) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert ( - response.event_data_retention - == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS - ) - assert response.reset_user_data_on_new_activity is True + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] -def test_get_data_retention_settings_empty_call(): +def test_create_custom_metric_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -26833,18 +26665,18 @@ def test_get_data_retention_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_retention_settings() + client.create_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() + assert args[0] == analytics_admin.CreateCustomMetricRequest() -def test_get_data_retention_settings_non_empty_request_with_auto_populated_field(): +def test_create_custom_metric_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -26855,26 +26687,26 @@ def test_get_data_retention_settings_non_empty_request_with_auto_populated_field # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetDataRetentionSettingsRequest( - name="name_value", + request = analytics_admin.CreateCustomMetricRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_retention_settings(request=request) + client.create_custom_metric(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataRetentionSettingsRequest( - name="name_value", + assert args[0] == analytics_admin.CreateCustomMetricRequest( + parent="parent_value", ) -def test_get_data_retention_settings_use_cached_wrapped_rpc(): +def test_create_custom_metric_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -26889,8 +26721,7 @@ def test_get_data_retention_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_data_retention_settings - in client._transport._wrapped_methods + client._transport.create_custom_metric in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -26899,15 +26730,15 @@ def test_get_data_retention_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_data_retention_settings + client._transport.create_custom_metric ] = mock_rpc request = {} - client.get_data_retention_settings(request) + client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_retention_settings(request) + client.create_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -26915,7 +26746,7 @@ def test_get_data_retention_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_data_retention_settings_empty_call_async(): +async def test_create_custom_metric_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -26925,24 +26756,30 @@ async def test_get_data_retention_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings( + resources.CustomMetric( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) ) - response = await client.get_data_retention_settings() + response = await client.create_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() + assert args[0] == analytics_admin.CreateCustomMetricRequest() @pytest.mark.asyncio -async def test_get_data_retention_settings_async_use_cached_wrapped_rpc( +async def test_create_custom_metric_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -26959,23 +26796,23 @@ async def test_get_data_retention_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_data_retention_settings + client._client._transport.create_custom_metric in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_data_retention_settings + client._client._transport.create_custom_metric ] = mock_object request = {} - await client.get_data_retention_settings(request) + await client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_data_retention_settings(request) + await client.create_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -26983,9 +26820,9 @@ async def test_get_data_retention_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_data_retention_settings_async( +async def test_create_custom_metric_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetDataRetentionSettingsRequest, + request_type=analytics_admin.CreateCustomMetricRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -26998,56 +26835,65 @@ async def test_get_data_retention_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings( + resources.CustomMetric( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) ) - response = await client.get_data_retention_settings(request) + response = await client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDataRetentionSettingsRequest() + request = analytics_admin.CreateCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRetentionSettings) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert ( - response.event_data_retention - == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS - ) - assert response.reset_user_data_on_new_activity is True + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] @pytest.mark.asyncio -async def test_get_data_retention_settings_async_from_dict(): - await test_get_data_retention_settings_async(request_type=dict) +async def test_create_custom_metric_async_from_dict(): + await test_create_custom_metric_async(request_type=dict) -def test_get_data_retention_settings_field_headers(): +def test_create_custom_metric_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDataRetentionSettingsRequest() + request = analytics_admin.CreateCustomMetricRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: - call.return_value = resources.DataRetentionSettings() - client.get_data_retention_settings(request) + call.return_value = resources.CustomMetric() + client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -27058,30 +26904,30 @@ def test_get_data_retention_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_data_retention_settings_field_headers_async(): +async def test_create_custom_metric_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDataRetentionSettingsRequest() + request = analytics_admin.CreateCustomMetricRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings() + resources.CustomMetric() ) - await client.get_data_retention_settings(request) + await client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -27092,37 +26938,41 @@ async def test_get_data_retention_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_data_retention_settings_flattened(): +def test_create_custom_metric_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRetentionSettings() + call.return_value = resources.CustomMetric() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_data_retention_settings( - name="name_value", + client.create_custom_metric( + parent="parent_value", + custom_metric=resources.CustomMetric(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].custom_metric + mock_val = resources.CustomMetric(name="name_value") assert arg == mock_val -def test_get_data_retention_settings_flattened_error(): +def test_create_custom_metric_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -27130,45 +26980,50 @@ def test_get_data_retention_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_retention_settings( - analytics_admin.GetDataRetentionSettingsRequest(), - name="name_value", + client.create_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent="parent_value", + custom_metric=resources.CustomMetric(name="name_value"), ) @pytest.mark.asyncio -async def test_get_data_retention_settings_flattened_async(): +async def test_create_custom_metric_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_retention_settings), "__call__" + type(client.transport.create_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRetentionSettings() + call.return_value = resources.CustomMetric() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings() + resources.CustomMetric() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_data_retention_settings( - name="name_value", + response = await client.create_custom_metric( + parent="parent_value", + custom_metric=resources.CustomMetric(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].custom_metric + mock_val = resources.CustomMetric(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_get_data_retention_settings_flattened_error_async(): +async def test_create_custom_metric_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -27176,20 +27031,21 @@ async def test_get_data_retention_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_data_retention_settings( - analytics_admin.GetDataRetentionSettingsRequest(), - name="name_value", + await client.create_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent="parent_value", + custom_metric=resources.CustomMetric(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateDataRetentionSettingsRequest, + analytics_admin.UpdateCustomMetricRequest, dict, ], ) -def test_update_data_retention_settings(request_type, transport: str = "grpc"): +def test_update_custom_metric(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -27201,33 +27057,42 @@ def test_update_data_retention_settings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRetentionSettings( + call.return_value = resources.CustomMetric( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) - response = client.update_data_retention_settings(request) + response = client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDataRetentionSettingsRequest() + request = analytics_admin.UpdateCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRetentionSettings) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert ( - response.event_data_retention - == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS - ) - assert response.reset_user_data_on_new_activity is True + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] -def test_update_data_retention_settings_empty_call(): +def test_update_custom_metric_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -27237,18 +27102,18 @@ def test_update_data_retention_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_retention_settings() + client.update_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == analytics_admin.UpdateCustomMetricRequest() -def test_update_data_retention_settings_non_empty_request_with_auto_populated_field(): +def test_update_custom_metric_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -27259,22 +27124,22 @@ def test_update_data_retention_settings_non_empty_request_with_auto_populated_fi # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateDataRetentionSettingsRequest() + request = analytics_admin.UpdateCustomMetricRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_retention_settings(request=request) + client.update_custom_metric(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == analytics_admin.UpdateCustomMetricRequest() -def test_update_data_retention_settings_use_cached_wrapped_rpc(): +def test_update_custom_metric_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -27289,8 +27154,7 @@ def test_update_data_retention_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_retention_settings - in client._transport._wrapped_methods + client._transport.update_custom_metric in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -27299,15 +27163,15 @@ def test_update_data_retention_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_data_retention_settings + client._transport.update_custom_metric ] = mock_rpc request = {} - client.update_data_retention_settings(request) + client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_retention_settings(request) + client.update_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -27315,7 +27179,7 @@ def test_update_data_retention_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_data_retention_settings_empty_call_async(): +async def test_update_custom_metric_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -27325,24 +27189,30 @@ async def test_update_data_retention_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings( + resources.CustomMetric( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) ) - response = await client.update_data_retention_settings() + response = await client.update_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == analytics_admin.UpdateCustomMetricRequest() @pytest.mark.asyncio -async def test_update_data_retention_settings_async_use_cached_wrapped_rpc( +async def test_update_custom_metric_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -27359,23 +27229,23 @@ async def test_update_data_retention_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_data_retention_settings + client._client._transport.update_custom_metric in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_data_retention_settings + client._client._transport.update_custom_metric ] = mock_object request = {} - await client.update_data_retention_settings(request) + await client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_data_retention_settings(request) + await client.update_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -27383,9 +27253,9 @@ async def test_update_data_retention_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_data_retention_settings_async( +async def test_update_custom_metric_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateDataRetentionSettingsRequest, + request_type=analytics_admin.UpdateCustomMetricRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -27398,56 +27268,65 @@ async def test_update_data_retention_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings( + resources.CustomMetric( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) ) - response = await client.update_data_retention_settings(request) + response = await client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDataRetentionSettingsRequest() + request = analytics_admin.UpdateCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRetentionSettings) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert ( - response.event_data_retention - == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS - ) - assert response.reset_user_data_on_new_activity is True + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] @pytest.mark.asyncio -async def test_update_data_retention_settings_async_from_dict(): - await test_update_data_retention_settings_async(request_type=dict) +async def test_update_custom_metric_async_from_dict(): + await test_update_custom_metric_async(request_type=dict) -def test_update_data_retention_settings_field_headers(): +def test_update_custom_metric_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDataRetentionSettingsRequest() + request = analytics_admin.UpdateCustomMetricRequest() - request.data_retention_settings.name = "name_value" + request.custom_metric.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: - call.return_value = resources.DataRetentionSettings() - client.update_data_retention_settings(request) + call.return_value = resources.CustomMetric() + client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -27458,30 +27337,30 @@ def test_update_data_retention_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_retention_settings.name=name_value", + "custom_metric.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_data_retention_settings_field_headers_async(): +async def test_update_custom_metric_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDataRetentionSettingsRequest() + request = analytics_admin.UpdateCustomMetricRequest() - request.data_retention_settings.name = "name_value" + request.custom_metric.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings() + resources.CustomMetric() ) - await client.update_data_retention_settings(request) + await client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -27492,25 +27371,25 @@ async def test_update_data_retention_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_retention_settings.name=name_value", + "custom_metric.name=name_value", ) in kw["metadata"] -def test_update_data_retention_settings_flattened(): +def test_update_custom_metric_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRetentionSettings() + call.return_value = resources.CustomMetric() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_data_retention_settings( - data_retention_settings=resources.DataRetentionSettings(name="name_value"), + client.update_custom_metric( + custom_metric=resources.CustomMetric(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -27518,15 +27397,15 @@ def test_update_data_retention_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].data_retention_settings - mock_val = resources.DataRetentionSettings(name="name_value") + arg = args[0].custom_metric + mock_val = resources.CustomMetric(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_update_data_retention_settings_flattened_error(): +def test_update_custom_metric_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -27534,33 +27413,33 @@ def test_update_data_retention_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_retention_settings( - analytics_admin.UpdateDataRetentionSettingsRequest(), - data_retention_settings=resources.DataRetentionSettings(name="name_value"), + client.update_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_data_retention_settings_flattened_async(): +async def test_update_custom_metric_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_retention_settings), "__call__" + type(client.transport.update_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRetentionSettings() + call.return_value = resources.CustomMetric() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRetentionSettings() + resources.CustomMetric() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_data_retention_settings( - data_retention_settings=resources.DataRetentionSettings(name="name_value"), + response = await client.update_custom_metric( + custom_metric=resources.CustomMetric(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -27568,8 +27447,8 @@ async def test_update_data_retention_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].data_retention_settings - mock_val = resources.DataRetentionSettings(name="name_value") + arg = args[0].custom_metric + mock_val = resources.CustomMetric(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -27577,7 +27456,7 @@ async def test_update_data_retention_settings_flattened_async(): @pytest.mark.asyncio -async def test_update_data_retention_settings_flattened_error_async(): +async def test_update_custom_metric_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -27585,9 +27464,9 @@ async def test_update_data_retention_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_data_retention_settings( - analytics_admin.UpdateDataRetentionSettingsRequest(), - data_retention_settings=resources.DataRetentionSettings(name="name_value"), + await client.update_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -27595,11 +27474,11 @@ async def test_update_data_retention_settings_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateDataStreamRequest, + analytics_admin.ListCustomMetricsRequest, dict, ], ) -def test_create_data_stream(request_type, transport: str = "grpc"): +def test_list_custom_metrics(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -27611,30 +27490,26 @@ def test_create_data_stream(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream( - name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + call.return_value = analytics_admin.ListCustomMetricsResponse( + next_page_token="next_page_token_value", ) - response = client.create_data_stream(request) + response = client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateDataStreamRequest() + request = analytics_admin.ListCustomMetricsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) - assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM - assert response.display_name == "display_name_value" + assert isinstance(response, pagers.ListCustomMetricsPager) + assert response.next_page_token == "next_page_token_value" -def test_create_data_stream_empty_call(): +def test_list_custom_metrics_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -27644,18 +27519,18 @@ def test_create_data_stream_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_data_stream() + client.list_custom_metrics() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateDataStreamRequest() + assert args[0] == analytics_admin.ListCustomMetricsRequest() -def test_create_data_stream_non_empty_request_with_auto_populated_field(): +def test_list_custom_metrics_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -27666,26 +27541,28 @@ def test_create_data_stream_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateDataStreamRequest( + request = analytics_admin.ListCustomMetricsRequest( parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_data_stream(request=request) + client.list_custom_metrics(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateDataStreamRequest( + assert args[0] == analytics_admin.ListCustomMetricsRequest( parent="parent_value", + page_token="page_token_value", ) -def test_create_data_stream_use_cached_wrapped_rpc(): +def test_list_custom_metrics_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -27700,7 +27577,7 @@ def test_create_data_stream_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_data_stream in client._transport._wrapped_methods + client._transport.list_custom_metrics in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -27709,15 +27586,15 @@ def test_create_data_stream_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_data_stream + client._transport.list_custom_metrics ] = mock_rpc request = {} - client.create_data_stream(request) + client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_data_stream(request) + client.list_custom_metrics(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -27725,7 +27602,7 @@ def test_create_data_stream_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_data_stream_empty_call_async(): +async def test_list_custom_metrics_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -27735,24 +27612,22 @@ async def test_create_data_stream_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream( - name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + analytics_admin.ListCustomMetricsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_data_stream() + response = await client.list_custom_metrics() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateDataStreamRequest() + assert args[0] == analytics_admin.ListCustomMetricsRequest() @pytest.mark.asyncio -async def test_create_data_stream_async_use_cached_wrapped_rpc( +async def test_list_custom_metrics_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -27769,23 +27644,23 @@ async def test_create_data_stream_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_data_stream + client._client._transport.list_custom_metrics in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_data_stream + client._client._transport.list_custom_metrics ] = mock_object request = {} - await client.create_data_stream(request) + await client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_data_stream(request) + await client.list_custom_metrics(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -27793,9 +27668,9 @@ async def test_create_data_stream_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_data_stream_async( +async def test_list_custom_metrics_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateDataStreamRequest, + request_type=analytics_admin.ListCustomMetricsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -27808,53 +27683,49 @@ async def test_create_data_stream_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream( - name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + analytics_admin.ListCustomMetricsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_data_stream(request) + response = await client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateDataStreamRequest() + request = analytics_admin.ListCustomMetricsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) - assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM - assert response.display_name == "display_name_value" + assert isinstance(response, pagers.ListCustomMetricsAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_create_data_stream_async_from_dict(): - await test_create_data_stream_async(request_type=dict) +async def test_list_custom_metrics_async_from_dict(): + await test_list_custom_metrics_async(request_type=dict) -def test_create_data_stream_field_headers(): +def test_list_custom_metrics_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateDataStreamRequest() + request = analytics_admin.ListCustomMetricsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: - call.return_value = resources.DataStream() - client.create_data_stream(request) + call.return_value = analytics_admin.ListCustomMetricsResponse() + client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -27870,25 +27741,25 @@ def test_create_data_stream_field_headers(): @pytest.mark.asyncio -async def test_create_data_stream_field_headers_async(): +async def test_list_custom_metrics_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateDataStreamRequest() + request = analytics_admin.ListCustomMetricsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream() + analytics_admin.ListCustomMetricsResponse() ) - await client.create_data_stream(request) + await client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -27903,26 +27774,21 @@ async def test_create_data_stream_field_headers_async(): ) in kw["metadata"] -def test_create_data_stream_flattened(): +def test_list_custom_metrics_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream() + call.return_value = analytics_admin.ListCustomMetricsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_data_stream( + client.list_custom_metrics( parent="parent_value", - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), ) # Establish that the underlying call was made with the expected @@ -27932,16 +27798,9 @@ def test_create_data_stream_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].data_stream - mock_val = resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ) - assert arg == mock_val -def test_create_data_stream_flattened_error(): +def test_list_custom_metrics_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -27949,42 +27808,32 @@ def test_create_data_stream_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_stream( - analytics_admin.CreateDataStreamRequest(), + client.list_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), parent="parent_value", - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), ) @pytest.mark.asyncio -async def test_create_data_stream_flattened_async(): +async def test_list_custom_metrics_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream() + call.return_value = analytics_admin.ListCustomMetricsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream() + analytics_admin.ListCustomMetricsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_data_stream( + response = await client.list_custom_metrics( parent="parent_value", - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), ) # Establish that the underlying call was made with the expected @@ -27994,17 +27843,10 @@ async def test_create_data_stream_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].data_stream - mock_val = resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ) - assert arg == mock_val @pytest.mark.asyncio -async def test_create_data_stream_flattened_error_async(): +async def test_list_custom_metrics_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -28012,104 +27854,301 @@ async def test_create_data_stream_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_data_stream( - analytics_admin.CreateDataStreamRequest(), + await client.list_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), parent="parent_value", - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), ) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.DeleteDataStreamRequest, - dict, - ], -) -def test_delete_data_stream(request_type, transport: str = "grpc"): +def test_list_custom_metrics_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_data_stream(request) + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteDataStreamRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_custom_metrics(request={}, retry=retry, timeout=timeout) - # Establish that the response is the type that we expect. - assert response is None + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomMetric) for i in results) -def test_delete_data_stream_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. + +def test_list_custom_metrics_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.list_custom_metrics), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, ) - client.delete_data_stream() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteDataStreamRequest() + pages = list(client.list_custom_metrics(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_delete_data_stream_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_list_custom_metrics_async_pager(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteDataStreamRequest( - name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.list_custom_metrics), + "__call__", + new_callable=mock.AsyncMock, ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, ) - client.delete_data_stream(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteDataStreamRequest( - name="name_value", + async_pager = await client.list_custom_metrics( + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - -def test_delete_data_stream_use_cached_wrapped_rpc(): + assert len(responses) == 6 + assert all(isinstance(i, resources.CustomMetric) for i in responses) + + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_custom_metrics(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ArchiveCustomMetricRequest, + dict, + ], +) +def test_archive_custom_metric(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_archive_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.archive_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + + +def test_archive_custom_metric_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ArchiveCustomMetricRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.archive_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest( + name="name_value", + ) + + +def test_archive_custom_metric_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -28124,7 +28163,8 @@ def test_delete_data_stream_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_data_stream in client._transport._wrapped_methods + client._transport.archive_custom_metric + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -28133,15 +28173,15 @@ def test_delete_data_stream_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_data_stream + client._transport.archive_custom_metric ] = mock_rpc request = {} - client.delete_data_stream(request) + client.archive_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_data_stream(request) + client.archive_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -28149,7 +28189,7 @@ def test_delete_data_stream_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_data_stream_empty_call_async(): +async def test_archive_custom_metric_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -28159,18 +28199,18 @@ async def test_delete_data_stream_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.archive_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_data_stream() + response = await client.archive_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteDataStreamRequest() + assert args[0] == analytics_admin.ArchiveCustomMetricRequest() @pytest.mark.asyncio -async def test_delete_data_stream_async_use_cached_wrapped_rpc( +async def test_archive_custom_metric_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -28187,23 +28227,23 @@ async def test_delete_data_stream_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_data_stream + client._client._transport.archive_custom_metric in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_data_stream + client._client._transport.archive_custom_metric ] = mock_object request = {} - await client.delete_data_stream(request) + await client.archive_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_data_stream(request) + await client.archive_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -28211,9 +28251,9 @@ async def test_delete_data_stream_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_data_stream_async( +async def test_archive_custom_metric_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteDataStreamRequest, + request_type=analytics_admin.ArchiveCustomMetricRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -28226,16 +28266,16 @@ async def test_delete_data_stream_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.archive_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_data_stream(request) + response = await client.archive_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteDataStreamRequest() + request = analytics_admin.ArchiveCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -28243,27 +28283,27 @@ async def test_delete_data_stream_async( @pytest.mark.asyncio -async def test_delete_data_stream_async_from_dict(): - await test_delete_data_stream_async(request_type=dict) +async def test_archive_custom_metric_async_from_dict(): + await test_archive_custom_metric_async(request_type=dict) -def test_delete_data_stream_field_headers(): +def test_archive_custom_metric_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteDataStreamRequest() + request = analytics_admin.ArchiveCustomMetricRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.archive_custom_metric), "__call__" ) as call: call.return_value = None - client.delete_data_stream(request) + client.archive_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -28279,23 +28319,23 @@ def test_delete_data_stream_field_headers(): @pytest.mark.asyncio -async def test_delete_data_stream_field_headers_async(): +async def test_archive_custom_metric_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteDataStreamRequest() + request = analytics_admin.ArchiveCustomMetricRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.archive_custom_metric), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_data_stream(request) + await client.archive_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -28310,20 +28350,20 @@ async def test_delete_data_stream_field_headers_async(): ) in kw["metadata"] -def test_delete_data_stream_flattened(): +def test_archive_custom_metric_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.archive_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_data_stream( + client.archive_custom_metric( name="name_value", ) @@ -28336,7 +28376,7 @@ def test_delete_data_stream_flattened(): assert arg == mock_val -def test_delete_data_stream_flattened_error(): +def test_archive_custom_metric_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -28344,21 +28384,21 @@ def test_delete_data_stream_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_stream( - analytics_admin.DeleteDataStreamRequest(), + client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_data_stream_flattened_async(): +async def test_archive_custom_metric_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_stream), "__call__" + type(client.transport.archive_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -28366,7 +28406,7 @@ async def test_delete_data_stream_flattened_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_data_stream( + response = await client.archive_custom_metric( name="name_value", ) @@ -28380,7 +28420,7 @@ async def test_delete_data_stream_flattened_async(): @pytest.mark.asyncio -async def test_delete_data_stream_flattened_error_async(): +async def test_archive_custom_metric_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -28388,8 +28428,8 @@ async def test_delete_data_stream_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_data_stream( - analytics_admin.DeleteDataStreamRequest(), + await client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), name="name_value", ) @@ -28397,11 +28437,11 @@ async def test_delete_data_stream_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateDataStreamRequest, + analytics_admin.GetCustomMetricRequest, dict, ], ) -def test_update_data_stream(request_type, transport: str = "grpc"): +def test_get_custom_metric(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -28413,30 +28453,42 @@ def test_update_data_stream(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream( + call.return_value = resources.CustomMetric( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + parameter_name="parameter_name_value", display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) - response = client.update_data_stream(request) + response = client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDataStreamRequest() + request = analytics_admin.GetCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] -def test_update_data_stream_empty_call(): +def test_get_custom_metric_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -28446,18 +28498,18 @@ def test_update_data_stream_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_stream() + client.get_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataStreamRequest() + assert args[0] == analytics_admin.GetCustomMetricRequest() -def test_update_data_stream_non_empty_request_with_auto_populated_field(): +def test_get_custom_metric_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -28468,22 +28520,26 @@ def test_update_data_stream_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateDataStreamRequest() + request = analytics_admin.GetCustomMetricRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_stream(request=request) + client.get_custom_metric(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataStreamRequest() + assert args[0] == analytics_admin.GetCustomMetricRequest( + name="name_value", + ) -def test_update_data_stream_use_cached_wrapped_rpc(): +def test_get_custom_metric_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -28497,9 +28553,7 @@ def test_update_data_stream_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_data_stream in client._transport._wrapped_methods - ) + assert client._transport.get_custom_metric in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -28507,15 +28561,15 @@ def test_update_data_stream_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_data_stream + client._transport.get_custom_metric ] = mock_rpc request = {} - client.update_data_stream(request) + client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_stream(request) + client.get_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -28523,7 +28577,7 @@ def test_update_data_stream_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_data_stream_empty_call_async(): +async def test_get_custom_metric_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -28533,24 +28587,30 @@ async def test_update_data_stream_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream( + resources.CustomMetric( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + parameter_name="parameter_name_value", display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) ) - response = await client.update_data_stream() + response = await client.get_custom_metric() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataStreamRequest() + assert args[0] == analytics_admin.GetCustomMetricRequest() @pytest.mark.asyncio -async def test_update_data_stream_async_use_cached_wrapped_rpc( +async def test_get_custom_metric_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -28567,23 +28627,23 @@ async def test_update_data_stream_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_data_stream + client._client._transport.get_custom_metric in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_data_stream + client._client._transport.get_custom_metric ] = mock_object request = {} - await client.update_data_stream(request) + await client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_data_stream(request) + await client.get_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -28591,9 +28651,8 @@ async def test_update_data_stream_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_data_stream_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateDataStreamRequest, +async def test_get_custom_metric_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetCustomMetricRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -28606,53 +28665,65 @@ async def test_update_data_stream_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream( + resources.CustomMetric( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + parameter_name="parameter_name_value", display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) ) - response = await client.update_data_stream(request) + response = await client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDataStreamRequest() + request = analytics_admin.GetCustomMetricRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.parameter_name == "parameter_name_value" assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] @pytest.mark.asyncio -async def test_update_data_stream_async_from_dict(): - await test_update_data_stream_async(request_type=dict) +async def test_get_custom_metric_async_from_dict(): + await test_get_custom_metric_async(request_type=dict) -def test_update_data_stream_field_headers(): +def test_get_custom_metric_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDataStreamRequest() + request = analytics_admin.GetCustomMetricRequest() - request.data_stream.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: - call.return_value = resources.DataStream() - client.update_data_stream(request) + call.return_value = resources.CustomMetric() + client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -28663,30 +28734,30 @@ def test_update_data_stream_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_stream.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_data_stream_field_headers_async(): +async def test_get_custom_metric_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDataStreamRequest() + request = analytics_admin.GetCustomMetricRequest() - request.data_stream.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream() + resources.CustomMetric() ) - await client.update_data_stream(request) + await client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -28697,49 +28768,37 @@ async def test_update_data_stream_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_stream.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_data_stream_flattened(): +def test_get_custom_metric_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream() + call.return_value = resources.CustomMetric() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_data_stream( - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_custom_metric( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].data_stream - mock_val = resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_data_stream_flattened_error(): +def test_get_custom_metric_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -28747,62 +28806,45 @@ def test_update_data_stream_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_stream( - analytics_admin.UpdateDataStreamRequest(), - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_data_stream_flattened_async(): +async def test_get_custom_metric_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_stream), "__call__" + type(client.transport.get_custom_metric), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream() + call.return_value = resources.CustomMetric() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream() + resources.CustomMetric() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_data_stream( - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_custom_metric( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].data_stream - mock_val = resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_data_stream_flattened_error_async(): +async def test_get_custom_metric_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -28810,25 +28852,20 @@ async def test_update_data_stream_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_data_stream( - analytics_admin.UpdateDataStreamRequest(), - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListDataStreamsRequest, + analytics_admin.GetDataRetentionSettingsRequest, dict, ], ) -def test_list_data_streams(request_type, transport: str = "grpc"): +def test_get_data_retention_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -28840,26 +28877,33 @@ def test_list_data_streams(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListDataStreamsResponse( - next_page_token="next_page_token_value", + call.return_value = resources.DataRetentionSettings( + name="name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) - response = client.list_data_streams(request) + response = client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListDataStreamsRequest() + request = analytics_admin.GetDataRetentionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataStreamsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == "name_value" + assert ( + response.event_data_retention + == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + ) + assert response.reset_user_data_on_new_activity is True -def test_list_data_streams_empty_call(): +def test_get_data_retention_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -28869,18 +28913,18 @@ def test_list_data_streams_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_data_streams() + client.get_data_retention_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListDataStreamsRequest() + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() -def test_list_data_streams_non_empty_request_with_auto_populated_field(): +def test_get_data_retention_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -28891,28 +28935,26 @@ def test_list_data_streams_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListDataStreamsRequest( - parent="parent_value", - page_token="page_token_value", + request = analytics_admin.GetDataRetentionSettingsRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_data_streams(request=request) + client.get_data_retention_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListDataStreamsRequest( - parent="parent_value", - page_token="page_token_value", + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest( + name="name_value", ) -def test_list_data_streams_use_cached_wrapped_rpc(): +def test_get_data_retention_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -28926,23 +28968,26 @@ def test_list_data_streams_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_streams in client._transport._wrapped_methods - + assert ( + client._transport.get_data_retention_settings + in client._transport._wrapped_methods + ) + # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_data_streams + client._transport.get_data_retention_settings ] = mock_rpc request = {} - client.list_data_streams(request) + client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_streams(request) + client.get_data_retention_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -28950,7 +28995,7 @@ def test_list_data_streams_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_data_streams_empty_call_async(): +async def test_get_data_retention_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -28960,22 +29005,24 @@ async def test_list_data_streams_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDataStreamsResponse( - next_page_token="next_page_token_value", + resources.DataRetentionSettings( + name="name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) ) - response = await client.list_data_streams() + response = await client.get_data_retention_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListDataStreamsRequest() + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() @pytest.mark.asyncio -async def test_list_data_streams_async_use_cached_wrapped_rpc( +async def test_get_data_retention_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -28992,23 +29039,23 @@ async def test_list_data_streams_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_data_streams + client._client._transport.get_data_retention_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_data_streams + client._client._transport.get_data_retention_settings ] = mock_object request = {} - await client.list_data_streams(request) + await client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_data_streams(request) + await client.get_data_retention_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -29016,8 +29063,9 @@ async def test_list_data_streams_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_data_streams_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.ListDataStreamsRequest +async def test_get_data_retention_settings_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.GetDataRetentionSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29030,49 +29078,56 @@ async def test_list_data_streams_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDataStreamsResponse( - next_page_token="next_page_token_value", + resources.DataRetentionSettings( + name="name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) ) - response = await client.list_data_streams(request) + response = await client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListDataStreamsRequest() + request = analytics_admin.GetDataRetentionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataStreamsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == "name_value" + assert ( + response.event_data_retention + == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + ) + assert response.reset_user_data_on_new_activity is True @pytest.mark.asyncio -async def test_list_data_streams_async_from_dict(): - await test_list_data_streams_async(request_type=dict) +async def test_get_data_retention_settings_async_from_dict(): + await test_get_data_retention_settings_async(request_type=dict) -def test_list_data_streams_field_headers(): +def test_get_data_retention_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListDataStreamsRequest() + request = analytics_admin.GetDataRetentionSettingsRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: - call.return_value = analytics_admin.ListDataStreamsResponse() - client.list_data_streams(request) + call.return_value = resources.DataRetentionSettings() + client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -29083,30 +29138,30 @@ def test_list_data_streams_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_data_streams_field_headers_async(): +async def test_get_data_retention_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListDataStreamsRequest() + request = analytics_admin.GetDataRetentionSettingsRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDataStreamsResponse() + resources.DataRetentionSettings() ) - await client.list_data_streams(request) + await client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -29117,37 +29172,37 @@ async def test_list_data_streams_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_data_streams_flattened(): +def test_get_data_retention_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListDataStreamsResponse() + call.return_value = resources.DataRetentionSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_data_streams( - parent="parent_value", + client.get_data_retention_settings( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_data_streams_flattened_error(): +def test_get_data_retention_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -29155,45 +29210,45 @@ def test_list_data_streams_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_streams( - analytics_admin.ListDataStreamsRequest(), - parent="parent_value", + client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_data_streams_flattened_async(): +async def test_get_data_retention_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_streams), "__call__" + type(client.transport.get_data_retention_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListDataStreamsResponse() + call.return_value = resources.DataRetentionSettings() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListDataStreamsResponse() + resources.DataRetentionSettings() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_data_streams( - parent="parent_value", + response = await client.get_data_retention_settings( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_data_streams_flattened_error_async(): +async def test_get_data_retention_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -29201,222 +29256,20 @@ async def test_list_data_streams_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_data_streams( - analytics_admin.ListDataStreamsRequest(), - parent="parent_value", - ) - - -def test_list_data_streams_pager(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_streams), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - resources.DataStream(), - ], - next_page_token="abc", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[], - next_page_token="def", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_data_streams(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.DataStream) for i in results) - - -def test_list_data_streams_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_streams), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - resources.DataStream(), - ], - next_page_token="abc", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[], - next_page_token="def", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - ], - ), - RuntimeError, - ) - pages = list(client.list_data_streams(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_data_streams_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_streams), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - resources.DataStream(), - ], - next_page_token="abc", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[], - next_page_token="def", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_data_streams( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.DataStream) for i in responses) - - -@pytest.mark.asyncio -async def test_list_data_streams_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_streams), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - resources.DataStream(), - ], - next_page_token="abc", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[], - next_page_token="def", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - ], - ), - RuntimeError, + await client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name="name_value", ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_data_streams(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDataStreamRequest, + analytics_admin.UpdateDataRetentionSettingsRequest, dict, ], ) -def test_get_data_stream(request_type, transport: str = "grpc"): +def test_update_data_retention_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -29427,29 +29280,34 @@ def test_get_data_stream(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream( + call.return_value = resources.DataRetentionSettings( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) - response = client.get_data_stream(request) + response = client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDataStreamRequest() + request = analytics_admin.UpdateDataRetentionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) + assert isinstance(response, resources.DataRetentionSettings) assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM - assert response.display_name == "display_name_value" + assert ( + response.event_data_retention + == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + ) + assert response.reset_user_data_on_new_activity is True -def test_get_data_stream_empty_call(): +def test_update_data_retention_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -29458,17 +29316,19 @@ def test_get_data_stream_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_stream() + client.update_data_retention_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataStreamRequest() + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() -def test_get_data_stream_non_empty_request_with_auto_populated_field(): +def test_update_data_retention_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -29479,24 +29339,22 @@ def test_get_data_stream_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetDataStreamRequest( - name="name_value", - ) + request = analytics_admin.UpdateDataRetentionSettingsRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_stream(request=request) + client.update_data_retention_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataStreamRequest( - name="name_value", - ) + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() -def test_get_data_stream_use_cached_wrapped_rpc(): +def test_update_data_retention_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -29510,21 +29368,26 @@ def test_get_data_stream_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_stream in client._transport._wrapped_methods + assert ( + client._transport.update_data_retention_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_data_retention_settings + ] = mock_rpc request = {} - client.get_data_stream(request) + client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_stream(request) + client.update_data_retention_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -29532,7 +29395,7 @@ def test_get_data_stream_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_data_stream_empty_call_async(): +async def test_update_data_retention_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -29541,23 +29404,25 @@ async def test_get_data_stream_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream( + resources.DataRetentionSettings( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) ) - response = await client.get_data_stream() + response = await client.update_data_retention_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataStreamRequest() + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() @pytest.mark.asyncio -async def test_get_data_stream_async_use_cached_wrapped_rpc( +async def test_update_data_retention_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -29574,23 +29439,23 @@ async def test_get_data_stream_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_data_stream + client._client._transport.update_data_retention_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_data_stream + client._client._transport.update_data_retention_settings ] = mock_object request = {} - await client.get_data_stream(request) + await client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_data_stream(request) + await client.update_data_retention_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -29598,8 +29463,9 @@ async def test_get_data_stream_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_data_stream_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.GetDataStreamRequest +async def test_update_data_retention_settings_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.UpdateDataRetentionSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29611,50 +29477,57 @@ async def test_get_data_stream_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream( + resources.DataRetentionSettings( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) ) - response = await client.get_data_stream(request) + response = await client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDataStreamRequest() + request = analytics_admin.UpdateDataRetentionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) + assert isinstance(response, resources.DataRetentionSettings) assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM - assert response.display_name == "display_name_value" + assert ( + response.event_data_retention + == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + ) + assert response.reset_user_data_on_new_activity is True @pytest.mark.asyncio -async def test_get_data_stream_async_from_dict(): - await test_get_data_stream_async(request_type=dict) +async def test_update_data_retention_settings_async_from_dict(): + await test_update_data_retention_settings_async(request_type=dict) -def test_get_data_stream_field_headers(): +def test_update_data_retention_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDataStreamRequest() + request = analytics_admin.UpdateDataRetentionSettingsRequest() - request.name = "name_value" + request.data_retention_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: - call.return_value = resources.DataStream() - client.get_data_stream(request) + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: + call.return_value = resources.DataRetentionSettings() + client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -29665,28 +29538,30 @@ def test_get_data_stream_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "data_retention_settings.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_data_stream_field_headers_async(): +async def test_update_data_retention_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDataStreamRequest() + request = analytics_admin.UpdateDataRetentionSettingsRequest() - request.name = "name_value" + request.data_retention_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream() + resources.DataRetentionSettings() ) - await client.get_data_stream(request) + await client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -29697,35 +29572,41 @@ async def test_get_data_stream_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "data_retention_settings.name=name_value", ) in kw["metadata"] -def test_get_data_stream_flattened(): +def test_update_data_retention_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream() + call.return_value = resources.DataRetentionSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_data_stream( - name="name_value", + client.update_data_retention_settings( + data_retention_settings=resources.DataRetentionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].data_retention_settings + mock_val = resources.DataRetentionSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_get_data_stream_flattened_error(): +def test_update_data_retention_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -29733,43 +29614,50 @@ def test_get_data_stream_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_stream( - analytics_admin.GetDataStreamRequest(), - name="name_value", + client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_data_stream_flattened_async(): +async def test_update_data_retention_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_retention_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataStream() + call.return_value = resources.DataRetentionSettings() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataStream() + resources.DataRetentionSettings() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_data_stream( - name="name_value", + response = await client.update_data_retention_settings( + data_retention_settings=resources.DataRetentionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].data_retention_settings + mock_val = resources.DataRetentionSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_get_data_stream_flattened_error_async(): +async def test_update_data_retention_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -29777,20 +29665,21 @@ async def test_get_data_stream_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_data_stream( - analytics_admin.GetDataStreamRequest(), - name="name_value", + await client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAudienceRequest, + analytics_admin.CreateDataStreamRequest, dict, ], ) -def test_get_audience(request_type, transport: str = "grpc"): +def test_create_data_stream(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -29801,38 +29690,31 @@ def test_get_audience(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = audience.Audience( + call.return_value = resources.DataStream( name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) - response = client.get_audience(request) + response = client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAudienceRequest() + request = analytics_admin.CreateDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, audience.Audience) + assert isinstance(response, resources.DataStream) assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) -def test_get_audience_empty_call(): +def test_create_data_stream_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -29841,17 +29723,19 @@ def test_get_audience_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_audience() + client.create_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAudienceRequest() + assert args[0] == analytics_admin.CreateDataStreamRequest() -def test_get_audience_non_empty_request_with_auto_populated_field(): +def test_create_data_stream_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -29862,24 +29746,26 @@ def test_get_audience_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetAudienceRequest( - name="name_value", + request = analytics_admin.CreateDataStreamRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_audience(request=request) + client.create_data_stream(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAudienceRequest( - name="name_value", + assert args[0] == analytics_admin.CreateDataStreamRequest( + parent="parent_value", ) -def test_get_audience_use_cached_wrapped_rpc(): +def test_create_data_stream_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -29893,21 +29779,25 @@ def test_get_audience_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_audience in client._transport._wrapped_methods + assert ( + client._transport.create_data_stream in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_audience] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_data_stream + ] = mock_rpc request = {} - client.get_audience(request) + client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_audience(request) + client.create_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -29915,7 +29805,7 @@ def test_get_audience_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_audience_empty_call_async(): +async def test_create_data_stream_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -29924,26 +29814,25 @@ async def test_get_audience_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - audience.Audience( + resources.DataStream( name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.get_audience() + response = await client.create_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAudienceRequest() + assert args[0] == analytics_admin.CreateDataStreamRequest() @pytest.mark.asyncio -async def test_get_audience_async_use_cached_wrapped_rpc( +async def test_create_data_stream_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -29960,23 +29849,23 @@ async def test_get_audience_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_audience + client._client._transport.create_data_stream in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_audience + client._client._transport.create_data_stream ] = mock_object request = {} - await client.get_audience(request) + await client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_audience(request) + await client.create_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -29984,8 +29873,9 @@ async def test_get_audience_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_audience_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.GetAudienceRequest +async def test_create_data_stream_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.CreateDataStreamRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29997,59 +29887,54 @@ async def test_get_audience_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - audience.Audience( + resources.DataStream( name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.get_audience(request) + response = await client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAudienceRequest() + request = analytics_admin.CreateDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, audience.Audience) + assert isinstance(response, resources.DataStream) assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) @pytest.mark.asyncio -async def test_get_audience_async_from_dict(): - await test_get_audience_async(request_type=dict) +async def test_create_data_stream_async_from_dict(): + await test_create_data_stream_async(request_type=dict) -def test_get_audience_field_headers(): +def test_create_data_stream_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAudienceRequest() + request = analytics_admin.CreateDataStreamRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: - call.return_value = audience.Audience() - client.get_audience(request) + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: + call.return_value = resources.DataStream() + client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -30060,26 +29945,30 @@ def test_get_audience_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_audience_field_headers_async(): +async def test_create_data_stream_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAudienceRequest() + request = analytics_admin.CreateDataStreamRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience()) - await client.get_audience(request) + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataStream() + ) + await client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -30090,35 +29979,49 @@ async def test_get_audience_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_audience_flattened(): +def test_create_data_stream_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = audience.Audience() + call.return_value = resources.DataStream() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_audience( - name="name_value", + client.create_data_stream( + parent="parent_value", + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].data_stream + mock_val = resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ) assert arg == mock_val -def test_get_audience_flattened_error(): +def test_create_data_stream_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -30126,41 +30029,62 @@ def test_get_audience_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_audience( - analytics_admin.GetAudienceRequest(), - name="name_value", + client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent="parent_value", + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), ) @pytest.mark.asyncio -async def test_get_audience_flattened_async(): +async def test_create_data_stream_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.create_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = audience.Audience() + call.return_value = resources.DataStream() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataStream() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_audience( - name="name_value", + response = await client.create_data_stream( + parent="parent_value", + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].data_stream + mock_val = resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ) assert arg == mock_val @pytest.mark.asyncio -async def test_get_audience_flattened_error_async(): +async def test_create_data_stream_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -30168,20 +30092,25 @@ async def test_get_audience_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_audience( - analytics_admin.GetAudienceRequest(), - name="name_value", + await client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent="parent_value", + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListAudiencesRequest, + analytics_admin.DeleteDataStreamRequest, dict, ], ) -def test_list_audiences(request_type, transport: str = "grpc"): +def test_delete_data_stream(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -30192,25 +30121,24 @@ def test_list_audiences(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAudiencesResponse( - next_page_token="next_page_token_value", - ) - response = client.list_audiences(request) + call.return_value = None + response = client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListAudiencesRequest() + request = analytics_admin.DeleteDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAudiencesPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_audiences_empty_call(): +def test_delete_data_stream_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -30219,17 +30147,19 @@ def test_list_audiences_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_audiences() + client.delete_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAudiencesRequest() + assert args[0] == analytics_admin.DeleteDataStreamRequest() -def test_list_audiences_non_empty_request_with_auto_populated_field(): +def test_delete_data_stream_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -30240,26 +30170,26 @@ def test_list_audiences_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListAudiencesRequest( - parent="parent_value", - page_token="page_token_value", + request = analytics_admin.DeleteDataStreamRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_audiences(request=request) + client.delete_data_stream(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAudiencesRequest( - parent="parent_value", - page_token="page_token_value", + assert args[0] == analytics_admin.DeleteDataStreamRequest( + name="name_value", ) -def test_list_audiences_use_cached_wrapped_rpc(): +def test_delete_data_stream_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -30273,21 +30203,25 @@ def test_list_audiences_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_audiences in client._transport._wrapped_methods + assert ( + client._transport.delete_data_stream in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_audiences] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_data_stream + ] = mock_rpc request = {} - client.list_audiences(request) + client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_audiences(request) + client.delete_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -30295,7 +30229,7 @@ def test_list_audiences_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_audiences_empty_call_async(): +async def test_delete_data_stream_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -30304,21 +30238,19 @@ async def test_list_audiences_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAudiencesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_audiences() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAudiencesRequest() + assert args[0] == analytics_admin.DeleteDataStreamRequest() @pytest.mark.asyncio -async def test_list_audiences_async_use_cached_wrapped_rpc( +async def test_delete_data_stream_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -30335,23 +30267,23 @@ async def test_list_audiences_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_audiences + client._client._transport.delete_data_stream in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_audiences + client._client._transport.delete_data_stream ] = mock_object request = {} - await client.list_audiences(request) + await client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_audiences(request) + await client.delete_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -30359,8 +30291,9 @@ async def test_list_audiences_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_audiences_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.ListAudiencesRequest +async def test_delete_data_stream_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.DeleteDataStreamRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -30372,46 +30305,45 @@ async def test_list_audiences_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAudiencesResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_audiences(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListAudiencesRequest() + request = analytics_admin.DeleteDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAudiencesAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response is None @pytest.mark.asyncio -async def test_list_audiences_async_from_dict(): - await test_list_audiences_async(request_type=dict) +async def test_delete_data_stream_async_from_dict(): + await test_delete_data_stream_async(request_type=dict) -def test_list_audiences_field_headers(): +def test_delete_data_stream_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListAudiencesRequest() + request = analytics_admin.DeleteDataStreamRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: - call.return_value = analytics_admin.ListAudiencesResponse() - client.list_audiences(request) + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: + call.return_value = None + client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -30422,28 +30354,28 @@ def test_list_audiences_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_audiences_field_headers_async(): +async def test_delete_data_stream_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListAudiencesRequest() + request = analytics_admin.DeleteDataStreamRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAudiencesResponse() - ) - await client.list_audiences(request) + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -30454,35 +30386,37 @@ async def test_list_audiences_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_audiences_flattened(): +def test_delete_data_stream_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAudiencesResponse() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_audiences( - parent="parent_value", + client.delete_data_stream( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_audiences_flattened_error(): +def test_delete_data_stream_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -30490,43 +30424,43 @@ def test_list_audiences_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_audiences( - analytics_admin.ListAudiencesRequest(), - parent="parent_value", + client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_audiences_flattened_async(): +async def test_delete_data_stream_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAudiencesResponse() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAudiencesResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_audiences( - parent="parent_value", + response = await client.delete_data_stream( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_audiences_flattened_error_async(): +async def test_delete_data_stream_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -30534,256 +30468,55 @@ async def test_list_audiences_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_audiences( - analytics_admin.ListAudiencesRequest(), - parent="parent_value", + await client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name="name_value", ) -def test_list_audiences_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateDataStreamRequest, + dict, + ], +) +def test_update_data_stream(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - audience.Audience(), - ], - next_page_token="abc", - ), - analytics_admin.ListAudiencesResponse( - audiences=[], - next_page_token="def", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_audiences(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, audience.Audience) for i in results) - - -def test_list_audiences_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - audience.Audience(), - ], - next_page_token="abc", - ), - analytics_admin.ListAudiencesResponse( - audiences=[], - next_page_token="def", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - ], - ), - RuntimeError, - ) - pages = list(client.list_audiences(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_audiences_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_audiences), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - audience.Audience(), - ], - next_page_token="abc", - ), - analytics_admin.ListAudiencesResponse( - audiences=[], - next_page_token="def", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_audiences( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, audience.Audience) for i in responses) - - -@pytest.mark.asyncio -async def test_list_audiences_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_audiences), "__call__", new_callable=mock.AsyncMock + type(client.transport.update_data_stream), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - audience.Audience(), - ], - next_page_token="abc", - ), - analytics_admin.ListAudiencesResponse( - audiences=[], - next_page_token="def", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_audiences(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.CreateAudienceRequest, - dict, - ], -) -def test_create_audience(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = gaa_audience.Audience( + call.return_value = resources.DataStream( name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) - response = client.create_audience(request) + response = client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateAudienceRequest() + request = analytics_admin.UpdateDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_audience.Audience) + assert isinstance(response, resources.DataStream) assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) -def test_create_audience_empty_call(): +def test_update_data_stream_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -30792,17 +30525,19 @@ def test_create_audience_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_audience() + client.update_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAudienceRequest() + assert args[0] == analytics_admin.UpdateDataStreamRequest() -def test_create_audience_non_empty_request_with_auto_populated_field(): +def test_update_data_stream_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -30813,24 +30548,22 @@ def test_create_audience_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateAudienceRequest( - parent="parent_value", - ) + request = analytics_admin.UpdateDataStreamRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_audience(request=request) + client.update_data_stream(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAudienceRequest( - parent="parent_value", - ) + assert args[0] == analytics_admin.UpdateDataStreamRequest() -def test_create_audience_use_cached_wrapped_rpc(): +def test_update_data_stream_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -30844,21 +30577,25 @@ def test_create_audience_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_audience in client._transport._wrapped_methods + assert ( + client._transport.update_data_stream in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_audience] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_data_stream + ] = mock_rpc request = {} - client.create_audience(request) + client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_audience(request) + client.update_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -30866,7 +30603,7 @@ def test_create_audience_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_audience_empty_call_async(): +async def test_update_data_stream_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -30875,26 +30612,25 @@ async def test_create_audience_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience( + resources.DataStream( name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.create_audience() + response = await client.update_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAudienceRequest() + assert args[0] == analytics_admin.UpdateDataStreamRequest() @pytest.mark.asyncio -async def test_create_audience_async_use_cached_wrapped_rpc( +async def test_update_data_stream_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -30911,23 +30647,23 @@ async def test_create_audience_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_audience + client._client._transport.update_data_stream in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_audience + client._client._transport.update_data_stream ] = mock_object request = {} - await client.create_audience(request) + await client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_audience(request) + await client.update_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -30935,8 +30671,9 @@ async def test_create_audience_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_audience_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.CreateAudienceRequest +async def test_update_data_stream_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.UpdateDataStreamRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -30948,59 +30685,54 @@ async def test_create_audience_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience( + resources.DataStream( name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.create_audience(request) + response = await client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateAudienceRequest() + request = analytics_admin.UpdateDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_audience.Audience) + assert isinstance(response, resources.DataStream) assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) @pytest.mark.asyncio -async def test_create_audience_async_from_dict(): - await test_create_audience_async(request_type=dict) +async def test_update_data_stream_async_from_dict(): + await test_update_data_stream_async(request_type=dict) -def test_create_audience_field_headers(): +def test_update_data_stream_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateAudienceRequest() + request = analytics_admin.UpdateDataStreamRequest() - request.parent = "parent_value" + request.data_stream.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: - call.return_value = gaa_audience.Audience() - client.create_audience(request) + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: + call.return_value = resources.DataStream() + client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -31011,28 +30743,30 @@ def test_create_audience_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "data_stream.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_audience_field_headers_async(): +async def test_update_data_stream_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateAudienceRequest() + request = analytics_admin.UpdateDataStreamRequest() - request.parent = "parent_value" + request.data_stream.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience() + resources.DataStream() ) - await client.create_audience(request) + await client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -31043,39 +30777,49 @@ async def test_create_audience_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "data_stream.name=name_value", ) in kw["metadata"] -def test_create_audience_flattened(): +def test_update_data_stream_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_audience.Audience() + call.return_value = resources.DataStream() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_audience( - parent="parent_value", - audience=gaa_audience.Audience(name="name_value"), + client.update_data_stream( + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].data_stream + mock_val = resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ) assert arg == mock_val - arg = args[0].audience - mock_val = gaa_audience.Audience(name="name_value") + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_audience_flattened_error(): +def test_update_data_stream_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -31083,48 +30827,62 @@ def test_create_audience_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_audience( - analytics_admin.CreateAudienceRequest(), - parent="parent_value", - audience=gaa_audience.Audience(name="name_value"), + client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_create_audience_flattened_async(): +async def test_update_data_stream_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.update_data_stream), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_audience.Audience() + call.return_value = resources.DataStream() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience() + resources.DataStream() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_audience( - parent="parent_value", - audience=gaa_audience.Audience(name="name_value"), + response = await client.update_data_stream( + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].data_stream + mock_val = resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ) assert arg == mock_val - arg = args[0].audience - mock_val = gaa_audience.Audience(name="name_value") + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_audience_flattened_error_async(): +async def test_update_data_stream_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -31132,21 +30890,25 @@ async def test_create_audience_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_audience( - analytics_admin.CreateAudienceRequest(), - parent="parent_value", - audience=gaa_audience.Audience(name="name_value"), + await client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAudienceRequest, + analytics_admin.ListDataStreamsRequest, dict, ], ) -def test_update_audience(request_type, transport: str = "grpc"): +def test_list_data_streams(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31157,38 +30919,27 @@ def test_update_audience(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_audience.Audience( - name="name_value", - display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + call.return_value = analytics_admin.ListDataStreamsResponse( + next_page_token="next_page_token_value", ) - response = client.update_audience(request) + response = client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateAudienceRequest() + request = analytics_admin.ListDataStreamsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_audience.Audience) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) + assert isinstance(response, pagers.ListDataStreamsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_audience_empty_call(): +def test_list_data_streams_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -31197,17 +30948,19 @@ def test_update_audience_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_audience() + client.list_data_streams() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAudienceRequest() + assert args[0] == analytics_admin.ListDataStreamsRequest() -def test_update_audience_non_empty_request_with_auto_populated_field(): +def test_list_data_streams_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -31218,20 +30971,28 @@ def test_update_audience_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateAudienceRequest() + request = analytics_admin.ListDataStreamsRequest( + parent="parent_value", + page_token="page_token_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_audience(request=request) + client.list_data_streams(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAudienceRequest() + assert args[0] == analytics_admin.ListDataStreamsRequest( + parent="parent_value", + page_token="page_token_value", + ) -def test_update_audience_use_cached_wrapped_rpc(): +def test_list_data_streams_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -31245,21 +31006,23 @@ def test_update_audience_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_audience in client._transport._wrapped_methods + assert client._transport.list_data_streams in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_audience] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_data_streams + ] = mock_rpc request = {} - client.update_audience(request) + client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_audience(request) + client.list_data_streams(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -31267,7 +31030,7 @@ def test_update_audience_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_audience_empty_call_async(): +async def test_list_data_streams_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -31276,26 +31039,23 @@ async def test_update_audience_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience( - name="name_value", - display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + analytics_admin.ListDataStreamsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_audience() + response = await client.list_data_streams() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAudienceRequest() + assert args[0] == analytics_admin.ListDataStreamsRequest() @pytest.mark.asyncio -async def test_update_audience_async_use_cached_wrapped_rpc( +async def test_list_data_streams_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -31312,23 +31072,23 @@ async def test_update_audience_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_audience + client._client._transport.list_data_streams in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_audience + client._client._transport.list_data_streams ] = mock_object request = {} - await client.update_audience(request) + await client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_audience(request) + await client.list_data_streams(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -31336,8 +31096,8 @@ async def test_update_audience_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_audience_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.UpdateAudienceRequest +async def test_list_data_streams_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.ListDataStreamsRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -31349,59 +31109,50 @@ async def test_update_audience_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience( - name="name_value", - display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + analytics_admin.ListDataStreamsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_audience(request) + response = await client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateAudienceRequest() + request = analytics_admin.ListDataStreamsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_audience.Audience) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) + assert isinstance(response, pagers.ListDataStreamsAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_update_audience_async_from_dict(): - await test_update_audience_async(request_type=dict) +async def test_list_data_streams_async_from_dict(): + await test_list_data_streams_async(request_type=dict) -def test_update_audience_field_headers(): +def test_list_data_streams_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateAudienceRequest() + request = analytics_admin.ListDataStreamsRequest() - request.audience.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: - call.return_value = gaa_audience.Audience() - client.update_audience(request) + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: + call.return_value = analytics_admin.ListDataStreamsResponse() + client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -31412,28 +31163,30 @@ def test_update_audience_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "audience.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_audience_field_headers_async(): +async def test_list_data_streams_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateAudienceRequest() + request = analytics_admin.ListDataStreamsRequest() - request.audience.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience() + analytics_admin.ListDataStreamsResponse() ) - await client.update_audience(request) + await client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -31444,39 +31197,37 @@ async def test_update_audience_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "audience.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_audience_flattened(): +def test_list_data_streams_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_audience.Audience() + call.return_value = analytics_admin.ListDataStreamsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_audience( - audience=gaa_audience.Audience(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_data_streams( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].audience - mock_val = gaa_audience.Audience(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_update_audience_flattened_error(): +def test_list_data_streams_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -31484,48 +31235,45 @@ def test_update_audience_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_audience( - analytics_admin.UpdateAudienceRequest(), - audience=gaa_audience.Audience(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_update_audience_flattened_async(): +async def test_list_data_streams_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_audience.Audience() + call.return_value = analytics_admin.ListDataStreamsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_audience.Audience() + analytics_admin.ListDataStreamsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_audience( - audience=gaa_audience.Audience(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.list_data_streams( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].audience - mock_val = gaa_audience.Audience(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_audience_flattened_error_async(): +async def test_list_data_streams_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -31533,21 +31281,222 @@ async def test_update_audience_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_audience( - analytics_admin.UpdateAudienceRequest(), - audience=gaa_audience.Audience(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent="parent_value", + ) + + +def test_list_data_streams_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token="abc", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token="def", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_data_streams(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DataStream) for i in results) + + +def test_list_data_streams_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token="abc", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token="def", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_streams(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_data_streams_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token="abc", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token="def", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_streams( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.DataStream) for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_streams_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token="abc", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token="def", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_data_streams(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.ArchiveAudienceRequest, + analytics_admin.GetDataStreamRequest, dict, ], ) -def test_archive_audience(request_type, transport: str = "grpc"): +def test_get_data_stream(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31558,22 +31507,29 @@ def test_archive_audience(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.archive_audience(request) + call.return_value = resources.DataStream( + name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name="display_name_value", + ) + response = client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ArchiveAudienceRequest() + request = analytics_admin.GetDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DataStream) + assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == "display_name_value" -def test_archive_audience_empty_call(): +def test_get_data_stream_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -31582,17 +31538,17 @@ def test_archive_audience_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.archive_audience() + client.get_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveAudienceRequest() + assert args[0] == analytics_admin.GetDataStreamRequest() -def test_archive_audience_non_empty_request_with_auto_populated_field(): +def test_get_data_stream_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -31603,24 +31559,24 @@ def test_archive_audience_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ArchiveAudienceRequest( + request = analytics_admin.GetDataStreamRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.archive_audience(request=request) + client.get_data_stream(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveAudienceRequest( + assert args[0] == analytics_admin.GetDataStreamRequest( name="name_value", ) -def test_archive_audience_use_cached_wrapped_rpc(): +def test_get_data_stream_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -31634,23 +31590,21 @@ def test_archive_audience_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.archive_audience in client._transport._wrapped_methods + assert client._transport.get_data_stream in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.archive_audience - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc request = {} - client.archive_audience(request) + client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.archive_audience(request) + client.get_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -31658,7 +31612,7 @@ def test_archive_audience_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_archive_audience_empty_call_async(): +async def test_get_data_stream_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -31667,17 +31621,23 @@ async def test_archive_audience_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.archive_audience() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataStream( + name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name="display_name_value", + ) + ) + response = await client.get_data_stream() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ArchiveAudienceRequest() + assert args[0] == analytics_admin.GetDataStreamRequest() @pytest.mark.asyncio -async def test_archive_audience_async_use_cached_wrapped_rpc( +async def test_get_data_stream_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -31694,23 +31654,23 @@ async def test_archive_audience_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.archive_audience + client._client._transport.get_data_stream in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.archive_audience + client._client._transport.get_data_stream ] = mock_object request = {} - await client.archive_audience(request) + await client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.archive_audience(request) + await client.get_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -31718,8 +31678,8 @@ async def test_archive_audience_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_archive_audience_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.ArchiveAudienceRequest +async def test_get_data_stream_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetDataStreamRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -31731,41 +31691,50 @@ async def test_archive_audience_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.archive_audience(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataStream( + name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name="display_name_value", + ) + ) + response = await client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ArchiveAudienceRequest() + request = analytics_admin.GetDataStreamRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DataStream) + assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == "display_name_value" @pytest.mark.asyncio -async def test_archive_audience_async_from_dict(): - await test_archive_audience_async(request_type=dict) +async def test_get_data_stream_async_from_dict(): + await test_get_data_stream_async(request_type=dict) -def test_archive_audience_field_headers(): +def test_get_data_stream_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ArchiveAudienceRequest() + request = analytics_admin.GetDataStreamRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: - call.return_value = None - client.archive_audience(request) + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + call.return_value = resources.DataStream() + client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -31781,21 +31750,23 @@ def test_archive_audience_field_headers(): @pytest.mark.asyncio -async def test_archive_audience_field_headers_async(): +async def test_get_data_stream_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ArchiveAudienceRequest() + request = analytics_admin.GetDataStreamRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.archive_audience(request) + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataStream() + ) + await client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -31810,49 +31781,138 @@ async def test_archive_audience_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetSearchAds360LinkRequest, - dict, - ], -) -def test_get_search_ads360_link(request_type, transport: str = "grpc"): +def test_get_data_stream_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link( + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_stream( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", ) - response = client.get_search_ads360_link(request) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_data_stream), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataStream() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_stream( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetAudienceRequest, + dict, + ], +) +def test_get_audience(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = audience.Audience( + name="name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + response = client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetSearchAds360LinkRequest() + request = analytics_admin.GetAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) + assert isinstance(response, audience.Audience) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) -def test_get_search_ads360_link_empty_call(): +def test_get_audience_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -31861,19 +31921,17 @@ def test_get_search_ads360_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_search_ads360_link() + client.get_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetSearchAds360LinkRequest() + assert args[0] == analytics_admin.GetAudienceRequest() -def test_get_search_ads360_link_non_empty_request_with_auto_populated_field(): +def test_get_audience_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -31884,26 +31942,24 @@ def test_get_search_ads360_link_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetSearchAds360LinkRequest( + request = analytics_admin.GetAudienceRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_search_ads360_link(request=request) + client.get_audience(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetSearchAds360LinkRequest( + assert args[0] == analytics_admin.GetAudienceRequest( name="name_value", ) -def test_get_search_ads360_link_use_cached_wrapped_rpc(): +def test_get_audience_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -31917,26 +31973,21 @@ def test_get_search_ads360_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_search_ads360_link - in client._transport._wrapped_methods - ) + assert client._transport.get_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_search_ads360_link - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_audience] = mock_rpc request = {} - client.get_search_ads360_link(request) + client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_search_ads360_link(request) + client.get_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -31944,7 +31995,7 @@ def test_get_search_ads360_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_search_ads360_link_empty_call_async(): +async def test_get_audience_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -31953,25 +32004,26 @@ async def test_get_search_ads360_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link( + audience.Audience( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.get_search_ads360_link() + response = await client.get_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetSearchAds360LinkRequest() + assert args[0] == analytics_admin.GetAudienceRequest() @pytest.mark.asyncio -async def test_get_search_ads360_link_async_use_cached_wrapped_rpc( +async def test_get_audience_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -31988,23 +32040,23 @@ async def test_get_search_ads360_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_search_ads360_link + client._client._transport.get_audience in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_search_ads360_link + client._client._transport.get_audience ] = mock_object request = {} - await client.get_search_ads360_link(request) + await client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_search_ads360_link(request) + await client.get_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -32012,9 +32064,8 @@ async def test_get_search_ads360_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_search_ads360_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.GetSearchAds360LinkRequest, +async def test_get_audience_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetAudienceRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -32026,54 +32077,59 @@ async def test_get_search_ads360_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link( + audience.Audience( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.get_search_ads360_link(request) + response = await client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetSearchAds360LinkRequest() + request = analytics_admin.GetAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) + assert isinstance(response, audience.Audience) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) @pytest.mark.asyncio -async def test_get_search_ads360_link_async_from_dict(): - await test_get_search_ads360_link_async(request_type=dict) +async def test_get_audience_async_from_dict(): + await test_get_audience_async(request_type=dict) -def test_get_search_ads360_link_field_headers(): +def test_get_audience_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetSearchAds360LinkRequest() + request = analytics_admin.GetAudienceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: - call.return_value = resources.SearchAds360Link() - client.get_search_ads360_link(request) + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + call.return_value = audience.Audience() + client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -32089,25 +32145,21 @@ def test_get_search_ads360_link_field_headers(): @pytest.mark.asyncio -async def test_get_search_ads360_link_field_headers_async(): +async def test_get_audience_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetSearchAds360LinkRequest() + request = analytics_admin.GetAudienceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link() - ) - await client.get_search_ads360_link(request) + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience()) + await client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -32122,20 +32174,18 @@ async def test_get_search_ads360_link_field_headers_async(): ) in kw["metadata"] -def test_get_search_ads360_link_flattened(): +def test_get_audience_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link() + call.return_value = audience.Audience() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_search_ads360_link( + client.get_audience( name="name_value", ) @@ -32148,7 +32198,7 @@ def test_get_search_ads360_link_flattened(): assert arg == mock_val -def test_get_search_ads360_link_flattened_error(): +def test_get_audience_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -32156,31 +32206,27 @@ def test_get_search_ads360_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_search_ads360_link( - analytics_admin.GetSearchAds360LinkRequest(), + client.get_audience( + analytics_admin.GetAudienceRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_search_ads360_link_flattened_async(): +async def test_get_audience_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link() + call.return_value = audience.Audience() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_search_ads360_link( + response = await client.get_audience( name="name_value", ) @@ -32194,7 +32240,7 @@ async def test_get_search_ads360_link_flattened_async(): @pytest.mark.asyncio -async def test_get_search_ads360_link_flattened_error_async(): +async def test_get_audience_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -32202,8 +32248,8 @@ async def test_get_search_ads360_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_search_ads360_link( - analytics_admin.GetSearchAds360LinkRequest(), + await client.get_audience( + analytics_admin.GetAudienceRequest(), name="name_value", ) @@ -32211,11 +32257,11 @@ async def test_get_search_ads360_link_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListSearchAds360LinksRequest, + analytics_admin.ListAudiencesRequest, dict, ], ) -def test_list_search_ads360_links(request_type, transport: str = "grpc"): +def test_list_audiences(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -32226,27 +32272,25 @@ def test_list_search_ads360_links(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListSearchAds360LinksResponse( + call.return_value = analytics_admin.ListAudiencesResponse( next_page_token="next_page_token_value", ) - response = client.list_search_ads360_links(request) + response = client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListSearchAds360LinksRequest() + request = analytics_admin.ListAudiencesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSearchAds360LinksPager) + assert isinstance(response, pagers.ListAudiencesPager) assert response.next_page_token == "next_page_token_value" -def test_list_search_ads360_links_empty_call(): +def test_list_audiences_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -32255,19 +32299,17 @@ def test_list_search_ads360_links_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_search_ads360_links() + client.list_audiences() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListSearchAds360LinksRequest() + assert args[0] == analytics_admin.ListAudiencesRequest() -def test_list_search_ads360_links_non_empty_request_with_auto_populated_field(): +def test_list_audiences_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -32278,28 +32320,26 @@ def test_list_search_ads360_links_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListSearchAds360LinksRequest( + request = analytics_admin.ListAudiencesRequest( parent="parent_value", page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_search_ads360_links(request=request) + client.list_audiences(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListSearchAds360LinksRequest( + assert args[0] == analytics_admin.ListAudiencesRequest( parent="parent_value", page_token="page_token_value", ) -def test_list_search_ads360_links_use_cached_wrapped_rpc(): +def test_list_audiences_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -32313,26 +32353,21 @@ def test_list_search_ads360_links_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_search_ads360_links - in client._transport._wrapped_methods - ) + assert client._transport.list_audiences in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_search_ads360_links - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_audiences] = mock_rpc request = {} - client.list_search_ads360_links(request) + client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_search_ads360_links(request) + client.list_audiences(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -32340,7 +32375,7 @@ def test_list_search_ads360_links_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_search_ads360_links_empty_call_async(): +async def test_list_audiences_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -32349,23 +32384,21 @@ async def test_list_search_ads360_links_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSearchAds360LinksResponse( + analytics_admin.ListAudiencesResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_search_ads360_links() + response = await client.list_audiences() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListSearchAds360LinksRequest() + assert args[0] == analytics_admin.ListAudiencesRequest() @pytest.mark.asyncio -async def test_list_search_ads360_links_async_use_cached_wrapped_rpc( +async def test_list_audiences_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -32382,23 +32415,23 @@ async def test_list_search_ads360_links_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_search_ads360_links + client._client._transport.list_audiences in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_search_ads360_links + client._client._transport.list_audiences ] = mock_object request = {} - await client.list_search_ads360_links(request) + await client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_search_ads360_links(request) + await client.list_audiences(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -32406,9 +32439,8 @@ async def test_list_search_ads360_links_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_search_ads360_links_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.ListSearchAds360LinksRequest, +async def test_list_audiences_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.ListAudiencesRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -32420,50 +32452,46 @@ async def test_list_search_ads360_links_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSearchAds360LinksResponse( + analytics_admin.ListAudiencesResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_search_ads360_links(request) + response = await client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListSearchAds360LinksRequest() + request = analytics_admin.ListAudiencesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSearchAds360LinksAsyncPager) + assert isinstance(response, pagers.ListAudiencesAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_list_search_ads360_links_async_from_dict(): - await test_list_search_ads360_links_async(request_type=dict) +async def test_list_audiences_async_from_dict(): + await test_list_audiences_async(request_type=dict) -def test_list_search_ads360_links_field_headers(): +def test_list_audiences_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListSearchAds360LinksRequest() + request = analytics_admin.ListAudiencesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: - call.return_value = analytics_admin.ListSearchAds360LinksResponse() - client.list_search_ads360_links(request) + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: + call.return_value = analytics_admin.ListAudiencesResponse() + client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -32479,25 +32507,23 @@ def test_list_search_ads360_links_field_headers(): @pytest.mark.asyncio -async def test_list_search_ads360_links_field_headers_async(): +async def test_list_audiences_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListSearchAds360LinksRequest() + request = analytics_admin.ListAudiencesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSearchAds360LinksResponse() + analytics_admin.ListAudiencesResponse() ) - await client.list_search_ads360_links(request) + await client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -32512,20 +32538,18 @@ async def test_list_search_ads360_links_field_headers_async(): ) in kw["metadata"] -def test_list_search_ads360_links_flattened(): +def test_list_audiences_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListSearchAds360LinksResponse() + call.return_value = analytics_admin.ListAudiencesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_search_ads360_links( + client.list_audiences( parent="parent_value", ) @@ -32538,7 +32562,7 @@ def test_list_search_ads360_links_flattened(): assert arg == mock_val -def test_list_search_ads360_links_flattened_error(): +def test_list_audiences_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -32546,31 +32570,29 @@ def test_list_search_ads360_links_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_search_ads360_links( - analytics_admin.ListSearchAds360LinksRequest(), + client.list_audiences( + analytics_admin.ListAudiencesRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_search_ads360_links_flattened_async(): +async def test_list_audiences_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListSearchAds360LinksResponse() + call.return_value = analytics_admin.ListAudiencesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSearchAds360LinksResponse() + analytics_admin.ListAudiencesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_search_ads360_links( + response = await client.list_audiences( parent="parent_value", ) @@ -32584,7 +32606,7 @@ async def test_list_search_ads360_links_flattened_async(): @pytest.mark.asyncio -async def test_list_search_ads360_links_flattened_error_async(): +async def test_list_audiences_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -32592,46 +32614,44 @@ async def test_list_search_ads360_links_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_search_ads360_links( - analytics_admin.ListSearchAds360LinksRequest(), + await client.list_audiences( + analytics_admin.ListAudiencesRequest(), parent="parent_value", ) -def test_list_search_ads360_links_pager(transport_name: str = "grpc"): +def test_list_audiences_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), ], next_page_token="abc", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[], + analytics_admin.ListAudiencesResponse( + audiences=[], next_page_token="def", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), ], next_page_token="ghi", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), ], ), RuntimeError, @@ -32643,9 +32663,7 @@ def test_list_search_ads360_links_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_search_ads360_links( - request={}, retry=retry, timeout=timeout - ) + pager = client.list_audiences(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -32653,93 +32671,89 @@ def test_list_search_ads360_links_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.SearchAds360Link) for i in results) + assert all(isinstance(i, audience.Audience) for i in results) -def test_list_search_ads360_links_pages(transport_name: str = "grpc"): +def test_list_audiences_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_search_ads360_links), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_audiences), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), ], next_page_token="abc", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[], + analytics_admin.ListAudiencesResponse( + audiences=[], next_page_token="def", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), ], next_page_token="ghi", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - ], - ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), RuntimeError, ) - pages = list(client.list_search_ads360_links(request={}).pages) + pages = list(client.list_audiences(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_search_ads360_links_async_pager(): +async def test_list_audiences_async_pager(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_search_ads360_links), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_audiences), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), ], next_page_token="abc", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[], + analytics_admin.ListAudiencesResponse( + audiences=[], next_page_token="def", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), ], next_page_token="ghi", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), ], ), RuntimeError, ) - async_pager = await client.list_search_ads360_links( + async_pager = await client.list_audiences( request={}, ) assert async_pager.next_page_token == "abc" @@ -32748,45 +32762,43 @@ async def test_list_search_ads360_links_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, resources.SearchAds360Link) for i in responses) + assert all(isinstance(i, audience.Audience) for i in responses) @pytest.mark.asyncio -async def test_list_search_ads360_links_async_pages(): +async def test_list_audiences_async_pages(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_search_ads360_links), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_audiences), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), ], next_page_token="abc", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[], + analytics_admin.ListAudiencesResponse( + audiences=[], next_page_token="def", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), ], next_page_token="ghi", ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), ], ), RuntimeError, @@ -32795,7 +32807,7 @@ async def test_list_search_ads360_links_async_pages(): # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 async for page_ in ( # pragma: no branch - await client.list_search_ads360_links(request={}) + await client.list_audiences(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -32805,11 +32817,11 @@ async def test_list_search_ads360_links_async_pages(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateSearchAds360LinkRequest, + analytics_admin.CreateAudienceRequest, dict, ], ) -def test_create_search_ads360_link(request_type, transport: str = "grpc"): +def test_create_audience(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -32820,31 +32832,38 @@ def test_create_search_ads360_link(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link( + call.return_value = gaa_audience.Audience( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) - response = client.create_search_ads360_link(request) + response = client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateSearchAds360LinkRequest() + request = analytics_admin.CreateAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) + assert isinstance(response, gaa_audience.Audience) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) -def test_create_search_ads360_link_empty_call(): +def test_create_audience_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -32853,19 +32872,17 @@ def test_create_search_ads360_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_search_ads360_link() + client.create_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSearchAds360LinkRequest() + assert args[0] == analytics_admin.CreateAudienceRequest() -def test_create_search_ads360_link_non_empty_request_with_auto_populated_field(): +def test_create_audience_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -32876,26 +32893,24 @@ def test_create_search_ads360_link_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateSearchAds360LinkRequest( + request = analytics_admin.CreateAudienceRequest( parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_search_ads360_link(request=request) + client.create_audience(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSearchAds360LinkRequest( + assert args[0] == analytics_admin.CreateAudienceRequest( parent="parent_value", ) -def test_create_search_ads360_link_use_cached_wrapped_rpc(): +def test_create_audience_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -32909,26 +32924,21 @@ def test_create_search_ads360_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_search_ads360_link - in client._transport._wrapped_methods - ) + assert client._transport.create_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_search_ads360_link - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_audience] = mock_rpc request = {} - client.create_search_ads360_link(request) + client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_search_ads360_link(request) + client.create_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -32936,7 +32946,7 @@ def test_create_search_ads360_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_search_ads360_link_empty_call_async(): +async def test_create_audience_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -32945,25 +32955,26 @@ async def test_create_search_ads360_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link( + gaa_audience.Audience( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.create_search_ads360_link() + response = await client.create_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSearchAds360LinkRequest() + assert args[0] == analytics_admin.CreateAudienceRequest() @pytest.mark.asyncio -async def test_create_search_ads360_link_async_use_cached_wrapped_rpc( +async def test_create_audience_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -32980,23 +32991,23 @@ async def test_create_search_ads360_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_search_ads360_link + client._client._transport.create_audience in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_search_ads360_link + client._client._transport.create_audience ] = mock_object request = {} - await client.create_search_ads360_link(request) + await client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_search_ads360_link(request) + await client.create_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -33004,9 +33015,8 @@ async def test_create_search_ads360_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_search_ads360_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateSearchAds360LinkRequest, +async def test_create_audience_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.CreateAudienceRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -33018,54 +33028,59 @@ async def test_create_search_ads360_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link( + gaa_audience.Audience( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) ) - response = await client.create_search_ads360_link(request) + response = await client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateSearchAds360LinkRequest() + request = analytics_admin.CreateAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) + assert isinstance(response, gaa_audience.Audience) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) @pytest.mark.asyncio -async def test_create_search_ads360_link_async_from_dict(): - await test_create_search_ads360_link_async(request_type=dict) +async def test_create_audience_async_from_dict(): + await test_create_audience_async(request_type=dict) -def test_create_search_ads360_link_field_headers(): +def test_create_audience_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateSearchAds360LinkRequest() + request = analytics_admin.CreateAudienceRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: - call.return_value = resources.SearchAds360Link() - client.create_search_ads360_link(request) + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: + call.return_value = gaa_audience.Audience() + client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -33081,25 +33096,23 @@ def test_create_search_ads360_link_field_headers(): @pytest.mark.asyncio -async def test_create_search_ads360_link_field_headers_async(): +async def test_create_audience_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateSearchAds360LinkRequest() + request = analytics_admin.CreateAudienceRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link() + gaa_audience.Audience() ) - await client.create_search_ads360_link(request) + await client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -33114,22 +33127,20 @@ async def test_create_search_ads360_link_field_headers_async(): ) in kw["metadata"] -def test_create_search_ads360_link_flattened(): +def test_create_audience_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link() + call.return_value = gaa_audience.Audience() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_search_ads360_link( + client.create_audience( parent="parent_value", - search_ads_360_link=resources.SearchAds360Link(name="name_value"), + audience=gaa_audience.Audience(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -33139,12 +33150,12 @@ def test_create_search_ads360_link_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].search_ads_360_link - mock_val = resources.SearchAds360Link(name="name_value") + arg = args[0].audience + mock_val = gaa_audience.Audience(name="name_value") assert arg == mock_val -def test_create_search_ads360_link_flattened_error(): +def test_create_audience_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -33152,34 +33163,32 @@ def test_create_search_ads360_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_search_ads360_link( - analytics_admin.CreateSearchAds360LinkRequest(), + client.create_audience( + analytics_admin.CreateAudienceRequest(), parent="parent_value", - search_ads_360_link=resources.SearchAds360Link(name="name_value"), + audience=gaa_audience.Audience(name="name_value"), ) @pytest.mark.asyncio -async def test_create_search_ads360_link_flattened_async(): +async def test_create_audience_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link() + call.return_value = gaa_audience.Audience() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link() + gaa_audience.Audience() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_search_ads360_link( + response = await client.create_audience( parent="parent_value", - search_ads_360_link=resources.SearchAds360Link(name="name_value"), + audience=gaa_audience.Audience(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -33189,13 +33198,13 @@ async def test_create_search_ads360_link_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].search_ads_360_link - mock_val = resources.SearchAds360Link(name="name_value") + arg = args[0].audience + mock_val = gaa_audience.Audience(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_create_search_ads360_link_flattened_error_async(): +async def test_create_audience_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -33203,21 +33212,21 @@ async def test_create_search_ads360_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_search_ads360_link( - analytics_admin.CreateSearchAds360LinkRequest(), + await client.create_audience( + analytics_admin.CreateAudienceRequest(), parent="parent_value", - search_ads_360_link=resources.SearchAds360Link(name="name_value"), + audience=gaa_audience.Audience(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteSearchAds360LinkRequest, + analytics_admin.UpdateAudienceRequest, dict, ], ) -def test_delete_search_ads360_link(request_type, transport: str = "grpc"): +def test_update_audience(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -33228,24 +33237,38 @@ def test_delete_search_ads360_link(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_search_ads360_link(request) + call.return_value = gaa_audience.Audience( + name="name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + response = client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteSearchAds360LinkRequest() + request = analytics_admin.UpdateAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, gaa_audience.Audience) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) -def test_delete_search_ads360_link_empty_call(): +def test_update_audience_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -33254,19 +33277,17 @@ def test_delete_search_ads360_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_search_ads360_link() + client.update_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest() + assert args[0] == analytics_admin.UpdateAudienceRequest() -def test_delete_search_ads360_link_non_empty_request_with_auto_populated_field(): +def test_update_audience_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -33277,26 +33298,20 @@ def test_delete_search_ads360_link_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteSearchAds360LinkRequest( - name="name_value", - ) + request = analytics_admin.UpdateAudienceRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_search_ads360_link(request=request) + client.update_audience(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest( - name="name_value", - ) + assert args[0] == analytics_admin.UpdateAudienceRequest() -def test_delete_search_ads360_link_use_cached_wrapped_rpc(): +def test_update_audience_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -33310,26 +33325,21 @@ def test_delete_search_ads360_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_search_ads360_link - in client._transport._wrapped_methods - ) + assert client._transport.update_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_search_ads360_link - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_audience] = mock_rpc request = {} - client.delete_search_ads360_link(request) + client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_search_ads360_link(request) + client.update_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -33337,7 +33347,7 @@ def test_delete_search_ads360_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_search_ads360_link_empty_call_async(): +async def test_update_audience_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -33346,19 +33356,26 @@ async def test_delete_search_ads360_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_search_ads360_link() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_audience.Audience( + name="name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + ) + response = await client.update_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest() + assert args[0] == analytics_admin.UpdateAudienceRequest() @pytest.mark.asyncio -async def test_delete_search_ads360_link_async_use_cached_wrapped_rpc( +async def test_update_audience_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -33375,23 +33392,23 @@ async def test_delete_search_ads360_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_search_ads360_link + client._client._transport.update_audience in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_search_ads360_link + client._client._transport.update_audience ] = mock_object request = {} - await client.delete_search_ads360_link(request) + await client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_search_ads360_link(request) + await client.update_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -33399,9 +33416,8 @@ async def test_delete_search_ads360_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_search_ads360_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteSearchAds360LinkRequest, +async def test_update_audience_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.UpdateAudienceRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -33413,45 +33429,59 @@ async def test_delete_search_ads360_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_search_ads360_link(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_audience.Audience( + name="name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + ) + response = await client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteSearchAds360LinkRequest() + request = analytics_admin.UpdateAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, gaa_audience.Audience) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) @pytest.mark.asyncio -async def test_delete_search_ads360_link_async_from_dict(): - await test_delete_search_ads360_link_async(request_type=dict) +async def test_update_audience_async_from_dict(): + await test_update_audience_async(request_type=dict) -def test_delete_search_ads360_link_field_headers(): +def test_update_audience_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteSearchAds360LinkRequest() + request = analytics_admin.UpdateAudienceRequest() - request.name = "name_value" + request.audience.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: - call.return_value = None - client.delete_search_ads360_link(request) + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + call.return_value = gaa_audience.Audience() + client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -33462,28 +33492,28 @@ def test_delete_search_ads360_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "audience.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_search_ads360_link_field_headers_async(): +async def test_update_audience_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteSearchAds360LinkRequest() + request = analytics_admin.UpdateAudienceRequest() - request.name = "name_value" + request.audience.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_search_ads360_link(request) + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_audience.Audience() + ) + await client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -33494,37 +33524,39 @@ async def test_delete_search_ads360_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "audience.name=name_value", ) in kw["metadata"] -def test_delete_search_ads360_link_flattened(): +def test_update_audience_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = gaa_audience.Audience() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_search_ads360_link( - name="name_value", + client.update_audience( + audience=gaa_audience.Audience(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].audience + mock_val = gaa_audience.Audience(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_delete_search_ads360_link_flattened_error(): +def test_update_audience_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -33532,43 +33564,48 @@ def test_delete_search_ads360_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_search_ads360_link( - analytics_admin.DeleteSearchAds360LinkRequest(), - name="name_value", + client.update_audience( + analytics_admin.UpdateAudienceRequest(), + audience=gaa_audience.Audience(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_delete_search_ads360_link_flattened_async(): +async def test_update_audience_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = gaa_audience.Audience() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_audience.Audience() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_search_ads360_link( - name="name_value", + response = await client.update_audience( + audience=gaa_audience.Audience(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].audience + mock_val = gaa_audience.Audience(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_delete_search_ads360_link_flattened_error_async(): +async def test_update_audience_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -33576,20 +33613,21 @@ async def test_delete_search_ads360_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_search_ads360_link( - analytics_admin.DeleteSearchAds360LinkRequest(), - name="name_value", + await client.update_audience( + analytics_admin.UpdateAudienceRequest(), + audience=gaa_audience.Audience(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateSearchAds360LinkRequest, + analytics_admin.ArchiveAudienceRequest, dict, ], ) -def test_update_search_ads360_link(request_type, transport: str = "grpc"): +def test_archive_audience(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -33600,31 +33638,22 @@ def test_update_search_ads360_link(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - ) - response = client.update_search_ads360_link(request) + call.return_value = None + response = client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateSearchAds360LinkRequest() + request = analytics_admin.ArchiveAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response is None -def test_update_search_ads360_link_empty_call(): +def test_archive_audience_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -33633,19 +33662,17 @@ def test_update_search_ads360_link_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_search_ads360_link() + client.archive_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() + assert args[0] == analytics_admin.ArchiveAudienceRequest() -def test_update_search_ads360_link_non_empty_request_with_auto_populated_field(): +def test_archive_audience_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -33656,22 +33683,24 @@ def test_update_search_ads360_link_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateSearchAds360LinkRequest() + request = analytics_admin.ArchiveAudienceRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_search_ads360_link(request=request) + client.archive_audience(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() + assert args[0] == analytics_admin.ArchiveAudienceRequest( + name="name_value", + ) -def test_update_search_ads360_link_use_cached_wrapped_rpc(): +def test_archive_audience_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -33685,10 +33714,7 @@ def test_update_search_ads360_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_search_ads360_link - in client._transport._wrapped_methods - ) + assert client._transport.archive_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -33696,15 +33722,15 @@ def test_update_search_ads360_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_search_ads360_link + client._transport.archive_audience ] = mock_rpc request = {} - client.update_search_ads360_link(request) + client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_search_ads360_link(request) + client.archive_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -33712,7 +33738,7 @@ def test_update_search_ads360_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_search_ads360_link_empty_call_async(): +async def test_archive_audience_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -33721,25 +33747,17 @@ async def test_update_search_ads360_link_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - ) - ) - response = await client.update_search_ads360_link() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_audience() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() + assert args[0] == analytics_admin.ArchiveAudienceRequest() @pytest.mark.asyncio -async def test_update_search_ads360_link_async_use_cached_wrapped_rpc( +async def test_archive_audience_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -33756,23 +33774,23 @@ async def test_update_search_ads360_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_search_ads360_link + client._client._transport.archive_audience in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_search_ads360_link + client._client._transport.archive_audience ] = mock_object request = {} - await client.update_search_ads360_link(request) + await client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_search_ads360_link(request) + await client.archive_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -33780,9 +33798,8 @@ async def test_update_search_ads360_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_search_ads360_link_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateSearchAds360LinkRequest, +async def test_archive_audience_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.ArchiveAudienceRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -33794,54 +33811,41 @@ async def test_update_search_ads360_link_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - ) - ) - response = await client.update_search_ads360_link(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateSearchAds360LinkRequest() + request = analytics_admin.ArchiveAudienceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response is None @pytest.mark.asyncio -async def test_update_search_ads360_link_async_from_dict(): - await test_update_search_ads360_link_async(request_type=dict) +async def test_archive_audience_async_from_dict(): + await test_archive_audience_async(request_type=dict) -def test_update_search_ads360_link_field_headers(): +def test_archive_audience_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateSearchAds360LinkRequest() + request = analytics_admin.ArchiveAudienceRequest() - request.search_ads_360_link.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: - call.return_value = resources.SearchAds360Link() - client.update_search_ads360_link(request) + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + call.return_value = None + client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -33852,30 +33856,26 @@ def test_update_search_ads360_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "search_ads_360_link.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_search_ads360_link_field_headers_async(): +async def test_archive_audience_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateSearchAds360LinkRequest() + request = analytics_admin.ArchiveAudienceRequest() - request.search_ads_360_link.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link() - ) - await client.update_search_ads360_link(request) + with mock.patch.object(type(client.transport.archive_audience), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -33886,114 +33886,18 @@ async def test_update_search_ads360_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "search_ads_360_link.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_search_ads360_link_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_search_ads360_link( - search_ads_360_link=resources.SearchAds360Link(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].search_ads_360_link - mock_val = resources.SearchAds360Link(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_search_ads360_link_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_search_ads360_link( - analytics_admin.UpdateSearchAds360LinkRequest(), - search_ads_360_link=resources.SearchAds360Link(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_search_ads360_link_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_search_ads360_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.SearchAds360Link() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.SearchAds360Link() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_search_ads360_link( - search_ads_360_link=resources.SearchAds360Link(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].search_ads_360_link - mock_val = resources.SearchAds360Link(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_search_ads360_link_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_search_ads360_link( - analytics_admin.UpdateSearchAds360LinkRequest(), - search_ads_360_link=resources.SearchAds360Link(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAttributionSettingsRequest, + analytics_admin.GetSearchAds360LinkRequest, dict, ], ) -def test_get_attribution_settings(request_type, transport: str = "grpc"): +def test_get_search_ads360_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -34005,46 +33909,30 @@ def test_get_attribution_settings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AttributionSettings( + call.return_value = resources.SearchAds360Link( name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) - response = client.get_attribution_settings(request) + response = client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAttributionSettingsRequest() + request = analytics_admin.GetSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AttributionSettings) + assert isinstance(response, resources.SearchAds360Link) assert response.name == "name_value" - assert ( - response.acquisition_conversion_event_lookback_window - == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS - ) - assert ( - response.other_conversion_event_lookback_window - == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS - ) - assert ( - response.reporting_attribution_model - == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN - ) - assert ( - response.ads_web_conversion_data_export_scope - == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET - ) + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_get_attribution_settings_empty_call(): +def test_get_search_ads360_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -34054,18 +33942,18 @@ def test_get_attribution_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_attribution_settings() + client.get_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAttributionSettingsRequest() + assert args[0] == analytics_admin.GetSearchAds360LinkRequest() -def test_get_attribution_settings_non_empty_request_with_auto_populated_field(): +def test_get_search_ads360_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -34076,26 +33964,26 @@ def test_get_attribution_settings_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetAttributionSettingsRequest( + request = analytics_admin.GetSearchAds360LinkRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_attribution_settings(request=request) + client.get_search_ads360_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAttributionSettingsRequest( + assert args[0] == analytics_admin.GetSearchAds360LinkRequest( name="name_value", ) -def test_get_attribution_settings_use_cached_wrapped_rpc(): +def test_get_search_ads360_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -34110,7 +33998,7 @@ def test_get_attribution_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_attribution_settings + client._transport.get_search_ads360_link in client._transport._wrapped_methods ) @@ -34120,15 +34008,15 @@ def test_get_attribution_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_attribution_settings + client._transport.get_search_ads360_link ] = mock_rpc request = {} - client.get_attribution_settings(request) + client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attribution_settings(request) + client.get_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -34136,7 +34024,7 @@ def test_get_attribution_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_attribution_settings_empty_call_async(): +async def test_get_search_ads360_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -34146,26 +34034,24 @@ async def test_get_attribution_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings( + resources.SearchAds360Link( name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) ) - response = await client.get_attribution_settings() + response = await client.get_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAttributionSettingsRequest() + assert args[0] == analytics_admin.GetSearchAds360LinkRequest() @pytest.mark.asyncio -async def test_get_attribution_settings_async_use_cached_wrapped_rpc( +async def test_get_search_ads360_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -34182,23 +34068,23 @@ async def test_get_attribution_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_attribution_settings + client._client._transport.get_search_ads360_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_attribution_settings + client._client._transport.get_search_ads360_link ] = mock_object request = {} - await client.get_attribution_settings(request) + await client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_attribution_settings(request) + await client.get_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -34206,9 +34092,9 @@ async def test_get_attribution_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_attribution_settings_async( +async def test_get_search_ads360_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetAttributionSettingsRequest, + request_type=analytics_admin.GetSearchAds360LinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -34221,69 +34107,53 @@ async def test_get_attribution_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings( + resources.SearchAds360Link( name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) ) - response = await client.get_attribution_settings(request) + response = await client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAttributionSettingsRequest() + request = analytics_admin.GetSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AttributionSettings) + assert isinstance(response, resources.SearchAds360Link) assert response.name == "name_value" - assert ( - response.acquisition_conversion_event_lookback_window - == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS - ) - assert ( - response.other_conversion_event_lookback_window - == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS - ) - assert ( - response.reporting_attribution_model - == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN - ) - assert ( - response.ads_web_conversion_data_export_scope - == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET - ) + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" @pytest.mark.asyncio -async def test_get_attribution_settings_async_from_dict(): - await test_get_attribution_settings_async(request_type=dict) +async def test_get_search_ads360_link_async_from_dict(): + await test_get_search_ads360_link_async(request_type=dict) -def test_get_attribution_settings_field_headers(): +def test_get_search_ads360_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAttributionSettingsRequest() + request = analytics_admin.GetSearchAds360LinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: - call.return_value = resources.AttributionSettings() - client.get_attribution_settings(request) + call.return_value = resources.SearchAds360Link() + client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -34299,25 +34169,25 @@ def test_get_attribution_settings_field_headers(): @pytest.mark.asyncio -async def test_get_attribution_settings_field_headers_async(): +async def test_get_search_ads360_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAttributionSettingsRequest() + request = analytics_admin.GetSearchAds360LinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings() + resources.SearchAds360Link() ) - await client.get_attribution_settings(request) + await client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -34332,20 +34202,20 @@ async def test_get_attribution_settings_field_headers_async(): ) in kw["metadata"] -def test_get_attribution_settings_flattened(): +def test_get_search_ads360_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AttributionSettings() + call.return_value = resources.SearchAds360Link() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_attribution_settings( + client.get_search_ads360_link( name="name_value", ) @@ -34358,7 +34228,7 @@ def test_get_attribution_settings_flattened(): assert arg == mock_val -def test_get_attribution_settings_flattened_error(): +def test_get_search_ads360_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -34366,31 +34236,31 @@ def test_get_attribution_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_attribution_settings( - analytics_admin.GetAttributionSettingsRequest(), + client.get_search_ads360_link( + analytics_admin.GetSearchAds360LinkRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_attribution_settings_flattened_async(): +async def test_get_search_ads360_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_attribution_settings), "__call__" + type(client.transport.get_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AttributionSettings() + call.return_value = resources.SearchAds360Link() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings() + resources.SearchAds360Link() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_attribution_settings( + response = await client.get_search_ads360_link( name="name_value", ) @@ -34404,7 +34274,7 @@ async def test_get_attribution_settings_flattened_async(): @pytest.mark.asyncio -async def test_get_attribution_settings_flattened_error_async(): +async def test_get_search_ads360_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -34412,8 +34282,8 @@ async def test_get_attribution_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_attribution_settings( - analytics_admin.GetAttributionSettingsRequest(), + await client.get_search_ads360_link( + analytics_admin.GetSearchAds360LinkRequest(), name="name_value", ) @@ -34421,11 +34291,11 @@ async def test_get_attribution_settings_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAttributionSettingsRequest, + analytics_admin.ListSearchAds360LinksRequest, dict, ], ) -def test_update_attribution_settings(request_type, transport: str = "grpc"): +def test_list_search_ads360_links(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -34437,46 +34307,26 @@ def test_update_attribution_settings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AttributionSettings( - name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + call.return_value = analytics_admin.ListSearchAds360LinksResponse( + next_page_token="next_page_token_value", ) - response = client.update_attribution_settings(request) + response = client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateAttributionSettingsRequest() + request = analytics_admin.ListSearchAds360LinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AttributionSettings) - assert response.name == "name_value" - assert ( - response.acquisition_conversion_event_lookback_window - == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS - ) - assert ( - response.other_conversion_event_lookback_window - == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS - ) - assert ( - response.reporting_attribution_model - == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN - ) - assert ( - response.ads_web_conversion_data_export_scope - == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET - ) + assert isinstance(response, pagers.ListSearchAds360LinksPager) + assert response.next_page_token == "next_page_token_value" -def test_update_attribution_settings_empty_call(): +def test_list_search_ads360_links_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -34486,18 +34336,18 @@ def test_update_attribution_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_attribution_settings() + client.list_search_ads360_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() + assert args[0] == analytics_admin.ListSearchAds360LinksRequest() -def test_update_attribution_settings_non_empty_request_with_auto_populated_field(): +def test_list_search_ads360_links_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -34508,22 +34358,28 @@ def test_update_attribution_settings_non_empty_request_with_auto_populated_field # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateAttributionSettingsRequest() + request = analytics_admin.ListSearchAds360LinksRequest( + parent="parent_value", + page_token="page_token_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_attribution_settings(request=request) + client.list_search_ads360_links(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() + assert args[0] == analytics_admin.ListSearchAds360LinksRequest( + parent="parent_value", + page_token="page_token_value", + ) -def test_update_attribution_settings_use_cached_wrapped_rpc(): +def test_list_search_ads360_links_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -34538,7 +34394,7 @@ def test_update_attribution_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_attribution_settings + client._transport.list_search_ads360_links in client._transport._wrapped_methods ) @@ -34548,15 +34404,15 @@ def test_update_attribution_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_attribution_settings + client._transport.list_search_ads360_links ] = mock_rpc request = {} - client.update_attribution_settings(request) + client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_attribution_settings(request) + client.list_search_ads360_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -34564,7 +34420,7 @@ def test_update_attribution_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_attribution_settings_empty_call_async(): +async def test_list_search_ads360_links_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -34574,26 +34430,22 @@ async def test_update_attribution_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings( - name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + analytics_admin.ListSearchAds360LinksResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_attribution_settings() + response = await client.list_search_ads360_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() + assert args[0] == analytics_admin.ListSearchAds360LinksRequest() @pytest.mark.asyncio -async def test_update_attribution_settings_async_use_cached_wrapped_rpc( +async def test_list_search_ads360_links_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -34610,23 +34462,23 @@ async def test_update_attribution_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_attribution_settings + client._client._transport.list_search_ads360_links in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_attribution_settings + client._client._transport.list_search_ads360_links ] = mock_object request = {} - await client.update_attribution_settings(request) + await client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_attribution_settings(request) + await client.list_search_ads360_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -34634,9 +34486,9 @@ async def test_update_attribution_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_attribution_settings_async( +async def test_list_search_ads360_links_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateAttributionSettingsRequest, + request_type=analytics_admin.ListSearchAds360LinksRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -34649,69 +34501,49 @@ async def test_update_attribution_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings( - name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + analytics_admin.ListSearchAds360LinksResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_attribution_settings(request) + response = await client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateAttributionSettingsRequest() + request = analytics_admin.ListSearchAds360LinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AttributionSettings) - assert response.name == "name_value" - assert ( - response.acquisition_conversion_event_lookback_window - == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS - ) - assert ( - response.other_conversion_event_lookback_window - == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS - ) - assert ( - response.reporting_attribution_model - == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN - ) - assert ( - response.ads_web_conversion_data_export_scope - == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET - ) + assert isinstance(response, pagers.ListSearchAds360LinksAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_update_attribution_settings_async_from_dict(): - await test_update_attribution_settings_async(request_type=dict) +async def test_list_search_ads360_links_async_from_dict(): + await test_list_search_ads360_links_async(request_type=dict) -def test_update_attribution_settings_field_headers(): +def test_list_search_ads360_links_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateAttributionSettingsRequest() + request = analytics_admin.ListSearchAds360LinksRequest() - request.attribution_settings.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: - call.return_value = resources.AttributionSettings() - client.update_attribution_settings(request) + call.return_value = analytics_admin.ListSearchAds360LinksResponse() + client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -34722,30 +34554,30 @@ def test_update_attribution_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "attribution_settings.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_attribution_settings_field_headers_async(): +async def test_list_search_ads360_links_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateAttributionSettingsRequest() + request = analytics_admin.ListSearchAds360LinksRequest() - request.attribution_settings.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings() + analytics_admin.ListSearchAds360LinksResponse() ) - await client.update_attribution_settings(request) + await client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -34756,41 +34588,37 @@ async def test_update_attribution_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "attribution_settings.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_attribution_settings_flattened(): +def test_list_search_ads360_links_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AttributionSettings() + call.return_value = analytics_admin.ListSearchAds360LinksResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_attribution_settings( - attribution_settings=resources.AttributionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_search_ads360_links( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].attribution_settings - mock_val = resources.AttributionSettings(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_update_attribution_settings_flattened_error(): +def test_list_search_ads360_links_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -34798,50 +34626,45 @@ def test_update_attribution_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_attribution_settings( - analytics_admin.UpdateAttributionSettingsRequest(), - attribution_settings=resources.AttributionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_search_ads360_links( + analytics_admin.ListSearchAds360LinksRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_update_attribution_settings_flattened_async(): +async def test_list_search_ads360_links_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_attribution_settings), "__call__" + type(client.transport.list_search_ads360_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AttributionSettings() + call.return_value = analytics_admin.ListSearchAds360LinksResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AttributionSettings() + analytics_admin.ListSearchAds360LinksResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_attribution_settings( - attribution_settings=resources.AttributionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.list_search_ads360_links( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].attribution_settings - mock_val = resources.AttributionSettings(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_attribution_settings_flattened_error_async(): +async def test_list_search_ads360_links_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -34849,21 +34672,224 @@ async def test_update_attribution_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_attribution_settings( - analytics_admin.UpdateAttributionSettingsRequest(), - attribution_settings=resources.AttributionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.list_search_ads360_links( + analytics_admin.ListSearchAds360LinksRequest(), + parent="parent_value", + ) + + +def test_list_search_ads360_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token="abc", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token="def", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_search_ads360_links( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SearchAds360Link) for i in results) + + +def test_list_search_ads360_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token="abc", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token="def", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + pages = list(client.list_search_ads360_links(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token="abc", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token="def", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_search_ads360_links( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SearchAds360Link) for i in responses) + + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token="abc", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token="def", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_search_ads360_links(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.RunAccessReportRequest, + analytics_admin.CreateSearchAds360LinkRequest, dict, ], ) -def test_run_access_report(request_type, transport: str = "grpc"): +def test_create_search_ads360_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -34875,26 +34901,30 @@ def test_run_access_report(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.RunAccessReportResponse( - row_count=992, + call.return_value = resources.SearchAds360Link( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) - response = client.run_access_report(request) + response = client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.RunAccessReportRequest() + request = analytics_admin.CreateSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.RunAccessReportResponse) - assert response.row_count == 992 + assert isinstance(response, resources.SearchAds360Link) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_run_access_report_empty_call(): +def test_create_search_ads360_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -34904,18 +34934,18 @@ def test_run_access_report_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.run_access_report() + client.create_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.RunAccessReportRequest() + assert args[0] == analytics_admin.CreateSearchAds360LinkRequest() -def test_run_access_report_non_empty_request_with_auto_populated_field(): +def test_create_search_ads360_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -34926,28 +34956,26 @@ def test_run_access_report_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.RunAccessReportRequest( - entity="entity_value", - time_zone="time_zone_value", + request = analytics_admin.CreateSearchAds360LinkRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.run_access_report(request=request) + client.create_search_ads360_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.RunAccessReportRequest( - entity="entity_value", - time_zone="time_zone_value", + assert args[0] == analytics_admin.CreateSearchAds360LinkRequest( + parent="parent_value", ) -def test_run_access_report_use_cached_wrapped_rpc(): +def test_create_search_ads360_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -34961,7 +34989,10 @@ def test_run_access_report_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.run_access_report in client._transport._wrapped_methods + assert ( + client._transport.create_search_ads360_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -34969,15 +35000,15 @@ def test_run_access_report_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.run_access_report + client._transport.create_search_ads360_link ] = mock_rpc request = {} - client.run_access_report(request) + client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.run_access_report(request) + client.create_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -34985,7 +35016,7 @@ def test_run_access_report_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_run_access_report_empty_call_async(): +async def test_create_search_ads360_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -34995,22 +35026,24 @@ async def test_run_access_report_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.RunAccessReportResponse( - row_count=992, + resources.SearchAds360Link( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) ) - response = await client.run_access_report() + response = await client.create_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.RunAccessReportRequest() + assert args[0] == analytics_admin.CreateSearchAds360LinkRequest() @pytest.mark.asyncio -async def test_run_access_report_async_use_cached_wrapped_rpc( +async def test_create_search_ads360_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -35027,23 +35060,23 @@ async def test_run_access_report_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.run_access_report + client._client._transport.create_search_ads360_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.run_access_report + client._client._transport.create_search_ads360_link ] = mock_object request = {} - await client.run_access_report(request) + await client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.run_access_report(request) + await client.create_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -35051,8 +35084,9 @@ async def test_run_access_report_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_run_access_report_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.RunAccessReportRequest +async def test_create_search_ads360_link_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.CreateSearchAds360LinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -35065,49 +35099,53 @@ async def test_run_access_report_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.RunAccessReportResponse( - row_count=992, + resources.SearchAds360Link( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) ) - response = await client.run_access_report(request) + response = await client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.RunAccessReportRequest() + request = analytics_admin.CreateSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.RunAccessReportResponse) - assert response.row_count == 992 + assert isinstance(response, resources.SearchAds360Link) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" @pytest.mark.asyncio -async def test_run_access_report_async_from_dict(): - await test_run_access_report_async(request_type=dict) +async def test_create_search_ads360_link_async_from_dict(): + await test_create_search_ads360_link_async(request_type=dict) -def test_run_access_report_field_headers(): +def test_create_search_ads360_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.RunAccessReportRequest() + request = analytics_admin.CreateSearchAds360LinkRequest() - request.entity = "entity_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: - call.return_value = analytics_admin.RunAccessReportResponse() - client.run_access_report(request) + call.return_value = resources.SearchAds360Link() + client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -35118,30 +35156,30 @@ def test_run_access_report_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "entity=entity_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_run_access_report_field_headers_async(): +async def test_create_search_ads360_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.RunAccessReportRequest() + request = analytics_admin.CreateSearchAds360LinkRequest() - request.entity = "entity_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.run_access_report), "__call__" + type(client.transport.create_search_ads360_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.RunAccessReportResponse() + resources.SearchAds360Link() ) - await client.run_access_report(request) + await client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -35152,18 +35190,114 @@ async def test_run_access_report_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "entity=entity_value", + "parent=parent_value", ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.CreateAccessBindingRequest, +def test_create_search_ads360_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_search_ads360_link( + parent="parent_value", + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].search_ads_360_link + mock_val = resources.SearchAds360Link(name="name_value") + assert arg == mock_val + + +def test_create_search_ads360_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_search_ads360_link( + analytics_admin.CreateSearchAds360LinkRequest(), + parent="parent_value", + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_search_ads360_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SearchAds360Link() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_search_ads360_link( + parent="parent_value", + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].search_ads_360_link + mock_val = resources.SearchAds360Link(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_search_ads360_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_search_ads360_link( + analytics_admin.CreateSearchAds360LinkRequest(), + parent="parent_value", + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteSearchAds360LinkRequest, dict, ], ) -def test_create_access_binding(request_type, transport: str = "grpc"): +def test_delete_search_ads360_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -35175,29 +35309,23 @@ def test_create_access_binding(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding( - name="name_value", - roles=["roles_value"], - user="user_value", - ) - response = client.create_access_binding(request) + call.return_value = None + response = client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateAccessBindingRequest() + request = analytics_admin.DeleteSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) - assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert response is None -def test_create_access_binding_empty_call(): +def test_delete_search_ads360_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -35207,18 +35335,18 @@ def test_create_access_binding_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_access_binding() + client.delete_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAccessBindingRequest() + assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest() -def test_create_access_binding_non_empty_request_with_auto_populated_field(): +def test_delete_search_ads360_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -35229,26 +35357,26 @@ def test_create_access_binding_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateAccessBindingRequest( - parent="parent_value", + request = analytics_admin.DeleteSearchAds360LinkRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_access_binding(request=request) + client.delete_search_ads360_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAccessBindingRequest( - parent="parent_value", + assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest( + name="name_value", ) -def test_create_access_binding_use_cached_wrapped_rpc(): +def test_delete_search_ads360_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -35263,7 +35391,7 @@ def test_create_access_binding_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_access_binding + client._transport.delete_search_ads360_link in client._transport._wrapped_methods ) @@ -35273,15 +35401,15 @@ def test_create_access_binding_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_access_binding + client._transport.delete_search_ads360_link ] = mock_rpc request = {} - client.create_access_binding(request) + client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_access_binding(request) + client.delete_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -35289,7 +35417,7 @@ def test_create_access_binding_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_access_binding_empty_call_async(): +async def test_delete_search_ads360_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -35299,23 +35427,18 @@ async def test_create_access_binding_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding( - name="name_value", - roles=["roles_value"], - ) - ) - response = await client.create_access_binding() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAccessBindingRequest() + assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest() @pytest.mark.asyncio -async def test_create_access_binding_async_use_cached_wrapped_rpc( +async def test_delete_search_ads360_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -35332,23 +35455,23 @@ async def test_create_access_binding_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_access_binding + client._client._transport.delete_search_ads360_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_access_binding + client._client._transport.delete_search_ads360_link ] = mock_object request = {} - await client.create_access_binding(request) + await client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_access_binding(request) + await client.delete_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -35356,9 +35479,9 @@ async def test_create_access_binding_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_access_binding_async( +async def test_delete_search_ads360_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateAccessBindingRequest, + request_type=analytics_admin.DeleteSearchAds360LinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -35371,51 +35494,44 @@ async def test_create_access_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding( - name="name_value", - roles=["roles_value"], - ) - ) - response = await client.create_access_binding(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateAccessBindingRequest() + request = analytics_admin.DeleteSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) - assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert response is None @pytest.mark.asyncio -async def test_create_access_binding_async_from_dict(): - await test_create_access_binding_async(request_type=dict) +async def test_delete_search_ads360_link_async_from_dict(): + await test_delete_search_ads360_link_async(request_type=dict) -def test_create_access_binding_field_headers(): +def test_delete_search_ads360_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateAccessBindingRequest() + request = analytics_admin.DeleteSearchAds360LinkRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: - call.return_value = resources.AccessBinding() - client.create_access_binding(request) + call.return_value = None + client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -35426,30 +35542,28 @@ def test_create_access_binding_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_access_binding_field_headers_async(): +async def test_delete_search_ads360_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateAccessBindingRequest() + request = analytics_admin.DeleteSearchAds360LinkRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding() - ) - await client.create_access_binding(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -35460,41 +35574,37 @@ async def test_create_access_binding_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_access_binding_flattened(): +def test_delete_search_ads360_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_access_binding( - parent="parent_value", - access_binding=resources.AccessBinding(user="user_value"), + client.delete_search_ads360_link( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].access_binding - mock_val = resources.AccessBinding(user="user_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_access_binding_flattened_error(): +def test_delete_search_ads360_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -35502,50 +35612,43 @@ def test_create_access_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_access_binding( - analytics_admin.CreateAccessBindingRequest(), - parent="parent_value", - access_binding=resources.AccessBinding(user="user_value"), + client.delete_search_ads360_link( + analytics_admin.DeleteSearchAds360LinkRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_access_binding_flattened_async(): +async def test_delete_search_ads360_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_access_binding), "__call__" + type(client.transport.delete_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_access_binding( - parent="parent_value", - access_binding=resources.AccessBinding(user="user_value"), + response = await client.delete_search_ads360_link( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].access_binding - mock_val = resources.AccessBinding(user="user_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_access_binding_flattened_error_async(): +async def test_delete_search_ads360_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -35553,21 +35656,20 @@ async def test_create_access_binding_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_access_binding( - analytics_admin.CreateAccessBindingRequest(), - parent="parent_value", - access_binding=resources.AccessBinding(user="user_value"), + await client.delete_search_ads360_link( + analytics_admin.DeleteSearchAds360LinkRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAccessBindingRequest, + analytics_admin.UpdateSearchAds360LinkRequest, dict, ], ) -def test_get_access_binding(request_type, transport: str = "grpc"): +def test_update_search_ads360_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -35579,29 +35681,30 @@ def test_get_access_binding(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding( + call.return_value = resources.SearchAds360Link( name="name_value", - roles=["roles_value"], - user="user_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) - response = client.get_access_binding(request) + response = client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAccessBindingRequest() + request = analytics_admin.UpdateSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) + assert isinstance(response, resources.SearchAds360Link) assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_get_access_binding_empty_call(): +def test_update_search_ads360_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -35611,18 +35714,18 @@ def test_get_access_binding_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_access_binding() + client.update_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAccessBindingRequest() + assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() -def test_get_access_binding_non_empty_request_with_auto_populated_field(): +def test_update_search_ads360_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -35633,26 +35736,22 @@ def test_get_access_binding_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetAccessBindingRequest( - name="name_value", - ) + request = analytics_admin.UpdateSearchAds360LinkRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_access_binding(request=request) + client.update_search_ads360_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAccessBindingRequest( - name="name_value", - ) + assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() -def test_get_access_binding_use_cached_wrapped_rpc(): +def test_update_search_ads360_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -35667,7 +35766,8 @@ def test_get_access_binding_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_access_binding in client._transport._wrapped_methods + client._transport.update_search_ads360_link + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -35676,15 +35776,15 @@ def test_get_access_binding_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_access_binding + client._transport.update_search_ads360_link ] = mock_rpc request = {} - client.get_access_binding(request) + client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_access_binding(request) + client.update_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -35692,7 +35792,7 @@ def test_get_access_binding_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_access_binding_empty_call_async(): +async def test_update_search_ads360_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -35702,23 +35802,24 @@ async def test_get_access_binding_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding( + resources.SearchAds360Link( name="name_value", - roles=["roles_value"], + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) ) - response = await client.get_access_binding() + response = await client.update_search_ads360_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAccessBindingRequest() + assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() @pytest.mark.asyncio -async def test_get_access_binding_async_use_cached_wrapped_rpc( +async def test_update_search_ads360_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -35735,23 +35836,23 @@ async def test_get_access_binding_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_access_binding + client._client._transport.update_search_ads360_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_access_binding + client._client._transport.update_search_ads360_link ] = mock_object request = {} - await client.get_access_binding(request) + await client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_access_binding(request) + await client.update_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -35759,9 +35860,9 @@ async def test_get_access_binding_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_access_binding_async( +async def test_update_search_ads360_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetAccessBindingRequest, + request_type=analytics_admin.UpdateSearchAds360LinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -35774,51 +35875,53 @@ async def test_get_access_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding( + resources.SearchAds360Link( name="name_value", - roles=["roles_value"], + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) ) - response = await client.get_access_binding(request) + response = await client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAccessBindingRequest() + request = analytics_admin.UpdateSearchAds360LinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) + assert isinstance(response, resources.SearchAds360Link) assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" @pytest.mark.asyncio -async def test_get_access_binding_async_from_dict(): - await test_get_access_binding_async(request_type=dict) +async def test_update_search_ads360_link_async_from_dict(): + await test_update_search_ads360_link_async(request_type=dict) -def test_get_access_binding_field_headers(): +def test_update_search_ads360_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAccessBindingRequest() + request = analytics_admin.UpdateSearchAds360LinkRequest() - request.name = "name_value" + request.search_ads_360_link.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: - call.return_value = resources.AccessBinding() - client.get_access_binding(request) + call.return_value = resources.SearchAds360Link() + client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -35829,30 +35932,30 @@ def test_get_access_binding_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "search_ads_360_link.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_access_binding_field_headers_async(): +async def test_update_search_ads360_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAccessBindingRequest() + request = analytics_admin.UpdateSearchAds360LinkRequest() - request.name = "name_value" + request.search_ads_360_link.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding() + resources.SearchAds360Link() ) - await client.get_access_binding(request) + await client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -35863,37 +35966,41 @@ async def test_get_access_binding_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "search_ads_360_link.name=name_value", ) in kw["metadata"] -def test_get_access_binding_flattened(): +def test_update_search_ads360_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding() + call.return_value = resources.SearchAds360Link() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_access_binding( - name="name_value", + client.update_search_ads360_link( + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].search_ads_360_link + mock_val = resources.SearchAds360Link(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_get_access_binding_flattened_error(): +def test_update_search_ads360_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -35901,45 +36008,50 @@ def test_get_access_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_access_binding( - analytics_admin.GetAccessBindingRequest(), - name="name_value", + client.update_search_ads360_link( + analytics_admin.UpdateSearchAds360LinkRequest(), + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_access_binding_flattened_async(): +async def test_update_search_ads360_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_access_binding), "__call__" + type(client.transport.update_search_ads360_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding() + call.return_value = resources.SearchAds360Link() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding() + resources.SearchAds360Link() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_access_binding( - name="name_value", + response = await client.update_search_ads360_link( + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].search_ads_360_link + mock_val = resources.SearchAds360Link(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_get_access_binding_flattened_error_async(): +async def test_update_search_ads360_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -35947,20 +36059,21 @@ async def test_get_access_binding_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_access_binding( - analytics_admin.GetAccessBindingRequest(), - name="name_value", + await client.update_search_ads360_link( + analytics_admin.UpdateSearchAds360LinkRequest(), + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAccessBindingRequest, + analytics_admin.GetAttributionSettingsRequest, dict, ], ) -def test_update_access_binding(request_type, transport: str = "grpc"): +def test_get_attribution_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -35972,29 +36085,46 @@ def test_update_access_binding(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding( + call.return_value = resources.AttributionSettings( name="name_value", - roles=["roles_value"], - user="user_value", + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, ) - response = client.update_access_binding(request) + response = client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateAccessBindingRequest() + request = analytics_admin.GetAttributionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) + assert isinstance(response, resources.AttributionSettings) assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert ( + response.acquisition_conversion_event_lookback_window + == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + ) + assert ( + response.other_conversion_event_lookback_window + == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + ) + assert ( + response.reporting_attribution_model + == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + ) + assert ( + response.ads_web_conversion_data_export_scope + == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + ) -def test_update_access_binding_empty_call(): +def test_get_attribution_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -36004,18 +36134,18 @@ def test_update_access_binding_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_access_binding() + client.get_attribution_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAccessBindingRequest() + assert args[0] == analytics_admin.GetAttributionSettingsRequest() -def test_update_access_binding_non_empty_request_with_auto_populated_field(): +def test_get_attribution_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -36026,22 +36156,26 @@ def test_update_access_binding_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateAccessBindingRequest() + request = analytics_admin.GetAttributionSettingsRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_access_binding(request=request) + client.get_attribution_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAccessBindingRequest() + assert args[0] == analytics_admin.GetAttributionSettingsRequest( + name="name_value", + ) -def test_update_access_binding_use_cached_wrapped_rpc(): +def test_get_attribution_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -36056,7 +36190,7 @@ def test_update_access_binding_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_access_binding + client._transport.get_attribution_settings in client._transport._wrapped_methods ) @@ -36066,15 +36200,15 @@ def test_update_access_binding_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_access_binding + client._transport.get_attribution_settings ] = mock_rpc request = {} - client.update_access_binding(request) + client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_access_binding(request) + client.get_attribution_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -36082,7 +36216,7 @@ def test_update_access_binding_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_access_binding_empty_call_async(): +async def test_get_attribution_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -36092,23 +36226,26 @@ async def test_update_access_binding_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding( + resources.AttributionSettings( name="name_value", - roles=["roles_value"], + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, ) ) - response = await client.update_access_binding() + response = await client.get_attribution_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateAccessBindingRequest() + assert args[0] == analytics_admin.GetAttributionSettingsRequest() @pytest.mark.asyncio -async def test_update_access_binding_async_use_cached_wrapped_rpc( +async def test_get_attribution_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -36125,23 +36262,23 @@ async def test_update_access_binding_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_access_binding + client._client._transport.get_attribution_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_access_binding + client._client._transport.get_attribution_settings ] = mock_object request = {} - await client.update_access_binding(request) + await client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_access_binding(request) + await client.get_attribution_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -36149,9 +36286,9 @@ async def test_update_access_binding_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_access_binding_async( +async def test_get_attribution_settings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateAccessBindingRequest, + request_type=analytics_admin.GetAttributionSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -36164,51 +36301,69 @@ async def test_update_access_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding( + resources.AttributionSettings( name="name_value", - roles=["roles_value"], + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, ) ) - response = await client.update_access_binding(request) + response = await client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateAccessBindingRequest() + request = analytics_admin.GetAttributionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) + assert isinstance(response, resources.AttributionSettings) assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert ( + response.acquisition_conversion_event_lookback_window + == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + ) + assert ( + response.other_conversion_event_lookback_window + == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + ) + assert ( + response.reporting_attribution_model + == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + ) + assert ( + response.ads_web_conversion_data_export_scope + == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + ) @pytest.mark.asyncio -async def test_update_access_binding_async_from_dict(): - await test_update_access_binding_async(request_type=dict) +async def test_get_attribution_settings_async_from_dict(): + await test_get_attribution_settings_async(request_type=dict) -def test_update_access_binding_field_headers(): +def test_get_attribution_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateAccessBindingRequest() + request = analytics_admin.GetAttributionSettingsRequest() - request.access_binding.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: - call.return_value = resources.AccessBinding() - client.update_access_binding(request) + call.return_value = resources.AttributionSettings() + client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -36219,30 +36374,30 @@ def test_update_access_binding_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "access_binding.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_access_binding_field_headers_async(): +async def test_get_attribution_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateAccessBindingRequest() + request = analytics_admin.GetAttributionSettingsRequest() - request.access_binding.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding() + resources.AttributionSettings() ) - await client.update_access_binding(request) + await client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -36253,37 +36408,37 @@ async def test_update_access_binding_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "access_binding.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_access_binding_flattened(): +def test_get_attribution_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding() + call.return_value = resources.AttributionSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_access_binding( - access_binding=resources.AccessBinding(user="user_value"), + client.get_attribution_settings( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].access_binding - mock_val = resources.AccessBinding(user="user_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_access_binding_flattened_error(): +def test_get_attribution_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -36291,45 +36446,45 @@ def test_update_access_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_access_binding( - analytics_admin.UpdateAccessBindingRequest(), - access_binding=resources.AccessBinding(user="user_value"), + client.get_attribution_settings( + analytics_admin.GetAttributionSettingsRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_access_binding_flattened_async(): +async def test_get_attribution_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_access_binding), "__call__" + type(client.transport.get_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AccessBinding() + call.return_value = resources.AttributionSettings() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AccessBinding() + resources.AttributionSettings() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_access_binding( - access_binding=resources.AccessBinding(user="user_value"), + response = await client.get_attribution_settings( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].access_binding - mock_val = resources.AccessBinding(user="user_value") + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_access_binding_flattened_error_async(): +async def test_get_attribution_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -36337,20 +36492,20 @@ async def test_update_access_binding_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_access_binding( - analytics_admin.UpdateAccessBindingRequest(), - access_binding=resources.AccessBinding(user="user_value"), + await client.get_attribution_settings( + analytics_admin.GetAttributionSettingsRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteAccessBindingRequest, + analytics_admin.UpdateAttributionSettingsRequest, dict, ], ) -def test_delete_access_binding(request_type, transport: str = "grpc"): +def test_update_attribution_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -36362,23 +36517,46 @@ def test_delete_access_binding(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_access_binding(request) + call.return_value = resources.AttributionSettings( + name="name_value", + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + response = client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteAccessBindingRequest() + request = analytics_admin.UpdateAttributionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.AttributionSettings) + assert response.name == "name_value" + assert ( + response.acquisition_conversion_event_lookback_window + == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + ) + assert ( + response.other_conversion_event_lookback_window + == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + ) + assert ( + response.reporting_attribution_model + == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + ) + assert ( + response.ads_web_conversion_data_export_scope + == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + ) -def test_delete_access_binding_empty_call(): +def test_update_attribution_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -36388,18 +36566,18 @@ def test_delete_access_binding_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_access_binding() + client.update_attribution_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteAccessBindingRequest() + assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() -def test_delete_access_binding_non_empty_request_with_auto_populated_field(): +def test_update_attribution_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -36410,26 +36588,22 @@ def test_delete_access_binding_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteAccessBindingRequest( - name="name_value", - ) + request = analytics_admin.UpdateAttributionSettingsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_access_binding(request=request) + client.update_attribution_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteAccessBindingRequest( - name="name_value", - ) + assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() -def test_delete_access_binding_use_cached_wrapped_rpc(): +def test_update_attribution_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -36444,7 +36618,7 @@ def test_delete_access_binding_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_access_binding + client._transport.update_attribution_settings in client._transport._wrapped_methods ) @@ -36454,15 +36628,15 @@ def test_delete_access_binding_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_access_binding + client._transport.update_attribution_settings ] = mock_rpc request = {} - client.delete_access_binding(request) + client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_access_binding(request) + client.update_attribution_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -36470,7 +36644,7 @@ def test_delete_access_binding_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_access_binding_empty_call_async(): +async def test_update_attribution_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -36480,18 +36654,26 @@ async def test_delete_access_binding_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_access_binding() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AttributionSettings( + name="name_value", + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + ) + response = await client.update_attribution_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteAccessBindingRequest() + assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() @pytest.mark.asyncio -async def test_delete_access_binding_async_use_cached_wrapped_rpc( +async def test_update_attribution_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -36508,23 +36690,23 @@ async def test_delete_access_binding_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_access_binding + client._client._transport.update_attribution_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_access_binding + client._client._transport.update_attribution_settings ] = mock_object request = {} - await client.delete_access_binding(request) + await client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_access_binding(request) + await client.update_attribution_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -36532,9 +36714,9 @@ async def test_delete_access_binding_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_access_binding_async( +async def test_update_attribution_settings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteAccessBindingRequest, + request_type=analytics_admin.UpdateAttributionSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -36547,44 +36729,69 @@ async def test_delete_access_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_access_binding(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AttributionSettings( + name="name_value", + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + ) + response = await client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteAccessBindingRequest() + request = analytics_admin.UpdateAttributionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.AttributionSettings) + assert response.name == "name_value" + assert ( + response.acquisition_conversion_event_lookback_window + == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + ) + assert ( + response.other_conversion_event_lookback_window + == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + ) + assert ( + response.reporting_attribution_model + == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + ) + assert ( + response.ads_web_conversion_data_export_scope + == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + ) @pytest.mark.asyncio -async def test_delete_access_binding_async_from_dict(): - await test_delete_access_binding_async(request_type=dict) +async def test_update_attribution_settings_async_from_dict(): + await test_update_attribution_settings_async(request_type=dict) -def test_delete_access_binding_field_headers(): +def test_update_attribution_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteAccessBindingRequest() + request = analytics_admin.UpdateAttributionSettingsRequest() - request.name = "name_value" + request.attribution_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: - call.return_value = None - client.delete_access_binding(request) + call.return_value = resources.AttributionSettings() + client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -36595,28 +36802,30 @@ def test_delete_access_binding_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "attribution_settings.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_access_binding_field_headers_async(): +async def test_update_attribution_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteAccessBindingRequest() + request = analytics_admin.UpdateAttributionSettingsRequest() - request.name = "name_value" + request.attribution_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_access_binding(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AttributionSettings() + ) + await client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -36627,37 +36836,41 @@ async def test_delete_access_binding_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "attribution_settings.name=name_value", ) in kw["metadata"] -def test_delete_access_binding_flattened(): +def test_update_attribution_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.AttributionSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_access_binding( - name="name_value", + client.update_attribution_settings( + attribution_settings=resources.AttributionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].attribution_settings + mock_val = resources.AttributionSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_delete_access_binding_flattened_error(): +def test_update_attribution_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -36665,43 +36878,50 @@ def test_delete_access_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_access_binding( - analytics_admin.DeleteAccessBindingRequest(), - name="name_value", + client.update_attribution_settings( + analytics_admin.UpdateAttributionSettingsRequest(), + attribution_settings=resources.AttributionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_delete_access_binding_flattened_async(): +async def test_update_attribution_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_access_binding), "__call__" + type(client.transport.update_attribution_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.AttributionSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AttributionSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_access_binding( - name="name_value", + response = await client.update_attribution_settings( + attribution_settings=resources.AttributionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].attribution_settings + mock_val = resources.AttributionSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_delete_access_binding_flattened_error_async(): +async def test_update_attribution_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -36709,20 +36929,21 @@ async def test_delete_access_binding_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_access_binding( - analytics_admin.DeleteAccessBindingRequest(), - name="name_value", + await client.update_attribution_settings( + analytics_admin.UpdateAttributionSettingsRequest(), + attribution_settings=resources.AttributionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListAccessBindingsRequest, + analytics_admin.RunAccessReportRequest, dict, ], ) -def test_list_access_bindings(request_type, transport: str = "grpc"): +def test_run_access_report(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -36734,26 +36955,26 @@ def test_list_access_bindings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAccessBindingsResponse( - next_page_token="next_page_token_value", + call.return_value = analytics_admin.RunAccessReportResponse( + row_count=992, ) - response = client.list_access_bindings(request) + response = client.run_access_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListAccessBindingsRequest() + request = analytics_admin.RunAccessReportRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccessBindingsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 -def test_list_access_bindings_empty_call(): +def test_run_access_report_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -36763,18 +36984,18 @@ def test_list_access_bindings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_access_bindings() + client.run_access_report() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAccessBindingsRequest() + assert args[0] == analytics_admin.RunAccessReportRequest() -def test_list_access_bindings_non_empty_request_with_auto_populated_field(): +def test_run_access_report_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -36785,28 +37006,28 @@ def test_list_access_bindings_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListAccessBindingsRequest( - parent="parent_value", - page_token="page_token_value", + request = analytics_admin.RunAccessReportRequest( + entity="entity_value", + time_zone="time_zone_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_access_bindings(request=request) + client.run_access_report(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAccessBindingsRequest( - parent="parent_value", - page_token="page_token_value", + assert args[0] == analytics_admin.RunAccessReportRequest( + entity="entity_value", + time_zone="time_zone_value", ) -def test_list_access_bindings_use_cached_wrapped_rpc(): +def test_run_access_report_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -36820,9 +37041,7 @@ def test_list_access_bindings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_access_bindings in client._transport._wrapped_methods - ) + assert client._transport.run_access_report in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -36830,15 +37049,15 @@ def test_list_access_bindings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_access_bindings + client._transport.run_access_report ] = mock_rpc request = {} - client.list_access_bindings(request) + client.run_access_report(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_access_bindings(request) + client.run_access_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -36846,7 +37065,7 @@ def test_list_access_bindings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_access_bindings_empty_call_async(): +async def test_run_access_report_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -36856,22 +37075,22 @@ async def test_list_access_bindings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAccessBindingsResponse( - next_page_token="next_page_token_value", + analytics_admin.RunAccessReportResponse( + row_count=992, ) ) - response = await client.list_access_bindings() + response = await client.run_access_report() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAccessBindingsRequest() + assert args[0] == analytics_admin.RunAccessReportRequest() @pytest.mark.asyncio -async def test_list_access_bindings_async_use_cached_wrapped_rpc( +async def test_run_access_report_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -36888,23 +37107,23 @@ async def test_list_access_bindings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_access_bindings + client._client._transport.run_access_report in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_access_bindings + client._client._transport.run_access_report ] = mock_object request = {} - await client.list_access_bindings(request) + await client.run_access_report(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_access_bindings(request) + await client.run_access_report(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -36912,9 +37131,8 @@ async def test_list_access_bindings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_access_bindings_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.ListAccessBindingsRequest, +async def test_run_access_report_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.RunAccessReportRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -36927,49 +37145,49 @@ async def test_list_access_bindings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAccessBindingsResponse( - next_page_token="next_page_token_value", + analytics_admin.RunAccessReportResponse( + row_count=992, ) ) - response = await client.list_access_bindings(request) + response = await client.run_access_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListAccessBindingsRequest() + request = analytics_admin.RunAccessReportRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccessBindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 @pytest.mark.asyncio -async def test_list_access_bindings_async_from_dict(): - await test_list_access_bindings_async(request_type=dict) +async def test_run_access_report_async_from_dict(): + await test_run_access_report_async(request_type=dict) -def test_list_access_bindings_field_headers(): +def test_run_access_report_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListAccessBindingsRequest() + request = analytics_admin.RunAccessReportRequest() - request.parent = "parent_value" + request.entity = "entity_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: - call.return_value = analytics_admin.ListAccessBindingsResponse() - client.list_access_bindings(request) + call.return_value = analytics_admin.RunAccessReportResponse() + client.run_access_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -36980,30 +37198,30 @@ def test_list_access_bindings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "entity=entity_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_access_bindings_field_headers_async(): +async def test_run_access_report_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListAccessBindingsRequest() + request = analytics_admin.RunAccessReportRequest() - request.parent = "parent_value" + request.entity = "entity_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" + type(client.transport.run_access_report), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAccessBindingsResponse() + analytics_admin.RunAccessReportResponse() ) - await client.list_access_bindings(request) + await client.run_access_report(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -37014,306 +37232,18 @@ async def test_list_access_bindings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "entity=entity_value", ) in kw["metadata"] -def test_list_access_bindings_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAccessBindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_access_bindings( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -def test_list_access_bindings_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_access_bindings( - analytics_admin.ListAccessBindingsRequest(), - parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_access_bindings_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAccessBindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAccessBindingsResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_access_bindings( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_access_bindings_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_access_bindings( - analytics_admin.ListAccessBindingsRequest(), - parent="parent_value", - ) - - -def test_list_access_bindings_pager(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - resources.AccessBinding(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[], - next_page_token="def", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_access_bindings(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.AccessBinding) for i in results) - - -def test_list_access_bindings_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_access_bindings), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - resources.AccessBinding(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[], - next_page_token="def", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_access_bindings(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_access_bindings_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_access_bindings), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - resources.AccessBinding(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[], - next_page_token="def", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_access_bindings( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.AccessBinding) for i in responses) - - -@pytest.mark.asyncio -async def test_list_access_bindings_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_access_bindings), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - resources.AccessBinding(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[], - next_page_token="def", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_access_bindings(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - @pytest.mark.parametrize( "request_type", [ - analytics_admin.BatchCreateAccessBindingsRequest, + analytics_admin.CreateAccessBindingRequest, dict, ], ) -def test_batch_create_access_bindings(request_type, transport: str = "grpc"): +def test_create_access_binding(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -37325,23 +37255,29 @@ def test_batch_create_access_bindings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.BatchCreateAccessBindingsResponse() - response = client.batch_create_access_bindings(request) + call.return_value = resources.AccessBinding( + name="name_value", + roles=["roles_value"], + user="user_value", + ) + response = client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchCreateAccessBindingsRequest() + request = analytics_admin.CreateAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] -def test_batch_create_access_bindings_empty_call(): +def test_create_access_binding_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -37351,18 +37287,18 @@ def test_batch_create_access_bindings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.batch_create_access_bindings() + client.create_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest() + assert args[0] == analytics_admin.CreateAccessBindingRequest() -def test_batch_create_access_bindings_non_empty_request_with_auto_populated_field(): +def test_create_access_binding_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -37373,26 +37309,26 @@ def test_batch_create_access_bindings_non_empty_request_with_auto_populated_fiel # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.BatchCreateAccessBindingsRequest( + request = analytics_admin.CreateAccessBindingRequest( parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.batch_create_access_bindings(request=request) + client.create_access_binding(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest( + assert args[0] == analytics_admin.CreateAccessBindingRequest( parent="parent_value", ) -def test_batch_create_access_bindings_use_cached_wrapped_rpc(): +def test_create_access_binding_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -37407,7 +37343,7 @@ def test_batch_create_access_bindings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_create_access_bindings + client._transport.create_access_binding in client._transport._wrapped_methods ) @@ -37417,15 +37353,15 @@ def test_batch_create_access_bindings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_create_access_bindings + client._transport.create_access_binding ] = mock_rpc request = {} - client.batch_create_access_bindings(request) + client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_create_access_bindings(request) + client.create_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -37433,7 +37369,7 @@ def test_batch_create_access_bindings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_batch_create_access_bindings_empty_call_async(): +async def test_create_access_binding_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -37443,20 +37379,23 @@ async def test_batch_create_access_bindings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchCreateAccessBindingsResponse() + resources.AccessBinding( + name="name_value", + roles=["roles_value"], + ) ) - response = await client.batch_create_access_bindings() + response = await client.create_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest() + assert args[0] == analytics_admin.CreateAccessBindingRequest() @pytest.mark.asyncio -async def test_batch_create_access_bindings_async_use_cached_wrapped_rpc( +async def test_create_access_binding_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -37473,23 +37412,23 @@ async def test_batch_create_access_bindings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.batch_create_access_bindings + client._client._transport.create_access_binding in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.batch_create_access_bindings + client._client._transport.create_access_binding ] = mock_object request = {} - await client.batch_create_access_bindings(request) + await client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.batch_create_access_bindings(request) + await client.create_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -37497,9 +37436,9 @@ async def test_batch_create_access_bindings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_batch_create_access_bindings_async( +async def test_create_access_binding_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.BatchCreateAccessBindingsRequest, + request_type=analytics_admin.CreateAccessBindingRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -37512,46 +37451,51 @@ async def test_batch_create_access_bindings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchCreateAccessBindingsResponse() + resources.AccessBinding( + name="name_value", + roles=["roles_value"], + ) ) - response = await client.batch_create_access_bindings(request) + response = await client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchCreateAccessBindingsRequest() + request = analytics_admin.CreateAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] @pytest.mark.asyncio -async def test_batch_create_access_bindings_async_from_dict(): - await test_batch_create_access_bindings_async(request_type=dict) +async def test_create_access_binding_async_from_dict(): + await test_create_access_binding_async(request_type=dict) -def test_batch_create_access_bindings_field_headers(): +def test_create_access_binding_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.BatchCreateAccessBindingsRequest() + request = analytics_admin.CreateAccessBindingRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: - call.return_value = analytics_admin.BatchCreateAccessBindingsResponse() - client.batch_create_access_bindings(request) + call.return_value = resources.AccessBinding() + client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -37567,25 +37511,25 @@ def test_batch_create_access_bindings_field_headers(): @pytest.mark.asyncio -async def test_batch_create_access_bindings_field_headers_async(): +async def test_create_access_binding_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.BatchCreateAccessBindingsRequest() + request = analytics_admin.CreateAccessBindingRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_create_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchCreateAccessBindingsResponse() + resources.AccessBinding() ) - await client.batch_create_access_bindings(request) + await client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -37600,94 +37544,196 @@ async def test_batch_create_access_bindings_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.BatchGetAccessBindingsRequest, - dict, - ], -) -def test_batch_get_access_bindings(request_type, transport: str = "grpc"): +def test_create_access_binding_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.BatchGetAccessBindingsResponse() - response = client.batch_get_access_bindings(request) + call.return_value = resources.AccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_access_binding( + parent="parent_value", + access_binding=resources.AccessBinding(user="user_value"), + ) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchGetAccessBindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].access_binding + mock_val = resources.AccessBinding(user="user_value") + assert arg == mock_val -def test_batch_get_access_bindings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_create_access_binding_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_access_binding( + analytics_admin.CreateAccessBindingRequest(), + parent="parent_value", + access_binding=resources.AccessBinding(user="user_value"), ) - client.batch_get_access_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchGetAccessBindingsRequest() -def test_batch_get_access_bindings_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_create_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.BatchGetAccessBindingsRequest( - parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" + type(client.transport.create_access_binding), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AccessBinding() ) - client.batch_get_access_bindings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchGetAccessBindingsRequest( + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_access_binding( parent="parent_value", + access_binding=resources.AccessBinding(user="user_value"), ) - -def test_batch_get_access_bindings_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].access_binding + mock_val = resources.AccessBinding(user="user_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_access_binding_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_access_binding( + analytics_admin.CreateAccessBindingRequest(), + parent="parent_value", + access_binding=resources.AccessBinding(user="user_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetAccessBindingRequest, + dict, + ], +) +def test_get_access_binding(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding( + name="name_value", + roles=["roles_value"], + user="user_value", + ) + response = client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] + + +def test_get_access_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccessBindingRequest() + + +def test_get_access_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.GetAccessBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccessBindingRequest( + name="name_value", + ) + + +def test_get_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = AnalyticsAdminServiceClient( @@ -37701,8 +37747,7 @@ def test_batch_get_access_bindings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_get_access_bindings - in client._transport._wrapped_methods + client._transport.get_access_binding in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -37711,15 +37756,15 @@ def test_batch_get_access_bindings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_get_access_bindings + client._transport.get_access_binding ] = mock_rpc request = {} - client.batch_get_access_bindings(request) + client.get_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_get_access_bindings(request) + client.get_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -37727,7 +37772,7 @@ def test_batch_get_access_bindings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_batch_get_access_bindings_empty_call_async(): +async def test_get_access_binding_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -37737,20 +37782,23 @@ async def test_batch_get_access_bindings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" + type(client.transport.get_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchGetAccessBindingsResponse() + resources.AccessBinding( + name="name_value", + roles=["roles_value"], + ) ) - response = await client.batch_get_access_bindings() + response = await client.get_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchGetAccessBindingsRequest() + assert args[0] == analytics_admin.GetAccessBindingRequest() @pytest.mark.asyncio -async def test_batch_get_access_bindings_async_use_cached_wrapped_rpc( +async def test_get_access_binding_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -37767,23 +37815,23 @@ async def test_batch_get_access_bindings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.batch_get_access_bindings + client._client._transport.get_access_binding in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.batch_get_access_bindings + client._client._transport.get_access_binding ] = mock_object request = {} - await client.batch_get_access_bindings(request) + await client.get_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.batch_get_access_bindings(request) + await client.get_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -37791,9 +37839,9 @@ async def test_batch_get_access_bindings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_batch_get_access_bindings_async( +async def test_get_access_binding_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.BatchGetAccessBindingsRequest, + request_type=analytics_admin.GetAccessBindingRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -37806,46 +37854,51 @@ async def test_batch_get_access_bindings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" + type(client.transport.get_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchGetAccessBindingsResponse() + resources.AccessBinding( + name="name_value", + roles=["roles_value"], + ) ) - response = await client.batch_get_access_bindings(request) + response = await client.get_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchGetAccessBindingsRequest() + request = analytics_admin.GetAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] @pytest.mark.asyncio -async def test_batch_get_access_bindings_async_from_dict(): - await test_batch_get_access_bindings_async(request_type=dict) +async def test_get_access_binding_async_from_dict(): + await test_get_access_binding_async(request_type=dict) -def test_batch_get_access_bindings_field_headers(): +def test_get_access_binding_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.BatchGetAccessBindingsRequest() + request = analytics_admin.GetAccessBindingRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" + type(client.transport.get_access_binding), "__call__" ) as call: - call.return_value = analytics_admin.BatchGetAccessBindingsResponse() - client.batch_get_access_bindings(request) + call.return_value = resources.AccessBinding() + client.get_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -37856,30 +37909,30 @@ def test_batch_get_access_bindings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_batch_get_access_bindings_field_headers_async(): +async def test_get_access_binding_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.BatchGetAccessBindingsRequest() + request = analytics_admin.GetAccessBindingRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_get_access_bindings), "__call__" + type(client.transport.get_access_binding), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchGetAccessBindingsResponse() + resources.AccessBinding() ) - await client.batch_get_access_bindings(request) + await client.get_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -37890,18 +37943,104 @@ async def test_batch_get_access_bindings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] +def test_get_access_binding_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_access_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_access_binding_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_access_binding( + analytics_admin.GetAccessBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AccessBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_access_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_access_binding_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_access_binding( + analytics_admin.GetAccessBindingRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ - analytics_admin.BatchUpdateAccessBindingsRequest, + analytics_admin.UpdateAccessBindingRequest, dict, ], ) -def test_batch_update_access_bindings(request_type, transport: str = "grpc"): +def test_update_access_binding(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -37913,23 +38052,29 @@ def test_batch_update_access_bindings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() - response = client.batch_update_access_bindings(request) + call.return_value = resources.AccessBinding( + name="name_value", + roles=["roles_value"], + user="user_value", + ) + response = client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchUpdateAccessBindingsRequest() + request = analytics_admin.UpdateAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] -def test_batch_update_access_bindings_empty_call(): +def test_update_access_binding_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -37939,18 +38084,18 @@ def test_batch_update_access_bindings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.batch_update_access_bindings() + client.update_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest() + assert args[0] == analytics_admin.UpdateAccessBindingRequest() -def test_batch_update_access_bindings_non_empty_request_with_auto_populated_field(): +def test_update_access_binding_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -37961,26 +38106,22 @@ def test_batch_update_access_bindings_non_empty_request_with_auto_populated_fiel # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.BatchUpdateAccessBindingsRequest( - parent="parent_value", - ) + request = analytics_admin.UpdateAccessBindingRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.batch_update_access_bindings(request=request) + client.update_access_binding(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest( - parent="parent_value", - ) + assert args[0] == analytics_admin.UpdateAccessBindingRequest() -def test_batch_update_access_bindings_use_cached_wrapped_rpc(): +def test_update_access_binding_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -37995,7 +38136,7 @@ def test_batch_update_access_bindings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_update_access_bindings + client._transport.update_access_binding in client._transport._wrapped_methods ) @@ -38005,15 +38146,15 @@ def test_batch_update_access_bindings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_update_access_bindings + client._transport.update_access_binding ] = mock_rpc request = {} - client.batch_update_access_bindings(request) + client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_update_access_bindings(request) + client.update_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -38021,7 +38162,7 @@ def test_batch_update_access_bindings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_batch_update_access_bindings_empty_call_async(): +async def test_update_access_binding_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -38031,20 +38172,23 @@ async def test_batch_update_access_bindings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchUpdateAccessBindingsResponse() + resources.AccessBinding( + name="name_value", + roles=["roles_value"], + ) ) - response = await client.batch_update_access_bindings() + response = await client.update_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest() + assert args[0] == analytics_admin.UpdateAccessBindingRequest() @pytest.mark.asyncio -async def test_batch_update_access_bindings_async_use_cached_wrapped_rpc( +async def test_update_access_binding_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -38061,23 +38205,23 @@ async def test_batch_update_access_bindings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.batch_update_access_bindings + client._client._transport.update_access_binding in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.batch_update_access_bindings + client._client._transport.update_access_binding ] = mock_object request = {} - await client.batch_update_access_bindings(request) + await client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.batch_update_access_bindings(request) + await client.update_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -38085,9 +38229,9 @@ async def test_batch_update_access_bindings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_batch_update_access_bindings_async( +async def test_update_access_binding_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.BatchUpdateAccessBindingsRequest, + request_type=analytics_admin.UpdateAccessBindingRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -38100,46 +38244,51 @@ async def test_batch_update_access_bindings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchUpdateAccessBindingsResponse() + resources.AccessBinding( + name="name_value", + roles=["roles_value"], + ) ) - response = await client.batch_update_access_bindings(request) + response = await client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchUpdateAccessBindingsRequest() + request = analytics_admin.UpdateAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] @pytest.mark.asyncio -async def test_batch_update_access_bindings_async_from_dict(): - await test_batch_update_access_bindings_async(request_type=dict) +async def test_update_access_binding_async_from_dict(): + await test_update_access_binding_async(request_type=dict) -def test_batch_update_access_bindings_field_headers(): +def test_update_access_binding_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.BatchUpdateAccessBindingsRequest() + request = analytics_admin.UpdateAccessBindingRequest() - request.parent = "parent_value" + request.access_binding.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: - call.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() - client.batch_update_access_bindings(request) + call.return_value = resources.AccessBinding() + client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -38150,30 +38299,30 @@ def test_batch_update_access_bindings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "access_binding.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_batch_update_access_bindings_field_headers_async(): +async def test_update_access_binding_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.BatchUpdateAccessBindingsRequest() + request = analytics_admin.UpdateAccessBindingRequest() - request.parent = "parent_value" + request.access_binding.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_update_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.BatchUpdateAccessBindingsResponse() + resources.AccessBinding() ) - await client.batch_update_access_bindings(request) + await client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -38184,306 +38333,104 @@ async def test_batch_update_access_bindings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "access_binding.name=name_value", ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.BatchDeleteAccessBindingsRequest, - dict, - ], -) -def test_batch_delete_access_bindings(request_type, transport: str = "grpc"): +def test_update_access_binding_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.batch_delete_access_bindings(request) + call.return_value = resources.AccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_access_binding( + access_binding=resources.AccessBinding(user="user_value"), + ) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchDeleteAccessBindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None + arg = args[0].access_binding + mock_val = resources.AccessBinding(user="user_value") + assert arg == mock_val -def test_batch_delete_access_bindings_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_update_access_binding_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_access_binding( + analytics_admin.UpdateAccessBindingRequest(), + access_binding=resources.AccessBinding(user="user_value"), ) - client.batch_delete_access_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest() -def test_batch_delete_access_bindings_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_update_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.BatchDeleteAccessBindingsRequest( - parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" + type(client.transport.update_access_binding), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.AccessBinding() ) - client.batch_delete_access_bindings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest( - parent="parent_value", + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_access_binding( + access_binding=resources.AccessBinding(user="user_value"), ) - -def test_batch_delete_access_bindings_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.batch_delete_access_bindings - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.batch_delete_access_bindings - ] = mock_rpc - request = {} - client.batch_delete_access_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.batch_delete_access_bindings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_batch_delete_access_bindings_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.batch_delete_access_bindings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest() - - -@pytest.mark.asyncio -async def test_batch_delete_access_bindings_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.batch_delete_access_bindings - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[ - client._client._transport.batch_delete_access_bindings - ] = mock_object - - request = {} - await client.batch_delete_access_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.batch_delete_access_bindings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - - -@pytest.mark.asyncio -async def test_batch_delete_access_bindings_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.BatchDeleteAccessBindingsRequest, -): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.batch_delete_access_bindings(request) - - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.BatchDeleteAccessBindingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_batch_delete_access_bindings_async_from_dict(): - await test_batch_delete_access_bindings_async(request_type=dict) - - -def test_batch_delete_access_bindings_field_headers(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.BatchDeleteAccessBindingsRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" - ) as call: - call.return_value = None - client.batch_delete_access_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + arg = args[0].access_binding + mock_val = resources.AccessBinding(user="user_value") + assert arg == mock_val @pytest.mark.asyncio -async def test_batch_delete_access_bindings_field_headers_async(): +async def test_update_access_binding_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.BatchDeleteAccessBindingsRequest() - - request.parent = "parent_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_delete_access_bindings), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.batch_delete_access_bindings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_access_binding( + analytics_admin.UpdateAccessBindingRequest(), + access_binding=resources.AccessBinding(user="user_value"), + ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetExpandedDataSetRequest, + analytics_admin.DeleteAccessBindingRequest, dict, ], ) -def test_get_expanded_data_set(request_type, transport: str = "grpc"): +def test_delete_access_binding(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -38495,34 +38442,23 @@ def test_get_expanded_data_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) - response = client.get_expanded_data_set(request) + call.return_value = None + response = client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetExpandedDataSetRequest() + request = analytics_admin.DeleteAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert response is None -def test_get_expanded_data_set_empty_call(): +def test_delete_access_binding_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -38532,18 +38468,18 @@ def test_get_expanded_data_set_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_expanded_data_set() + client.delete_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetExpandedDataSetRequest() + assert args[0] == analytics_admin.DeleteAccessBindingRequest() -def test_get_expanded_data_set_non_empty_request_with_auto_populated_field(): +def test_delete_access_binding_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -38554,26 +38490,26 @@ def test_get_expanded_data_set_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetExpandedDataSetRequest( + request = analytics_admin.DeleteAccessBindingRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_expanded_data_set(request=request) + client.delete_access_binding(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetExpandedDataSetRequest( + assert args[0] == analytics_admin.DeleteAccessBindingRequest( name="name_value", ) -def test_get_expanded_data_set_use_cached_wrapped_rpc(): +def test_delete_access_binding_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -38588,7 +38524,7 @@ def test_get_expanded_data_set_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_expanded_data_set + client._transport.delete_access_binding in client._transport._wrapped_methods ) @@ -38598,15 +38534,15 @@ def test_get_expanded_data_set_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_expanded_data_set + client._transport.delete_access_binding ] = mock_rpc request = {} - client.get_expanded_data_set(request) + client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_expanded_data_set(request) + client.delete_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -38614,7 +38550,7 @@ def test_get_expanded_data_set_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_expanded_data_set_empty_call_async(): +async def test_delete_access_binding_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -38624,26 +38560,18 @@ async def test_get_expanded_data_set_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) - ) - response = await client.get_expanded_data_set() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_access_binding() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetExpandedDataSetRequest() + assert args[0] == analytics_admin.DeleteAccessBindingRequest() @pytest.mark.asyncio -async def test_get_expanded_data_set_async_use_cached_wrapped_rpc( +async def test_delete_access_binding_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -38660,23 +38588,23 @@ async def test_get_expanded_data_set_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_expanded_data_set + client._client._transport.delete_access_binding in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_expanded_data_set + client._client._transport.delete_access_binding ] = mock_object request = {} - await client.get_expanded_data_set(request) + await client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_expanded_data_set(request) + await client.delete_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -38684,9 +38612,9 @@ async def test_get_expanded_data_set_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_expanded_data_set_async( +async def test_delete_access_binding_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetExpandedDataSetRequest, + request_type=analytics_admin.DeleteAccessBindingRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -38699,57 +38627,44 @@ async def test_get_expanded_data_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) - ) - response = await client.get_expanded_data_set(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetExpandedDataSetRequest() + request = analytics_admin.DeleteAccessBindingRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert response is None @pytest.mark.asyncio -async def test_get_expanded_data_set_async_from_dict(): - await test_get_expanded_data_set_async(request_type=dict) +async def test_delete_access_binding_async_from_dict(): + await test_delete_access_binding_async(request_type=dict) -def test_get_expanded_data_set_field_headers(): +def test_delete_access_binding_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetExpandedDataSetRequest() + request = analytics_admin.DeleteAccessBindingRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: - call.return_value = expanded_data_set.ExpandedDataSet() - client.get_expanded_data_set(request) + call.return_value = None + client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -38765,25 +38680,23 @@ def test_get_expanded_data_set_field_headers(): @pytest.mark.asyncio -async def test_get_expanded_data_set_field_headers_async(): +async def test_delete_access_binding_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetExpandedDataSetRequest() + request = analytics_admin.DeleteAccessBindingRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - expanded_data_set.ExpandedDataSet() - ) - await client.get_expanded_data_set(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -38798,20 +38711,20 @@ async def test_get_expanded_data_set_field_headers_async(): ) in kw["metadata"] -def test_get_expanded_data_set_flattened(): +def test_delete_access_binding_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = expanded_data_set.ExpandedDataSet() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_expanded_data_set( + client.delete_access_binding( name="name_value", ) @@ -38824,7 +38737,7 @@ def test_get_expanded_data_set_flattened(): assert arg == mock_val -def test_get_expanded_data_set_flattened_error(): +def test_delete_access_binding_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -38832,31 +38745,29 @@ def test_get_expanded_data_set_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_expanded_data_set( - analytics_admin.GetExpandedDataSetRequest(), + client.delete_access_binding( + analytics_admin.DeleteAccessBindingRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_expanded_data_set_flattened_async(): +async def test_delete_access_binding_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_expanded_data_set), "__call__" + type(client.transport.delete_access_binding), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = expanded_data_set.ExpandedDataSet() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - expanded_data_set.ExpandedDataSet() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_expanded_data_set( + response = await client.delete_access_binding( name="name_value", ) @@ -38870,7 +38781,7 @@ async def test_get_expanded_data_set_flattened_async(): @pytest.mark.asyncio -async def test_get_expanded_data_set_flattened_error_async(): +async def test_delete_access_binding_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -38878,8 +38789,8 @@ async def test_get_expanded_data_set_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_expanded_data_set( - analytics_admin.GetExpandedDataSetRequest(), + await client.delete_access_binding( + analytics_admin.DeleteAccessBindingRequest(), name="name_value", ) @@ -38887,11 +38798,11 @@ async def test_get_expanded_data_set_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListExpandedDataSetsRequest, + analytics_admin.ListAccessBindingsRequest, dict, ], ) -def test_list_expanded_data_sets(request_type, transport: str = "grpc"): +def test_list_access_bindings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -38903,26 +38814,26 @@ def test_list_expanded_data_sets(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListExpandedDataSetsResponse( + call.return_value = analytics_admin.ListAccessBindingsResponse( next_page_token="next_page_token_value", ) - response = client.list_expanded_data_sets(request) + response = client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListExpandedDataSetsRequest() + request = analytics_admin.ListAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExpandedDataSetsPager) + assert isinstance(response, pagers.ListAccessBindingsPager) assert response.next_page_token == "next_page_token_value" -def test_list_expanded_data_sets_empty_call(): +def test_list_access_bindings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -38932,18 +38843,18 @@ def test_list_expanded_data_sets_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_expanded_data_sets() + client.list_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListExpandedDataSetsRequest() + assert args[0] == analytics_admin.ListAccessBindingsRequest() -def test_list_expanded_data_sets_non_empty_request_with_auto_populated_field(): +def test_list_access_bindings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -38954,28 +38865,28 @@ def test_list_expanded_data_sets_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListExpandedDataSetsRequest( + request = analytics_admin.ListAccessBindingsRequest( parent="parent_value", page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_expanded_data_sets(request=request) + client.list_access_bindings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListExpandedDataSetsRequest( + assert args[0] == analytics_admin.ListAccessBindingsRequest( parent="parent_value", page_token="page_token_value", ) -def test_list_expanded_data_sets_use_cached_wrapped_rpc(): +def test_list_access_bindings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -38990,8 +38901,7 @@ def test_list_expanded_data_sets_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_expanded_data_sets - in client._transport._wrapped_methods + client._transport.list_access_bindings in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -39000,15 +38910,15 @@ def test_list_expanded_data_sets_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_expanded_data_sets + client._transport.list_access_bindings ] = mock_rpc request = {} - client.list_expanded_data_sets(request) + client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_expanded_data_sets(request) + client.list_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -39016,7 +38926,7 @@ def test_list_expanded_data_sets_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_expanded_data_sets_empty_call_async(): +async def test_list_access_bindings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -39026,22 +38936,22 @@ async def test_list_expanded_data_sets_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListExpandedDataSetsResponse( + analytics_admin.ListAccessBindingsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_expanded_data_sets() + response = await client.list_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListExpandedDataSetsRequest() + assert args[0] == analytics_admin.ListAccessBindingsRequest() @pytest.mark.asyncio -async def test_list_expanded_data_sets_async_use_cached_wrapped_rpc( +async def test_list_access_bindings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -39058,23 +38968,23 @@ async def test_list_expanded_data_sets_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_expanded_data_sets + client._client._transport.list_access_bindings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_expanded_data_sets + client._client._transport.list_access_bindings ] = mock_object request = {} - await client.list_expanded_data_sets(request) + await client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_expanded_data_sets(request) + await client.list_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -39082,9 +38992,9 @@ async def test_list_expanded_data_sets_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_expanded_data_sets_async( +async def test_list_access_bindings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListExpandedDataSetsRequest, + request_type=analytics_admin.ListAccessBindingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -39097,49 +39007,49 @@ async def test_list_expanded_data_sets_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListExpandedDataSetsResponse( + analytics_admin.ListAccessBindingsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_expanded_data_sets(request) + response = await client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListExpandedDataSetsRequest() + request = analytics_admin.ListAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExpandedDataSetsAsyncPager) + assert isinstance(response, pagers.ListAccessBindingsAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_list_expanded_data_sets_async_from_dict(): - await test_list_expanded_data_sets_async(request_type=dict) +async def test_list_access_bindings_async_from_dict(): + await test_list_access_bindings_async(request_type=dict) -def test_list_expanded_data_sets_field_headers(): +def test_list_access_bindings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListExpandedDataSetsRequest() + request = analytics_admin.ListAccessBindingsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: - call.return_value = analytics_admin.ListExpandedDataSetsResponse() - client.list_expanded_data_sets(request) + call.return_value = analytics_admin.ListAccessBindingsResponse() + client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -39155,25 +39065,25 @@ def test_list_expanded_data_sets_field_headers(): @pytest.mark.asyncio -async def test_list_expanded_data_sets_field_headers_async(): +async def test_list_access_bindings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListExpandedDataSetsRequest() + request = analytics_admin.ListAccessBindingsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListExpandedDataSetsResponse() + analytics_admin.ListAccessBindingsResponse() ) - await client.list_expanded_data_sets(request) + await client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -39188,20 +39098,20 @@ async def test_list_expanded_data_sets_field_headers_async(): ) in kw["metadata"] -def test_list_expanded_data_sets_flattened(): +def test_list_access_bindings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListExpandedDataSetsResponse() + call.return_value = analytics_admin.ListAccessBindingsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_expanded_data_sets( + client.list_access_bindings( parent="parent_value", ) @@ -39214,7 +39124,7 @@ def test_list_expanded_data_sets_flattened(): assert arg == mock_val -def test_list_expanded_data_sets_flattened_error(): +def test_list_access_bindings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -39222,31 +39132,31 @@ def test_list_expanded_data_sets_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_expanded_data_sets( - analytics_admin.ListExpandedDataSetsRequest(), + client.list_access_bindings( + analytics_admin.ListAccessBindingsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_expanded_data_sets_flattened_async(): +async def test_list_access_bindings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListExpandedDataSetsResponse() + call.return_value = analytics_admin.ListAccessBindingsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListExpandedDataSetsResponse() + analytics_admin.ListAccessBindingsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_expanded_data_sets( + response = await client.list_access_bindings( parent="parent_value", ) @@ -39260,7 +39170,7 @@ async def test_list_expanded_data_sets_flattened_async(): @pytest.mark.asyncio -async def test_list_expanded_data_sets_flattened_error_async(): +async def test_list_access_bindings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -39268,13 +39178,13 @@ async def test_list_expanded_data_sets_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_expanded_data_sets( - analytics_admin.ListExpandedDataSetsRequest(), + await client.list_access_bindings( + analytics_admin.ListAccessBindingsRequest(), parent="parent_value", ) -def test_list_expanded_data_sets_pager(transport_name: str = "grpc"): +def test_list_access_bindings_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -39282,32 +39192,32 @@ def test_list_expanded_data_sets_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), ], next_page_token="abc", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[], + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], next_page_token="def", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), ], next_page_token="ghi", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), ], ), RuntimeError, @@ -39319,7 +39229,7 @@ def test_list_expanded_data_sets_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_expanded_data_sets(request={}, retry=retry, timeout=timeout) + pager = client.list_access_bindings(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -39327,10 +39237,10 @@ def test_list_expanded_data_sets_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, expanded_data_set.ExpandedDataSet) for i in results) + assert all(isinstance(i, resources.AccessBinding) for i in results) -def test_list_expanded_data_sets_pages(transport_name: str = "grpc"): +def test_list_access_bindings_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -39338,82 +39248,82 @@ def test_list_expanded_data_sets_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), "__call__" + type(client.transport.list_access_bindings), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), ], next_page_token="abc", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[], + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], next_page_token="def", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), ], next_page_token="ghi", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), ], ), RuntimeError, ) - pages = list(client.list_expanded_data_sets(request={}).pages) + pages = list(client.list_access_bindings(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_expanded_data_sets_async_pager(): +async def test_list_access_bindings_async_pager(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), + type(client.transport.list_access_bindings), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), ], next_page_token="abc", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[], + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], next_page_token="def", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), ], next_page_token="ghi", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), ], ), RuntimeError, ) - async_pager = await client.list_expanded_data_sets( + async_pager = await client.list_access_bindings( request={}, ) assert async_pager.next_page_token == "abc" @@ -39422,45 +39332,45 @@ async def test_list_expanded_data_sets_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, expanded_data_set.ExpandedDataSet) for i in responses) + assert all(isinstance(i, resources.AccessBinding) for i in responses) @pytest.mark.asyncio -async def test_list_expanded_data_sets_async_pages(): +async def test_list_access_bindings_async_pages(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_expanded_data_sets), + type(client.transport.list_access_bindings), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), ], next_page_token="abc", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[], + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], next_page_token="def", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), ], next_page_token="ghi", ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), ], ), RuntimeError, @@ -39469,7 +39379,7 @@ async def test_list_expanded_data_sets_async_pages(): # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 async for page_ in ( # pragma: no branch - await client.list_expanded_data_sets(request={}) + await client.list_access_bindings(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -39479,11 +39389,11 @@ async def test_list_expanded_data_sets_async_pages(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateExpandedDataSetRequest, + analytics_admin.BatchCreateAccessBindingsRequest, dict, ], ) -def test_create_expanded_data_set(request_type, transport: str = "grpc"): +def test_batch_create_access_bindings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -39495,34 +39405,23 @@ def test_create_expanded_data_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) - response = client.create_expanded_data_set(request) + call.return_value = analytics_admin.BatchCreateAccessBindingsResponse() + response = client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateExpandedDataSetRequest() + request = analytics_admin.BatchCreateAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) -def test_create_expanded_data_set_empty_call(): +def test_batch_create_access_bindings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -39532,18 +39431,18 @@ def test_create_expanded_data_set_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_expanded_data_set() + client.batch_create_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest() -def test_create_expanded_data_set_non_empty_request_with_auto_populated_field(): +def test_batch_create_access_bindings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -39554,26 +39453,26 @@ def test_create_expanded_data_set_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateExpandedDataSetRequest( + request = analytics_admin.BatchCreateAccessBindingsRequest( parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_expanded_data_set(request=request) + client.batch_create_access_bindings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateExpandedDataSetRequest( + assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest( parent="parent_value", ) -def test_create_expanded_data_set_use_cached_wrapped_rpc(): +def test_batch_create_access_bindings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -39588,7 +39487,7 @@ def test_create_expanded_data_set_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_expanded_data_set + client._transport.batch_create_access_bindings in client._transport._wrapped_methods ) @@ -39598,15 +39497,15 @@ def test_create_expanded_data_set_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_expanded_data_set + client._transport.batch_create_access_bindings ] = mock_rpc request = {} - client.create_expanded_data_set(request) + client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_expanded_data_set(request) + client.batch_create_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -39614,7 +39513,7 @@ def test_create_expanded_data_set_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_expanded_data_set_empty_call_async(): +async def test_batch_create_access_bindings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -39624,26 +39523,20 @@ async def test_create_expanded_data_set_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) + analytics_admin.BatchCreateAccessBindingsResponse() ) - response = await client.create_expanded_data_set() + response = await client.batch_create_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest() @pytest.mark.asyncio -async def test_create_expanded_data_set_async_use_cached_wrapped_rpc( +async def test_batch_create_access_bindings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -39660,23 +39553,23 @@ async def test_create_expanded_data_set_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_expanded_data_set + client._client._transport.batch_create_access_bindings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_expanded_data_set + client._client._transport.batch_create_access_bindings ] = mock_object request = {} - await client.create_expanded_data_set(request) + await client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_expanded_data_set(request) + await client.batch_create_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -39684,9 +39577,9 @@ async def test_create_expanded_data_set_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_expanded_data_set_async( +async def test_batch_create_access_bindings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateExpandedDataSetRequest, + request_type=analytics_admin.BatchCreateAccessBindingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -39699,57 +39592,46 @@ async def test_create_expanded_data_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) + analytics_admin.BatchCreateAccessBindingsResponse() ) - response = await client.create_expanded_data_set(request) + response = await client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateExpandedDataSetRequest() + request = analytics_admin.BatchCreateAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) @pytest.mark.asyncio -async def test_create_expanded_data_set_async_from_dict(): - await test_create_expanded_data_set_async(request_type=dict) +async def test_batch_create_access_bindings_async_from_dict(): + await test_batch_create_access_bindings_async(request_type=dict) -def test_create_expanded_data_set_field_headers(): +def test_batch_create_access_bindings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateExpandedDataSetRequest() + request = analytics_admin.BatchCreateAccessBindingsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: - call.return_value = gaa_expanded_data_set.ExpandedDataSet() - client.create_expanded_data_set(request) + call.return_value = analytics_admin.BatchCreateAccessBindingsResponse() + client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -39765,25 +39647,25 @@ def test_create_expanded_data_set_field_headers(): @pytest.mark.asyncio -async def test_create_expanded_data_set_field_headers_async(): +async def test_batch_create_access_bindings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateExpandedDataSetRequest() + request = analytics_admin.BatchCreateAccessBindingsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" + type(client.transport.batch_create_access_bindings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet() + analytics_admin.BatchCreateAccessBindingsResponse() ) - await client.create_expanded_data_set(request) + await client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -39798,110 +39680,14 @@ async def test_create_expanded_data_set_field_headers_async(): ) in kw["metadata"] -def test_create_expanded_data_set_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gaa_expanded_data_set.ExpandedDataSet() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_expanded_data_set( - parent="parent_value", - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].expanded_data_set - mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") - assert arg == mock_val - - -def test_create_expanded_data_set_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_expanded_data_set( - analytics_admin.CreateExpandedDataSetRequest(), - parent="parent_value", - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - ) - - -@pytest.mark.asyncio -async def test_create_expanded_data_set_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_expanded_data_set), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gaa_expanded_data_set.ExpandedDataSet() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_expanded_data_set( - parent="parent_value", - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].expanded_data_set - mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_expanded_data_set_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_expanded_data_set( - analytics_admin.CreateExpandedDataSetRequest(), - parent="parent_value", - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - ) - - @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateExpandedDataSetRequest, + analytics_admin.BatchGetAccessBindingsRequest, dict, ], ) -def test_update_expanded_data_set(request_type, transport: str = "grpc"): +def test_batch_get_access_bindings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -39913,34 +39699,23 @@ def test_update_expanded_data_set(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) - response = client.update_expanded_data_set(request) + call.return_value = analytics_admin.BatchGetAccessBindingsResponse() + response = client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateExpandedDataSetRequest() + request = analytics_admin.BatchGetAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) -def test_update_expanded_data_set_empty_call(): +def test_batch_get_access_bindings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -39950,18 +39725,18 @@ def test_update_expanded_data_set_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_expanded_data_set() + client.batch_get_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchGetAccessBindingsRequest() -def test_update_expanded_data_set_non_empty_request_with_auto_populated_field(): +def test_batch_get_access_bindings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -39972,22 +39747,26 @@ def test_update_expanded_data_set_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateExpandedDataSetRequest() + request = analytics_admin.BatchGetAccessBindingsRequest( + parent="parent_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_expanded_data_set(request=request) + client.batch_get_access_bindings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchGetAccessBindingsRequest( + parent="parent_value", + ) -def test_update_expanded_data_set_use_cached_wrapped_rpc(): +def test_batch_get_access_bindings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -40002,7 +39781,7 @@ def test_update_expanded_data_set_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_expanded_data_set + client._transport.batch_get_access_bindings in client._transport._wrapped_methods ) @@ -40012,15 +39791,15 @@ def test_update_expanded_data_set_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_expanded_data_set + client._transport.batch_get_access_bindings ] = mock_rpc request = {} - client.update_expanded_data_set(request) + client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_expanded_data_set(request) + client.batch_get_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -40028,7 +39807,7 @@ def test_update_expanded_data_set_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_expanded_data_set_empty_call_async(): +async def test_batch_get_access_bindings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -40038,26 +39817,20 @@ async def test_update_expanded_data_set_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) + analytics_admin.BatchGetAccessBindingsResponse() ) - response = await client.update_expanded_data_set() + response = await client.batch_get_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchGetAccessBindingsRequest() @pytest.mark.asyncio -async def test_update_expanded_data_set_async_use_cached_wrapped_rpc( +async def test_batch_get_access_bindings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -40074,23 +39847,23 @@ async def test_update_expanded_data_set_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_expanded_data_set + client._client._transport.batch_get_access_bindings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_expanded_data_set + client._client._transport.batch_get_access_bindings ] = mock_object request = {} - await client.update_expanded_data_set(request) + await client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_expanded_data_set(request) + await client.batch_get_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -40098,9 +39871,9 @@ async def test_update_expanded_data_set_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_expanded_data_set_async( +async def test_batch_get_access_bindings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateExpandedDataSetRequest, + request_type=analytics_admin.BatchGetAccessBindingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -40113,57 +39886,46 @@ async def test_update_expanded_data_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) + analytics_admin.BatchGetAccessBindingsResponse() ) - response = await client.update_expanded_data_set(request) + response = await client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateExpandedDataSetRequest() + request = analytics_admin.BatchGetAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) @pytest.mark.asyncio -async def test_update_expanded_data_set_async_from_dict(): - await test_update_expanded_data_set_async(request_type=dict) +async def test_batch_get_access_bindings_async_from_dict(): + await test_batch_get_access_bindings_async(request_type=dict) -def test_update_expanded_data_set_field_headers(): +def test_batch_get_access_bindings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateExpandedDataSetRequest() + request = analytics_admin.BatchGetAccessBindingsRequest() - request.expanded_data_set.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: - call.return_value = gaa_expanded_data_set.ExpandedDataSet() - client.update_expanded_data_set(request) + call.return_value = analytics_admin.BatchGetAccessBindingsResponse() + client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -40174,30 +39936,30 @@ def test_update_expanded_data_set_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "expanded_data_set.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_expanded_data_set_field_headers_async(): +async def test_batch_get_access_bindings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateExpandedDataSetRequest() + request = analytics_admin.BatchGetAccessBindingsRequest() - request.expanded_data_set.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_get_access_bindings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet() + analytics_admin.BatchGetAccessBindingsResponse() ) - await client.update_expanded_data_set(request) + await client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -40208,142 +39970,46 @@ async def test_update_expanded_data_set_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "expanded_data_set.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_expanded_data_set_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.BatchUpdateAccessBindingsRequest, + dict, + ], +) +def test_batch_update_access_bindings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_expanded_data_set.ExpandedDataSet() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_expanded_data_set( - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].expanded_data_set - mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_expanded_data_set_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_expanded_data_set( - analytics_admin.UpdateExpandedDataSetRequest(), - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_expanded_data_set_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_expanded_data_set), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gaa_expanded_data_set.ExpandedDataSet() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_expanded_data_set.ExpandedDataSet() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_expanded_data_set( - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].expanded_data_set - mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_expanded_data_set_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_expanded_data_set( - analytics_admin.UpdateExpandedDataSetRequest(), - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.DeleteExpandedDataSetRequest, - dict, - ], -) -def test_delete_expanded_data_set(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_expanded_data_set(request) + call.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + response = client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteExpandedDataSetRequest() + request = analytics_admin.BatchUpdateAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) -def test_delete_expanded_data_set_empty_call(): +def test_batch_update_access_bindings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -40353,18 +40019,18 @@ def test_delete_expanded_data_set_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_expanded_data_set() + client.batch_update_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest() -def test_delete_expanded_data_set_non_empty_request_with_auto_populated_field(): +def test_batch_update_access_bindings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -40375,26 +40041,26 @@ def test_delete_expanded_data_set_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteExpandedDataSetRequest( - name="name_value", + request = analytics_admin.BatchUpdateAccessBindingsRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_expanded_data_set(request=request) + client.batch_update_access_bindings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteExpandedDataSetRequest( - name="name_value", + assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest( + parent="parent_value", ) -def test_delete_expanded_data_set_use_cached_wrapped_rpc(): +def test_batch_update_access_bindings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -40409,7 +40075,7 @@ def test_delete_expanded_data_set_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_expanded_data_set + client._transport.batch_update_access_bindings in client._transport._wrapped_methods ) @@ -40419,15 +40085,15 @@ def test_delete_expanded_data_set_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_expanded_data_set + client._transport.batch_update_access_bindings ] = mock_rpc request = {} - client.delete_expanded_data_set(request) + client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_expanded_data_set(request) + client.batch_update_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -40435,7 +40101,7 @@ def test_delete_expanded_data_set_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_expanded_data_set_empty_call_async(): +async def test_batch_update_access_bindings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -40445,18 +40111,20 @@ async def test_delete_expanded_data_set_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_expanded_data_set() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.BatchUpdateAccessBindingsResponse() + ) + response = await client.batch_update_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteExpandedDataSetRequest() + assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest() @pytest.mark.asyncio -async def test_delete_expanded_data_set_async_use_cached_wrapped_rpc( +async def test_batch_update_access_bindings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -40473,23 +40141,23 @@ async def test_delete_expanded_data_set_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_expanded_data_set + client._client._transport.batch_update_access_bindings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_expanded_data_set + client._client._transport.batch_update_access_bindings ] = mock_object request = {} - await client.delete_expanded_data_set(request) + await client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_expanded_data_set(request) + await client.batch_update_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -40497,9 +40165,9 @@ async def test_delete_expanded_data_set_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_expanded_data_set_async( +async def test_batch_update_access_bindings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteExpandedDataSetRequest, + request_type=analytics_admin.BatchUpdateAccessBindingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -40512,44 +40180,46 @@ async def test_delete_expanded_data_set_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_expanded_data_set(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.BatchUpdateAccessBindingsResponse() + ) + response = await client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteExpandedDataSetRequest() + request = analytics_admin.BatchUpdateAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) @pytest.mark.asyncio -async def test_delete_expanded_data_set_async_from_dict(): - await test_delete_expanded_data_set_async(request_type=dict) +async def test_batch_update_access_bindings_async_from_dict(): + await test_batch_update_access_bindings_async(request_type=dict) -def test_delete_expanded_data_set_field_headers(): +def test_batch_update_access_bindings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteExpandedDataSetRequest() + request = analytics_admin.BatchUpdateAccessBindingsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: - call.return_value = None - client.delete_expanded_data_set(request) + call.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -40560,28 +40230,30 @@ def test_delete_expanded_data_set_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_expanded_data_set_field_headers_async(): +async def test_batch_update_access_bindings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteExpandedDataSetRequest() + request = analytics_admin.BatchUpdateAccessBindingsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" + type(client.transport.batch_update_access_bindings), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_expanded_data_set(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.BatchUpdateAccessBindingsResponse() + ) + await client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -40592,102 +40264,18 @@ async def test_delete_expanded_data_set_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_expanded_data_set_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_expanded_data_set( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_delete_expanded_data_set_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_expanded_data_set( - analytics_admin.DeleteExpandedDataSetRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_delete_expanded_data_set_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_expanded_data_set), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_expanded_data_set( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_delete_expanded_data_set_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_expanded_data_set( - analytics_admin.DeleteExpandedDataSetRequest(), - name="name_value", - ) - - @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetChannelGroupRequest, + analytics_admin.BatchDeleteAccessBindingsRequest, dict, ], ) -def test_get_channel_group(request_type, transport: str = "grpc"): +def test_batch_delete_access_bindings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -40699,32 +40287,23 @@ def test_get_channel_group(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = channel_group.ChannelGroup( - name="name_value", - display_name="display_name_value", - description="description_value", - system_defined=True, - ) - response = client.get_channel_group(request) + call.return_value = None + response = client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetChannelGroupRequest() + request = analytics_admin.BatchDeleteAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, channel_group.ChannelGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.system_defined is True + assert response is None -def test_get_channel_group_empty_call(): +def test_batch_delete_access_bindings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -40734,18 +40313,18 @@ def test_get_channel_group_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_channel_group() + client.batch_delete_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetChannelGroupRequest() + assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest() -def test_get_channel_group_non_empty_request_with_auto_populated_field(): +def test_batch_delete_access_bindings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -40756,26 +40335,26 @@ def test_get_channel_group_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetChannelGroupRequest( - name="name_value", + request = analytics_admin.BatchDeleteAccessBindingsRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_channel_group(request=request) + client.batch_delete_access_bindings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetChannelGroupRequest( - name="name_value", + assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest( + parent="parent_value", ) -def test_get_channel_group_use_cached_wrapped_rpc(): +def test_batch_delete_access_bindings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -40789,7 +40368,10 @@ def test_get_channel_group_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_channel_group in client._transport._wrapped_methods + assert ( + client._transport.batch_delete_access_bindings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -40797,15 +40379,15 @@ def test_get_channel_group_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_channel_group + client._transport.batch_delete_access_bindings ] = mock_rpc request = {} - client.get_channel_group(request) + client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_channel_group(request) + client.batch_delete_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -40813,7 +40395,7 @@ def test_get_channel_group_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_channel_group_empty_call_async(): +async def test_batch_delete_access_bindings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -40823,25 +40405,18 @@ async def test_get_channel_group_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - channel_group.ChannelGroup( - name="name_value", - display_name="display_name_value", - description="description_value", - system_defined=True, - ) - ) - response = await client.get_channel_group() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_access_bindings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetChannelGroupRequest() + assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest() @pytest.mark.asyncio -async def test_get_channel_group_async_use_cached_wrapped_rpc( +async def test_batch_delete_access_bindings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -40858,23 +40433,23 @@ async def test_get_channel_group_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_channel_group + client._client._transport.batch_delete_access_bindings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_channel_group + client._client._transport.batch_delete_access_bindings ] = mock_object request = {} - await client.get_channel_group(request) + await client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_channel_group(request) + await client.batch_delete_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -40882,8 +40457,9 @@ async def test_get_channel_group_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_channel_group_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.GetChannelGroupRequest +async def test_batch_delete_access_bindings_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.BatchDeleteAccessBindingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -40896,55 +40472,44 @@ async def test_get_channel_group_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - channel_group.ChannelGroup( - name="name_value", - display_name="display_name_value", - description="description_value", - system_defined=True, - ) - ) - response = await client.get_channel_group(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetChannelGroupRequest() + request = analytics_admin.BatchDeleteAccessBindingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, channel_group.ChannelGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.system_defined is True + assert response is None @pytest.mark.asyncio -async def test_get_channel_group_async_from_dict(): - await test_get_channel_group_async(request_type=dict) +async def test_batch_delete_access_bindings_async_from_dict(): + await test_batch_delete_access_bindings_async(request_type=dict) -def test_get_channel_group_field_headers(): +def test_batch_delete_access_bindings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetChannelGroupRequest() + request = analytics_admin.BatchDeleteAccessBindingsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: - call.return_value = channel_group.ChannelGroup() - client.get_channel_group(request) + call.return_value = None + client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -40955,30 +40520,28 @@ def test_get_channel_group_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_channel_group_field_headers_async(): +async def test_batch_delete_access_bindings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetChannelGroupRequest() + request = analytics_admin.BatchDeleteAccessBindingsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.batch_delete_access_bindings), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - channel_group.ChannelGroup() - ) - await client.get_channel_group(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -40989,69 +40552,391 @@ async def test_get_channel_group_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_channel_group_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetExpandedDataSetRequest, + dict, + ], +) +def test_get_expanded_data_set(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.get_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = channel_group.ChannelGroup() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_channel_group( + call.return_value = expanded_data_set.ExpandedDataSet( name="name_value", + display_name="display_name_value", + description="description_value", + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) + response = client.get_expanded_data_set(request) - # Establish that the underlying call was made with the expected - # request object values. + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val + request = analytics_admin.GetExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, expanded_data_set.ExpandedDataSet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] -def test_get_channel_group_flattened_error(): +def test_get_expanded_data_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_channel_group( - analytics_admin.GetChannelGroupRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.get_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetExpandedDataSetRequest() -@pytest.mark.asyncio -async def test_get_channel_group_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( +def test_get_expanded_data_set_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.GetExpandedDataSetRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_channel_group), "__call__" + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_expanded_data_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetExpandedDataSetRequest( + name="name_value", + ) + + +def test_get_expanded_data_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_expanded_data_set + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_expanded_data_set + ] = mock_rpc + request = {} + client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_expanded_data_set_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = channel_group.ChannelGroup() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + expanded_data_set.ExpandedDataSet( + name="name_value", + display_name="display_name_value", + description="description_value", + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], + ) + ) + response = await client.get_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetExpandedDataSetRequest() + + +@pytest.mark.asyncio +async def test_get_expanded_data_set_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_expanded_data_set + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_expanded_data_set + ] = mock_object + + request = {} + await client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_expanded_data_set_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.GetExpandedDataSetRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - channel_group.ChannelGroup() + expanded_data_set.ExpandedDataSet( + name="name_value", + display_name="display_name_value", + description="description_value", + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], + ) + ) + response = await client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, expanded_data_set.ExpandedDataSet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] + + +@pytest.mark.asyncio +async def test_get_expanded_data_set_async_from_dict(): + await test_get_expanded_data_set_async(request_type=dict) + + +def test_get_expanded_data_set_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetExpandedDataSetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + call.return_value = expanded_data_set.ExpandedDataSet() + client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_expanded_data_set_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetExpandedDataSetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + expanded_data_set.ExpandedDataSet() ) + await client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_expanded_data_set_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = expanded_data_set.ExpandedDataSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_channel_group( + client.get_expanded_data_set( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_expanded_data_set_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_expanded_data_set( + analytics_admin.GetExpandedDataSetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_expanded_data_set_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = expanded_data_set.ExpandedDataSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + expanded_data_set.ExpandedDataSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_expanded_data_set( name="name_value", ) @@ -41065,7 +40950,7 @@ async def test_get_channel_group_flattened_async(): @pytest.mark.asyncio -async def test_get_channel_group_flattened_error_async(): +async def test_get_expanded_data_set_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -41073,8 +40958,8 @@ async def test_get_channel_group_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_channel_group( - analytics_admin.GetChannelGroupRequest(), + await client.get_expanded_data_set( + analytics_admin.GetExpandedDataSetRequest(), name="name_value", ) @@ -41082,11 +40967,11 @@ async def test_get_channel_group_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListChannelGroupsRequest, + analytics_admin.ListExpandedDataSetsRequest, dict, ], ) -def test_list_channel_groups(request_type, transport: str = "grpc"): +def test_list_expanded_data_sets(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -41098,26 +40983,26 @@ def test_list_channel_groups(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListChannelGroupsResponse( + call.return_value = analytics_admin.ListExpandedDataSetsResponse( next_page_token="next_page_token_value", ) - response = client.list_channel_groups(request) + response = client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListChannelGroupsRequest() + request = analytics_admin.ListExpandedDataSetsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelGroupsPager) + assert isinstance(response, pagers.ListExpandedDataSetsPager) assert response.next_page_token == "next_page_token_value" -def test_list_channel_groups_empty_call(): +def test_list_expanded_data_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -41127,18 +41012,18 @@ def test_list_channel_groups_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_channel_groups() + client.list_expanded_data_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListChannelGroupsRequest() + assert args[0] == analytics_admin.ListExpandedDataSetsRequest() -def test_list_channel_groups_non_empty_request_with_auto_populated_field(): +def test_list_expanded_data_sets_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -41149,28 +41034,28 @@ def test_list_channel_groups_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListChannelGroupsRequest( + request = analytics_admin.ListExpandedDataSetsRequest( parent="parent_value", page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_channel_groups(request=request) + client.list_expanded_data_sets(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListChannelGroupsRequest( + assert args[0] == analytics_admin.ListExpandedDataSetsRequest( parent="parent_value", page_token="page_token_value", ) -def test_list_channel_groups_use_cached_wrapped_rpc(): +def test_list_expanded_data_sets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -41185,7 +41070,8 @@ def test_list_channel_groups_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_channel_groups in client._transport._wrapped_methods + client._transport.list_expanded_data_sets + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -41194,15 +41080,15 @@ def test_list_channel_groups_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_channel_groups + client._transport.list_expanded_data_sets ] = mock_rpc request = {} - client.list_channel_groups(request) + client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_channel_groups(request) + client.list_expanded_data_sets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -41210,7 +41096,7 @@ def test_list_channel_groups_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_channel_groups_empty_call_async(): +async def test_list_expanded_data_sets_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -41220,22 +41106,22 @@ async def test_list_channel_groups_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListChannelGroupsResponse( + analytics_admin.ListExpandedDataSetsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_channel_groups() + response = await client.list_expanded_data_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListChannelGroupsRequest() + assert args[0] == analytics_admin.ListExpandedDataSetsRequest() @pytest.mark.asyncio -async def test_list_channel_groups_async_use_cached_wrapped_rpc( +async def test_list_expanded_data_sets_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -41252,23 +41138,23 @@ async def test_list_channel_groups_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_channel_groups + client._client._transport.list_expanded_data_sets in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_channel_groups + client._client._transport.list_expanded_data_sets ] = mock_object request = {} - await client.list_channel_groups(request) + await client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_channel_groups(request) + await client.list_expanded_data_sets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -41276,9 +41162,9 @@ async def test_list_channel_groups_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_channel_groups_async( +async def test_list_expanded_data_sets_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListChannelGroupsRequest, + request_type=analytics_admin.ListExpandedDataSetsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -41291,49 +41177,49 @@ async def test_list_channel_groups_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListChannelGroupsResponse( + analytics_admin.ListExpandedDataSetsResponse( next_page_token="next_page_token_value", ) ) - response = await client.list_channel_groups(request) + response = await client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListChannelGroupsRequest() + request = analytics_admin.ListExpandedDataSetsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelGroupsAsyncPager) + assert isinstance(response, pagers.ListExpandedDataSetsAsyncPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_list_channel_groups_async_from_dict(): - await test_list_channel_groups_async(request_type=dict) +async def test_list_expanded_data_sets_async_from_dict(): + await test_list_expanded_data_sets_async(request_type=dict) -def test_list_channel_groups_field_headers(): +def test_list_expanded_data_sets_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListChannelGroupsRequest() + request = analytics_admin.ListExpandedDataSetsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: - call.return_value = analytics_admin.ListChannelGroupsResponse() - client.list_channel_groups(request) + call.return_value = analytics_admin.ListExpandedDataSetsResponse() + client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -41349,25 +41235,25 @@ def test_list_channel_groups_field_headers(): @pytest.mark.asyncio -async def test_list_channel_groups_field_headers_async(): +async def test_list_expanded_data_sets_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListChannelGroupsRequest() + request = analytics_admin.ListExpandedDataSetsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListChannelGroupsResponse() + analytics_admin.ListExpandedDataSetsResponse() ) - await client.list_channel_groups(request) + await client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -41382,20 +41268,20 @@ async def test_list_channel_groups_field_headers_async(): ) in kw["metadata"] -def test_list_channel_groups_flattened(): +def test_list_expanded_data_sets_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListChannelGroupsResponse() + call.return_value = analytics_admin.ListExpandedDataSetsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_channel_groups( + client.list_expanded_data_sets( parent="parent_value", ) @@ -41408,7 +41294,7 @@ def test_list_channel_groups_flattened(): assert arg == mock_val -def test_list_channel_groups_flattened_error(): +def test_list_expanded_data_sets_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -41416,31 +41302,31 @@ def test_list_channel_groups_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_channel_groups( - analytics_admin.ListChannelGroupsRequest(), + client.list_expanded_data_sets( + analytics_admin.ListExpandedDataSetsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_channel_groups_flattened_async(): +async def test_list_expanded_data_sets_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListChannelGroupsResponse() + call.return_value = analytics_admin.ListExpandedDataSetsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListChannelGroupsResponse() + analytics_admin.ListExpandedDataSetsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_channel_groups( + response = await client.list_expanded_data_sets( parent="parent_value", ) @@ -41454,7 +41340,7 @@ async def test_list_channel_groups_flattened_async(): @pytest.mark.asyncio -async def test_list_channel_groups_flattened_error_async(): +async def test_list_expanded_data_sets_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -41462,13 +41348,13 @@ async def test_list_channel_groups_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_channel_groups( - analytics_admin.ListChannelGroupsRequest(), + await client.list_expanded_data_sets( + analytics_admin.ListExpandedDataSetsRequest(), parent="parent_value", ) -def test_list_channel_groups_pager(transport_name: str = "grpc"): +def test_list_expanded_data_sets_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -41476,32 +41362,32 @@ def test_list_channel_groups_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], next_page_token="abc", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[], + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], next_page_token="def", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), ], next_page_token="ghi", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], ), RuntimeError, @@ -41513,7 +41399,7 @@ def test_list_channel_groups_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_channel_groups(request={}, retry=retry, timeout=timeout) + pager = client.list_expanded_data_sets(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -41521,10 +41407,10 @@ def test_list_channel_groups_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, channel_group.ChannelGroup) for i in results) + assert all(isinstance(i, expanded_data_set.ExpandedDataSet) for i in results) -def test_list_channel_groups_pages(transport_name: str = "grpc"): +def test_list_expanded_data_sets_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -41532,82 +41418,82 @@ def test_list_channel_groups_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), "__call__" + type(client.transport.list_expanded_data_sets), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], next_page_token="abc", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[], + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], next_page_token="def", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), ], next_page_token="ghi", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], ), RuntimeError, ) - pages = list(client.list_channel_groups(request={}).pages) + pages = list(client.list_expanded_data_sets(request={}).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_list_channel_groups_async_pager(): +async def test_list_expanded_data_sets_async_pager(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), + type(client.transport.list_expanded_data_sets), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], next_page_token="abc", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[], + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], next_page_token="def", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), ], next_page_token="ghi", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], ), RuntimeError, ) - async_pager = await client.list_channel_groups( + async_pager = await client.list_expanded_data_sets( request={}, ) assert async_pager.next_page_token == "abc" @@ -41616,45 +41502,45 @@ async def test_list_channel_groups_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, channel_group.ChannelGroup) for i in responses) + assert all(isinstance(i, expanded_data_set.ExpandedDataSet) for i in responses) @pytest.mark.asyncio -async def test_list_channel_groups_async_pages(): +async def test_list_expanded_data_sets_async_pages(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_channel_groups), + type(client.transport.list_expanded_data_sets), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], next_page_token="abc", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[], + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], next_page_token="def", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), ], next_page_token="ghi", ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), ], ), RuntimeError, @@ -41663,7 +41549,7 @@ async def test_list_channel_groups_async_pages(): # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 async for page_ in ( # pragma: no branch - await client.list_channel_groups(request={}) + await client.list_expanded_data_sets(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -41673,11 +41559,11 @@ async def test_list_channel_groups_async_pages(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateChannelGroupRequest, + analytics_admin.CreateExpandedDataSetRequest, dict, ], ) -def test_create_channel_group(request_type, transport: str = "grpc"): +def test_create_expanded_data_set(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -41689,32 +41575,34 @@ def test_create_channel_group(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_channel_group.ChannelGroup( + call.return_value = gaa_expanded_data_set.ExpandedDataSet( name="name_value", display_name="display_name_value", description="description_value", - system_defined=True, + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) - response = client.create_channel_group(request) + response = client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateChannelGroupRequest() + request = analytics_admin.CreateExpandedDataSetRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_channel_group.ChannelGroup) + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.system_defined is True + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] -def test_create_channel_group_empty_call(): +def test_create_expanded_data_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -41724,18 +41612,18 @@ def test_create_channel_group_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_channel_group() + client.create_expanded_data_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateChannelGroupRequest() + assert args[0] == analytics_admin.CreateExpandedDataSetRequest() -def test_create_channel_group_non_empty_request_with_auto_populated_field(): +def test_create_expanded_data_set_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -41746,26 +41634,26 @@ def test_create_channel_group_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateChannelGroupRequest( + request = analytics_admin.CreateExpandedDataSetRequest( parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_channel_group(request=request) + client.create_expanded_data_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateChannelGroupRequest( + assert args[0] == analytics_admin.CreateExpandedDataSetRequest( parent="parent_value", ) -def test_create_channel_group_use_cached_wrapped_rpc(): +def test_create_expanded_data_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -41780,7 +41668,8 @@ def test_create_channel_group_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_channel_group in client._transport._wrapped_methods + client._transport.create_expanded_data_set + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -41789,15 +41678,15 @@ def test_create_channel_group_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_channel_group + client._transport.create_expanded_data_set ] = mock_rpc request = {} - client.create_channel_group(request) + client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_channel_group(request) + client.create_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -41805,7 +41694,7 @@ def test_create_channel_group_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_channel_group_empty_call_async(): +async def test_create_expanded_data_set_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -41815,25 +41704,26 @@ async def test_create_channel_group_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup( + gaa_expanded_data_set.ExpandedDataSet( name="name_value", display_name="display_name_value", description="description_value", - system_defined=True, + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) ) - response = await client.create_channel_group() + response = await client.create_expanded_data_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateChannelGroupRequest() + assert args[0] == analytics_admin.CreateExpandedDataSetRequest() @pytest.mark.asyncio -async def test_create_channel_group_async_use_cached_wrapped_rpc( +async def test_create_expanded_data_set_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -41850,23 +41740,23 @@ async def test_create_channel_group_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_channel_group + client._client._transport.create_expanded_data_set in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_channel_group + client._client._transport.create_expanded_data_set ] = mock_object request = {} - await client.create_channel_group(request) + await client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_channel_group(request) + await client.create_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -41874,9 +41764,9 @@ async def test_create_channel_group_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_channel_group_async( +async def test_create_expanded_data_set_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateChannelGroupRequest, + request_type=analytics_admin.CreateExpandedDataSetRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -41889,55 +41779,57 @@ async def test_create_channel_group_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup( + gaa_expanded_data_set.ExpandedDataSet( name="name_value", display_name="display_name_value", description="description_value", - system_defined=True, + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) ) - response = await client.create_channel_group(request) + response = await client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateChannelGroupRequest() + request = analytics_admin.CreateExpandedDataSetRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_channel_group.ChannelGroup) + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.system_defined is True + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] @pytest.mark.asyncio -async def test_create_channel_group_async_from_dict(): - await test_create_channel_group_async(request_type=dict) +async def test_create_expanded_data_set_async_from_dict(): + await test_create_expanded_data_set_async(request_type=dict) -def test_create_channel_group_field_headers(): +def test_create_expanded_data_set_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateChannelGroupRequest() + request = analytics_admin.CreateExpandedDataSetRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: - call.return_value = gaa_channel_group.ChannelGroup() - client.create_channel_group(request) + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -41953,25 +41845,25 @@ def test_create_channel_group_field_headers(): @pytest.mark.asyncio -async def test_create_channel_group_field_headers_async(): +async def test_create_expanded_data_set_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateChannelGroupRequest() + request = analytics_admin.CreateExpandedDataSetRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup() + gaa_expanded_data_set.ExpandedDataSet() ) - await client.create_channel_group(request) + await client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -41986,22 +41878,22 @@ async def test_create_channel_group_field_headers_async(): ) in kw["metadata"] -def test_create_channel_group_flattened(): +def test_create_expanded_data_set_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_channel_group.ChannelGroup() + call.return_value = gaa_expanded_data_set.ExpandedDataSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_channel_group( + client.create_expanded_data_set( parent="parent_value", - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -42011,12 +41903,12 @@ def test_create_channel_group_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].channel_group - mock_val = gaa_channel_group.ChannelGroup(name="name_value") + arg = args[0].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") assert arg == mock_val -def test_create_channel_group_flattened_error(): +def test_create_expanded_data_set_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -42024,34 +41916,34 @@ def test_create_channel_group_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_channel_group( - analytics_admin.CreateChannelGroupRequest(), + client.create_expanded_data_set( + analytics_admin.CreateExpandedDataSetRequest(), parent="parent_value", - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), ) @pytest.mark.asyncio -async def test_create_channel_group_flattened_async(): +async def test_create_expanded_data_set_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_channel_group), "__call__" + type(client.transport.create_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_channel_group.ChannelGroup() + call.return_value = gaa_expanded_data_set.ExpandedDataSet() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup() + gaa_expanded_data_set.ExpandedDataSet() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_channel_group( + response = await client.create_expanded_data_set( parent="parent_value", - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -42061,13 +41953,13 @@ async def test_create_channel_group_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].channel_group - mock_val = gaa_channel_group.ChannelGroup(name="name_value") + arg = args[0].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_create_channel_group_flattened_error_async(): +async def test_create_expanded_data_set_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -42075,21 +41967,21 @@ async def test_create_channel_group_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_channel_group( - analytics_admin.CreateChannelGroupRequest(), + await client.create_expanded_data_set( + analytics_admin.CreateExpandedDataSetRequest(), parent="parent_value", - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateChannelGroupRequest, + analytics_admin.UpdateExpandedDataSetRequest, dict, ], ) -def test_update_channel_group(request_type, transport: str = "grpc"): +def test_update_expanded_data_set(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -42101,32 +41993,34 @@ def test_update_channel_group(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_channel_group.ChannelGroup( + call.return_value = gaa_expanded_data_set.ExpandedDataSet( name="name_value", display_name="display_name_value", description="description_value", - system_defined=True, + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) - response = client.update_channel_group(request) + response = client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateChannelGroupRequest() + request = analytics_admin.UpdateExpandedDataSetRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_channel_group.ChannelGroup) + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.system_defined is True + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] -def test_update_channel_group_empty_call(): +def test_update_expanded_data_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -42136,18 +42030,18 @@ def test_update_channel_group_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_channel_group() + client.update_expanded_data_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateChannelGroupRequest() + assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() -def test_update_channel_group_non_empty_request_with_auto_populated_field(): +def test_update_expanded_data_set_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -42158,22 +42052,22 @@ def test_update_channel_group_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateChannelGroupRequest() + request = analytics_admin.UpdateExpandedDataSetRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_channel_group(request=request) + client.update_expanded_data_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateChannelGroupRequest() + assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() -def test_update_channel_group_use_cached_wrapped_rpc(): +def test_update_expanded_data_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -42188,7 +42082,8 @@ def test_update_channel_group_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_channel_group in client._transport._wrapped_methods + client._transport.update_expanded_data_set + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -42197,15 +42092,15 @@ def test_update_channel_group_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_channel_group + client._transport.update_expanded_data_set ] = mock_rpc request = {} - client.update_channel_group(request) + client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_channel_group(request) + client.update_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -42213,7 +42108,7 @@ def test_update_channel_group_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_channel_group_empty_call_async(): +async def test_update_expanded_data_set_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -42223,25 +42118,26 @@ async def test_update_channel_group_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup( + gaa_expanded_data_set.ExpandedDataSet( name="name_value", display_name="display_name_value", description="description_value", - system_defined=True, + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) ) - response = await client.update_channel_group() + response = await client.update_expanded_data_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateChannelGroupRequest() + assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() @pytest.mark.asyncio -async def test_update_channel_group_async_use_cached_wrapped_rpc( +async def test_update_expanded_data_set_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -42258,23 +42154,23 @@ async def test_update_channel_group_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_channel_group + client._client._transport.update_expanded_data_set in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_channel_group + client._client._transport.update_expanded_data_set ] = mock_object request = {} - await client.update_channel_group(request) + await client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_channel_group(request) + await client.update_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -42282,9 +42178,9 @@ async def test_update_channel_group_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_channel_group_async( +async def test_update_expanded_data_set_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateChannelGroupRequest, + request_type=analytics_admin.UpdateExpandedDataSetRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -42297,55 +42193,57 @@ async def test_update_channel_group_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup( + gaa_expanded_data_set.ExpandedDataSet( name="name_value", display_name="display_name_value", description="description_value", - system_defined=True, + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) ) - response = await client.update_channel_group(request) + response = await client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateChannelGroupRequest() + request = analytics_admin.UpdateExpandedDataSetRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_channel_group.ChannelGroup) + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.system_defined is True + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] @pytest.mark.asyncio -async def test_update_channel_group_async_from_dict(): - await test_update_channel_group_async(request_type=dict) +async def test_update_expanded_data_set_async_from_dict(): + await test_update_expanded_data_set_async(request_type=dict) -def test_update_channel_group_field_headers(): +def test_update_expanded_data_set_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateChannelGroupRequest() + request = analytics_admin.UpdateExpandedDataSetRequest() - request.channel_group.name = "name_value" + request.expanded_data_set.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: - call.return_value = gaa_channel_group.ChannelGroup() - client.update_channel_group(request) + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -42356,30 +42254,30 @@ def test_update_channel_group_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "channel_group.name=name_value", + "expanded_data_set.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_channel_group_field_headers_async(): +async def test_update_expanded_data_set_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateChannelGroupRequest() + request = analytics_admin.UpdateExpandedDataSetRequest() - request.channel_group.name = "name_value" + request.expanded_data_set.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup() + gaa_expanded_data_set.ExpandedDataSet() ) - await client.update_channel_group(request) + await client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -42390,25 +42288,25 @@ async def test_update_channel_group_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "channel_group.name=name_value", + "expanded_data_set.name=name_value", ) in kw["metadata"] -def test_update_channel_group_flattened(): +def test_update_expanded_data_set_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_channel_group.ChannelGroup() + call.return_value = gaa_expanded_data_set.ExpandedDataSet() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_channel_group( - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + client.update_expanded_data_set( + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -42416,15 +42314,15 @@ def test_update_channel_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].channel_group - mock_val = gaa_channel_group.ChannelGroup(name="name_value") + arg = args[0].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_update_channel_group_flattened_error(): +def test_update_expanded_data_set_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -42432,33 +42330,33 @@ def test_update_channel_group_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_channel_group( - analytics_admin.UpdateChannelGroupRequest(), - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + client.update_expanded_data_set( + analytics_admin.UpdateExpandedDataSetRequest(), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_channel_group_flattened_async(): +async def test_update_expanded_data_set_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_channel_group), "__call__" + type(client.transport.update_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_channel_group.ChannelGroup() + call.return_value = gaa_expanded_data_set.ExpandedDataSet() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_channel_group.ChannelGroup() + gaa_expanded_data_set.ExpandedDataSet() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_channel_group( - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + response = await client.update_expanded_data_set( + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -42466,8 +42364,8 @@ async def test_update_channel_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].channel_group - mock_val = gaa_channel_group.ChannelGroup(name="name_value") + arg = args[0].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -42475,7 +42373,7 @@ async def test_update_channel_group_flattened_async(): @pytest.mark.asyncio -async def test_update_channel_group_flattened_error_async(): +async def test_update_expanded_data_set_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -42483,9 +42381,9 @@ async def test_update_channel_group_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_channel_group( - analytics_admin.UpdateChannelGroupRequest(), - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + await client.update_expanded_data_set( + analytics_admin.UpdateExpandedDataSetRequest(), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -42493,11 +42391,11 @@ async def test_update_channel_group_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteChannelGroupRequest, + analytics_admin.DeleteExpandedDataSetRequest, dict, ], ) -def test_delete_channel_group(request_type, transport: str = "grpc"): +def test_delete_expanded_data_set(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -42509,23 +42407,23 @@ def test_delete_channel_group(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_channel_group(request) + response = client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteChannelGroupRequest() + request = analytics_admin.DeleteExpandedDataSetRequest() assert args[0] == request # Establish that the response is the type that we expect. assert response is None -def test_delete_channel_group_empty_call(): +def test_delete_expanded_data_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -42535,18 +42433,18 @@ def test_delete_channel_group_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_channel_group() + client.delete_expanded_data_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteChannelGroupRequest() + assert args[0] == analytics_admin.DeleteExpandedDataSetRequest() -def test_delete_channel_group_non_empty_request_with_auto_populated_field(): +def test_delete_expanded_data_set_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -42557,26 +42455,26 @@ def test_delete_channel_group_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteChannelGroupRequest( + request = analytics_admin.DeleteExpandedDataSetRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_channel_group(request=request) + client.delete_expanded_data_set(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteChannelGroupRequest( + assert args[0] == analytics_admin.DeleteExpandedDataSetRequest( name="name_value", ) -def test_delete_channel_group_use_cached_wrapped_rpc(): +def test_delete_expanded_data_set_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -42591,7 +42489,8 @@ def test_delete_channel_group_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_channel_group in client._transport._wrapped_methods + client._transport.delete_expanded_data_set + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -42600,15 +42499,15 @@ def test_delete_channel_group_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_channel_group + client._transport.delete_expanded_data_set ] = mock_rpc request = {} - client.delete_channel_group(request) + client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_channel_group(request) + client.delete_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -42616,7 +42515,7 @@ def test_delete_channel_group_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_channel_group_empty_call_async(): +async def test_delete_expanded_data_set_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -42626,18 +42525,18 @@ async def test_delete_channel_group_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_channel_group() + response = await client.delete_expanded_data_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteChannelGroupRequest() + assert args[0] == analytics_admin.DeleteExpandedDataSetRequest() @pytest.mark.asyncio -async def test_delete_channel_group_async_use_cached_wrapped_rpc( +async def test_delete_expanded_data_set_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -42654,23 +42553,23 @@ async def test_delete_channel_group_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_channel_group + client._client._transport.delete_expanded_data_set in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_channel_group + client._client._transport.delete_expanded_data_set ] = mock_object request = {} - await client.delete_channel_group(request) + await client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_channel_group(request) + await client.delete_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -42678,9 +42577,9 @@ async def test_delete_channel_group_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_channel_group_async( +async def test_delete_expanded_data_set_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteChannelGroupRequest, + request_type=analytics_admin.DeleteExpandedDataSetRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -42693,16 +42592,16 @@ async def test_delete_channel_group_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_channel_group(request) + response = await client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteChannelGroupRequest() + request = analytics_admin.DeleteExpandedDataSetRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -42710,27 +42609,27 @@ async def test_delete_channel_group_async( @pytest.mark.asyncio -async def test_delete_channel_group_async_from_dict(): - await test_delete_channel_group_async(request_type=dict) +async def test_delete_expanded_data_set_async_from_dict(): + await test_delete_expanded_data_set_async(request_type=dict) -def test_delete_channel_group_field_headers(): +def test_delete_expanded_data_set_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteChannelGroupRequest() + request = analytics_admin.DeleteExpandedDataSetRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: call.return_value = None - client.delete_channel_group(request) + client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -42746,23 +42645,23 @@ def test_delete_channel_group_field_headers(): @pytest.mark.asyncio -async def test_delete_channel_group_field_headers_async(): +async def test_delete_expanded_data_set_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteChannelGroupRequest() + request = analytics_admin.DeleteExpandedDataSetRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_channel_group(request) + await client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -42777,20 +42676,20 @@ async def test_delete_channel_group_field_headers_async(): ) in kw["metadata"] -def test_delete_channel_group_flattened(): +def test_delete_expanded_data_set_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_channel_group( + client.delete_expanded_data_set( name="name_value", ) @@ -42803,7 +42702,7 @@ def test_delete_channel_group_flattened(): assert arg == mock_val -def test_delete_channel_group_flattened_error(): +def test_delete_expanded_data_set_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -42811,21 +42710,21 @@ def test_delete_channel_group_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_channel_group( - analytics_admin.DeleteChannelGroupRequest(), + client.delete_expanded_data_set( + analytics_admin.DeleteExpandedDataSetRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_channel_group_flattened_async(): +async def test_delete_expanded_data_set_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_channel_group), "__call__" + type(client.transport.delete_expanded_data_set), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -42833,7 +42732,7 @@ async def test_delete_channel_group_flattened_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_channel_group( + response = await client.delete_expanded_data_set( name="name_value", ) @@ -42847,7 +42746,7 @@ async def test_delete_channel_group_flattened_async(): @pytest.mark.asyncio -async def test_delete_channel_group_flattened_error_async(): +async def test_delete_expanded_data_set_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -42855,8 +42754,8 @@ async def test_delete_channel_group_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_channel_group( - analytics_admin.DeleteChannelGroupRequest(), + await client.delete_expanded_data_set( + analytics_admin.DeleteExpandedDataSetRequest(), name="name_value", ) @@ -42864,11 +42763,11 @@ async def test_delete_channel_group_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, + analytics_admin.GetChannelGroupRequest, dict, ], ) -def test_set_automated_ga4_configuration_opt_out(request_type, transport: str = "grpc"): +def test_get_channel_group(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -42880,25 +42779,34 @@ def test_set_automated_ga4_configuration_opt_out(request_type, transport: str = # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() - response = client.set_automated_ga4_configuration_opt_out(request) + call.return_value = channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, + ) + response = client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + request = analytics_admin.GetChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse - ) + assert isinstance(response, channel_group.ChannelGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True -def test_set_automated_ga4_configuration_opt_out_empty_call(): +def test_get_channel_group_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -42908,18 +42816,18 @@ def test_set_automated_ga4_configuration_opt_out_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.set_automated_ga4_configuration_opt_out() + client.get_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + assert args[0] == analytics_admin.GetChannelGroupRequest() -def test_set_automated_ga4_configuration_opt_out_non_empty_request_with_auto_populated_field(): +def test_get_channel_group_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -42930,26 +42838,26 @@ def test_set_automated_ga4_configuration_opt_out_non_empty_request_with_auto_pop # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest( - property="property_value", + request = analytics_admin.GetChannelGroupRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.set_automated_ga4_configuration_opt_out(request=request) + client.get_channel_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest( - property="property_value", + assert args[0] == analytics_admin.GetChannelGroupRequest( + name="name_value", ) -def test_set_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): +def test_get_channel_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -42963,10 +42871,7 @@ def test_set_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.set_automated_ga4_configuration_opt_out - in client._transport._wrapped_methods - ) + assert client._transport.get_channel_group in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -42974,15 +42879,15 @@ def test_set_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.set_automated_ga4_configuration_opt_out + client._transport.get_channel_group ] = mock_rpc request = {} - client.set_automated_ga4_configuration_opt_out(request) + client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_automated_ga4_configuration_opt_out(request) + client.get_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -42990,7 +42895,7 @@ def test_set_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_set_automated_ga4_configuration_opt_out_empty_call_async(): +async def test_get_channel_group_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -43000,20 +42905,26 @@ async def test_set_automated_ga4_configuration_opt_out_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, + ) ) - response = await client.set_automated_ga4_configuration_opt_out() + response = await client.get_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + assert args[0] == analytics_admin.GetChannelGroupRequest() @pytest.mark.asyncio -async def test_set_automated_ga4_configuration_opt_out_async_use_cached_wrapped_rpc( +async def test_get_channel_group_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -43030,23 +42941,23 @@ async def test_set_automated_ga4_configuration_opt_out_async_use_cached_wrapped_ # Ensure method has been cached assert ( - client._client._transport.set_automated_ga4_configuration_opt_out + client._client._transport.get_channel_group in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.set_automated_ga4_configuration_opt_out + client._client._transport.get_channel_group ] = mock_object request = {} - await client.set_automated_ga4_configuration_opt_out(request) + await client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.set_automated_ga4_configuration_opt_out(request) + await client.get_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -43054,9 +42965,8 @@ async def test_set_automated_ga4_configuration_opt_out_async_use_cached_wrapped_ @pytest.mark.asyncio -async def test_set_automated_ga4_configuration_opt_out_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, +async def test_get_channel_group_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetChannelGroupRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -43069,284 +42979,199 @@ async def test_set_automated_ga4_configuration_opt_out_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, + ) ) - response = await client.set_automated_ga4_configuration_opt_out(request) + response = await client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + request = analytics_admin.GetChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse - ) + assert isinstance(response, channel_group.ChannelGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True @pytest.mark.asyncio -async def test_set_automated_ga4_configuration_opt_out_async_from_dict(): - await test_set_automated_ga4_configuration_opt_out_async(request_type=dict) +async def test_get_channel_group_async_from_dict(): + await test_get_channel_group_async(request_type=dict) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, - dict, - ], -) -def test_fetch_automated_ga4_configuration_opt_out( - request_type, transport: str = "grpc" -): +def test_get_channel_group_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetChannelGroupRequest() + + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = ( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( - opt_out=True, - ) - ) - response = client.fetch_automated_ga4_configuration_opt_out(request) + call.return_value = channel_group.ChannelGroup() + client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() assert args[0] == request - # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse - ) - assert response.opt_out is True + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_fetch_automated_ga4_configuration_opt_out_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_get_channel_group_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.fetch_automated_ga4_configuration_opt_out() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() - - -def test_fetch_automated_ga4_configuration_opt_out_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetChannelGroupRequest() - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( - property="property_value", - ) + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.fetch_automated_ga4_configuration_opt_out(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( - property="property_value", - ) - - -def test_fetch_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.fetch_automated_ga4_configuration_opt_out - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + channel_group.ChannelGroup() ) - client._transport._wrapped_methods[ - client._transport.fetch_automated_ga4_configuration_opt_out - ] = mock_rpc - request = {} - client.fetch_automated_ga4_configuration_opt_out(request) + await client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_automated_ga4_configuration_opt_out(request) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -@pytest.mark.asyncio -async def test_fetch_automated_ga4_configuration_opt_out_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceAsyncClient( +def test_get_channel_group_flattened(): + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( - opt_out=True, - ) + call.return_value = channel_group.ChannelGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_channel_group( + name="name_value", ) - response = await client.fetch_automated_ga4_configuration_opt_out() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -@pytest.mark.asyncio -async def test_fetch_automated_ga4_configuration_opt_out_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +def test_get_channel_group_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - # Ensure method has been cached - assert ( - client._client._transport.fetch_automated_ga4_configuration_opt_out - in client._client._transport._wrapped_methods + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_channel_group( + analytics_admin.GetChannelGroupRequest(), + name="name_value", ) - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[ - client._client._transport.fetch_automated_ga4_configuration_opt_out - ] = mock_object - - request = {} - await client.fetch_automated_ga4_configuration_opt_out(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.fetch_automated_ga4_configuration_opt_out(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - @pytest.mark.asyncio -async def test_fetch_automated_ga4_configuration_opt_out_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, -): +async def test_get_channel_group_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" + type(client.transport.get_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. + call.return_value = channel_group.ChannelGroup() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( - opt_out=True, - ) + channel_group.ChannelGroup() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_channel_group( + name="name_value", ) - response = await client.fetch_automated_ga4_configuration_opt_out(request) - # Establish that the underlying gRPC stub method was called. + # Establish that the underlying call was made with the expected + # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse - ) - assert response.opt_out is True + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_automated_ga4_configuration_opt_out_async_from_dict(): - await test_fetch_automated_ga4_configuration_opt_out_async(request_type=dict) +async def test_get_channel_group_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_channel_group( + analytics_admin.GetChannelGroupRequest(), + name="name_value", + ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetBigQueryLinkRequest, + analytics_admin.ListChannelGroupsRequest, dict, ], ) -def test_get_big_query_link(request_type, transport: str = "grpc"): +def test_list_channel_groups(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -43358,40 +43183,26 @@ def test_get_big_query_link(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.BigQueryLink( - name="name_value", - project="project_value", - daily_export_enabled=True, - streaming_export_enabled=True, - fresh_daily_export_enabled=True, - include_advertising_id=True, - export_streams=["export_streams_value"], - excluded_events=["excluded_events_value"], + call.return_value = analytics_admin.ListChannelGroupsResponse( + next_page_token="next_page_token_value", ) - response = client.get_big_query_link(request) + response = client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetBigQueryLinkRequest() + request = analytics_admin.ListChannelGroupsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.BigQueryLink) - assert response.name == "name_value" - assert response.project == "project_value" - assert response.daily_export_enabled is True - assert response.streaming_export_enabled is True - assert response.fresh_daily_export_enabled is True - assert response.include_advertising_id is True - assert response.export_streams == ["export_streams_value"] - assert response.excluded_events == ["excluded_events_value"] + assert isinstance(response, pagers.ListChannelGroupsPager) + assert response.next_page_token == "next_page_token_value" -def test_get_big_query_link_empty_call(): +def test_list_channel_groups_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -43401,18 +43212,18 @@ def test_get_big_query_link_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_big_query_link() + client.list_channel_groups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetBigQueryLinkRequest() + assert args[0] == analytics_admin.ListChannelGroupsRequest() -def test_get_big_query_link_non_empty_request_with_auto_populated_field(): +def test_list_channel_groups_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -43423,26 +43234,28 @@ def test_get_big_query_link_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetBigQueryLinkRequest( - name="name_value", + request = analytics_admin.ListChannelGroupsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_big_query_link(request=request) + client.list_channel_groups(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetBigQueryLinkRequest( - name="name_value", + assert args[0] == analytics_admin.ListChannelGroupsRequest( + parent="parent_value", + page_token="page_token_value", ) -def test_get_big_query_link_use_cached_wrapped_rpc(): +def test_list_channel_groups_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -43457,7 +43270,7 @@ def test_get_big_query_link_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_big_query_link in client._transport._wrapped_methods + client._transport.list_channel_groups in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -43466,15 +43279,15 @@ def test_get_big_query_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_big_query_link + client._transport.list_channel_groups ] = mock_rpc request = {} - client.get_big_query_link(request) + client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_big_query_link(request) + client.list_channel_groups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -43482,7 +43295,7 @@ def test_get_big_query_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_big_query_link_empty_call_async(): +async def test_list_channel_groups_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -43492,29 +43305,22 @@ async def test_get_big_query_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.BigQueryLink( - name="name_value", - project="project_value", - daily_export_enabled=True, - streaming_export_enabled=True, - fresh_daily_export_enabled=True, - include_advertising_id=True, - export_streams=["export_streams_value"], - excluded_events=["excluded_events_value"], + analytics_admin.ListChannelGroupsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.get_big_query_link() + response = await client.list_channel_groups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetBigQueryLinkRequest() + assert args[0] == analytics_admin.ListChannelGroupsRequest() @pytest.mark.asyncio -async def test_get_big_query_link_async_use_cached_wrapped_rpc( +async def test_list_channel_groups_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -43531,23 +43337,23 @@ async def test_get_big_query_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_big_query_link + client._client._transport.list_channel_groups in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_big_query_link + client._client._transport.list_channel_groups ] = mock_object request = {} - await client.get_big_query_link(request) + await client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_big_query_link(request) + await client.list_channel_groups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -43555,8 +43361,9 @@ async def test_get_big_query_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_big_query_link_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.GetBigQueryLinkRequest +async def test_list_channel_groups_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.ListChannelGroupsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -43569,63 +43376,49 @@ async def test_get_big_query_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.BigQueryLink( - name="name_value", - project="project_value", - daily_export_enabled=True, - streaming_export_enabled=True, - fresh_daily_export_enabled=True, - include_advertising_id=True, - export_streams=["export_streams_value"], - excluded_events=["excluded_events_value"], + analytics_admin.ListChannelGroupsResponse( + next_page_token="next_page_token_value", ) ) - response = await client.get_big_query_link(request) + response = await client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetBigQueryLinkRequest() + request = analytics_admin.ListChannelGroupsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.BigQueryLink) - assert response.name == "name_value" - assert response.project == "project_value" - assert response.daily_export_enabled is True - assert response.streaming_export_enabled is True - assert response.fresh_daily_export_enabled is True - assert response.include_advertising_id is True - assert response.export_streams == ["export_streams_value"] - assert response.excluded_events == ["excluded_events_value"] + assert isinstance(response, pagers.ListChannelGroupsAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_get_big_query_link_async_from_dict(): - await test_get_big_query_link_async(request_type=dict) +async def test_list_channel_groups_async_from_dict(): + await test_list_channel_groups_async(request_type=dict) -def test_get_big_query_link_field_headers(): +def test_list_channel_groups_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetBigQueryLinkRequest() + request = analytics_admin.ListChannelGroupsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: - call.return_value = resources.BigQueryLink() - client.get_big_query_link(request) + call.return_value = analytics_admin.ListChannelGroupsResponse() + client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -43636,30 +43429,30 @@ def test_get_big_query_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_big_query_link_field_headers_async(): +async def test_list_channel_groups_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetBigQueryLinkRequest() + request = analytics_admin.ListChannelGroupsRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.BigQueryLink() + analytics_admin.ListChannelGroupsResponse() ) - await client.get_big_query_link(request) + await client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -43670,37 +43463,37 @@ async def test_get_big_query_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_big_query_link_flattened(): +def test_list_channel_groups_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.BigQueryLink() + call.return_value = analytics_admin.ListChannelGroupsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_big_query_link( - name="name_value", + client.list_channel_groups( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_big_query_link_flattened_error(): +def test_list_channel_groups_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -43708,45 +43501,45 @@ def test_get_big_query_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_big_query_link( - analytics_admin.GetBigQueryLinkRequest(), - name="name_value", + client.list_channel_groups( + analytics_admin.ListChannelGroupsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_big_query_link_flattened_async(): +async def test_list_channel_groups_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_big_query_link), "__call__" + type(client.transport.list_channel_groups), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.BigQueryLink() + call.return_value = analytics_admin.ListChannelGroupsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.BigQueryLink() + analytics_admin.ListChannelGroupsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_big_query_link( - name="name_value", + response = await client.list_channel_groups( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_big_query_link_flattened_error_async(): +async def test_list_channel_groups_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -43754,20 +43547,222 @@ async def test_get_big_query_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_big_query_link( - analytics_admin.GetBigQueryLinkRequest(), - name="name_value", + await client.list_channel_groups( + analytics_admin.ListChannelGroupsRequest(), + parent="parent_value", + ) + + +def test_list_channel_groups_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token="abc", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token="def", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token="ghi", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_channel_groups(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel_group.ChannelGroup) for i in results) + + +def test_list_channel_groups_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token="abc", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token="def", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token="ghi", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_channel_groups(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_channel_groups_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token="abc", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token="def", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token="ghi", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_channel_groups( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, channel_group.ChannelGroup) for i in responses) + + +@pytest.mark.asyncio +async def test_list_channel_groups_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token="abc", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token="def", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token="ghi", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_channel_groups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListBigQueryLinksRequest, + analytics_admin.CreateChannelGroupRequest, dict, ], ) -def test_list_big_query_links(request_type, transport: str = "grpc"): +def test_create_channel_group(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -43779,26 +43774,34 @@ def test_list_big_query_links(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListBigQueryLinksResponse( - next_page_token="next_page_token_value", + call.return_value = gaa_channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) - response = client.list_big_query_links(request) + response = client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListBigQueryLinksRequest() + request = analytics_admin.CreateChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryLinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True -def test_list_big_query_links_empty_call(): +def test_create_channel_group_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -43808,18 +43811,18 @@ def test_list_big_query_links_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_big_query_links() + client.create_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListBigQueryLinksRequest() + assert args[0] == analytics_admin.CreateChannelGroupRequest() -def test_list_big_query_links_non_empty_request_with_auto_populated_field(): +def test_create_channel_group_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -43830,28 +43833,26 @@ def test_list_big_query_links_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListBigQueryLinksRequest( + request = analytics_admin.CreateChannelGroupRequest( parent="parent_value", - page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_big_query_links(request=request) + client.create_channel_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListBigQueryLinksRequest( + assert args[0] == analytics_admin.CreateChannelGroupRequest( parent="parent_value", - page_token="page_token_value", ) -def test_list_big_query_links_use_cached_wrapped_rpc(): +def test_create_channel_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -43866,7 +43867,7 @@ def test_list_big_query_links_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_big_query_links in client._transport._wrapped_methods + client._transport.create_channel_group in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -43875,15 +43876,15 @@ def test_list_big_query_links_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_big_query_links + client._transport.create_channel_group ] = mock_rpc request = {} - client.list_big_query_links(request) + client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_big_query_links(request) + client.create_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -43891,7 +43892,7 @@ def test_list_big_query_links_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_big_query_links_empty_call_async(): +async def test_create_channel_group_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -43901,22 +43902,26 @@ async def test_list_big_query_links_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListBigQueryLinksResponse( - next_page_token="next_page_token_value", + gaa_channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) ) - response = await client.list_big_query_links() + response = await client.create_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListBigQueryLinksRequest() + assert args[0] == analytics_admin.CreateChannelGroupRequest() @pytest.mark.asyncio -async def test_list_big_query_links_async_use_cached_wrapped_rpc( +async def test_create_channel_group_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -43933,23 +43938,23 @@ async def test_list_big_query_links_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_big_query_links + client._client._transport.create_channel_group in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_big_query_links + client._client._transport.create_channel_group ] = mock_object request = {} - await client.list_big_query_links(request) + await client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_big_query_links(request) + await client.create_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -43957,9 +43962,9 @@ async def test_list_big_query_links_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_big_query_links_async( +async def test_create_channel_group_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListBigQueryLinksRequest, + request_type=analytics_admin.CreateChannelGroupRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -43972,49 +43977,57 @@ async def test_list_big_query_links_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListBigQueryLinksResponse( - next_page_token="next_page_token_value", + gaa_channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) ) - response = await client.list_big_query_links(request) + response = await client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListBigQueryLinksRequest() + request = analytics_admin.CreateChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryLinksAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True @pytest.mark.asyncio -async def test_list_big_query_links_async_from_dict(): - await test_list_big_query_links_async(request_type=dict) +async def test_create_channel_group_async_from_dict(): + await test_create_channel_group_async(request_type=dict) -def test_list_big_query_links_field_headers(): +def test_create_channel_group_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListBigQueryLinksRequest() + request = analytics_admin.CreateChannelGroupRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: - call.return_value = analytics_admin.ListBigQueryLinksResponse() - client.list_big_query_links(request) + call.return_value = gaa_channel_group.ChannelGroup() + client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -44030,25 +44043,25 @@ def test_list_big_query_links_field_headers(): @pytest.mark.asyncio -async def test_list_big_query_links_field_headers_async(): +async def test_create_channel_group_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListBigQueryLinksRequest() + request = analytics_admin.CreateChannelGroupRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListBigQueryLinksResponse() + gaa_channel_group.ChannelGroup() ) - await client.list_big_query_links(request) + await client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -44063,21 +44076,22 @@ async def test_list_big_query_links_field_headers_async(): ) in kw["metadata"] -def test_list_big_query_links_flattened(): +def test_create_channel_group_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListBigQueryLinksResponse() + call.return_value = gaa_channel_group.ChannelGroup() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_big_query_links( + client.create_channel_group( parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -44087,9 +44101,12 @@ def test_list_big_query_links_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].channel_group + mock_val = gaa_channel_group.ChannelGroup(name="name_value") + assert arg == mock_val -def test_list_big_query_links_flattened_error(): +def test_create_channel_group_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -44097,32 +44114,34 @@ def test_list_big_query_links_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_big_query_links( - analytics_admin.ListBigQueryLinksRequest(), + client.create_channel_group( + analytics_admin.CreateChannelGroupRequest(), parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) @pytest.mark.asyncio -async def test_list_big_query_links_flattened_async(): +async def test_create_channel_group_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.create_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListBigQueryLinksResponse() + call.return_value = gaa_channel_group.ChannelGroup() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListBigQueryLinksResponse() + gaa_channel_group.ChannelGroup() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_big_query_links( + response = await client.create_channel_group( parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -44132,10 +44151,13 @@ async def test_list_big_query_links_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].channel_group + mock_val = gaa_channel_group.ChannelGroup(name="name_value") + assert arg == mock_val @pytest.mark.asyncio -async def test_list_big_query_links_flattened_error_async(): +async def test_create_channel_group_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -44143,273 +44165,60 @@ async def test_list_big_query_links_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_big_query_links( - analytics_admin.ListBigQueryLinksRequest(), + await client.create_channel_group( + analytics_admin.CreateChannelGroupRequest(), parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) -def test_list_big_query_links_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateChannelGroupRequest, + dict, + ], +) +def test_update_channel_group(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[], - next_page_token="def", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) - pager = client.list_big_query_links(request={}, retry=retry, timeout=timeout) + response = client.update_channel_group(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.BigQueryLink) for i in results) - - -def test_list_big_query_links_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_links), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[], - next_page_token="def", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - ), - RuntimeError, - ) - pages = list(client.list_big_query_links(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_big_query_links_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[], - next_page_token="def", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_big_query_links( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.BigQueryLink) for i in responses) - - -@pytest.mark.asyncio -async def test_list_big_query_links_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_big_query_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[], - next_page_token="def", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_big_query_links(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetEnhancedMeasurementSettingsRequest, - dict, - ], -) -def test_get_enhanced_measurement_settings(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.EnhancedMeasurementSettings( - name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", - ) - response = client.get_enhanced_measurement_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.GetEnhancedMeasurementSettingsRequest() - assert args[0] == request + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateChannelGroupRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.EnhancedMeasurementSettings) + assert isinstance(response, gaa_channel_group.ChannelGroup) assert response.name == "name_value" - assert response.stream_enabled is True - assert response.scrolls_enabled is True - assert response.outbound_clicks_enabled is True - assert response.site_search_enabled is True - assert response.video_engagement_enabled is True - assert response.file_downloads_enabled is True - assert response.page_changes_enabled is True - assert response.form_interactions_enabled is True - assert response.search_query_parameter == "search_query_parameter_value" - assert response.uri_query_parameter == "uri_query_parameter_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True -def test_get_enhanced_measurement_settings_empty_call(): +def test_update_channel_group_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -44419,18 +44228,18 @@ def test_get_enhanced_measurement_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_enhanced_measurement_settings() + client.update_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest() + assert args[0] == analytics_admin.UpdateChannelGroupRequest() -def test_get_enhanced_measurement_settings_non_empty_request_with_auto_populated_field(): +def test_update_channel_group_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -44441,26 +44250,22 @@ def test_get_enhanced_measurement_settings_non_empty_request_with_auto_populated # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetEnhancedMeasurementSettingsRequest( - name="name_value", - ) + request = analytics_admin.UpdateChannelGroupRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_enhanced_measurement_settings(request=request) + client.update_channel_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest( - name="name_value", - ) + assert args[0] == analytics_admin.UpdateChannelGroupRequest() -def test_get_enhanced_measurement_settings_use_cached_wrapped_rpc(): +def test_update_channel_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -44475,8 +44280,7 @@ def test_get_enhanced_measurement_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_enhanced_measurement_settings - in client._transport._wrapped_methods + client._transport.update_channel_group in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -44485,15 +44289,15 @@ def test_get_enhanced_measurement_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_enhanced_measurement_settings + client._transport.update_channel_group ] = mock_rpc request = {} - client.get_enhanced_measurement_settings(request) + client.update_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_enhanced_measurement_settings(request) + client.update_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -44501,7 +44305,7 @@ def test_get_enhanced_measurement_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_empty_call_async(): +async def test_update_channel_group_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -44511,32 +44315,26 @@ async def test_get_enhanced_measurement_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings( + gaa_channel_group.ChannelGroup( name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) ) - response = await client.get_enhanced_measurement_settings() + response = await client.update_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest() + assert args[0] == analytics_admin.UpdateChannelGroupRequest() @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_async_use_cached_wrapped_rpc( +async def test_update_channel_group_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -44553,23 +44351,23 @@ async def test_get_enhanced_measurement_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_enhanced_measurement_settings + client._client._transport.update_channel_group in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_enhanced_measurement_settings + client._client._transport.update_channel_group ] = mock_object request = {} - await client.get_enhanced_measurement_settings(request) + await client.update_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_enhanced_measurement_settings(request) + await client.update_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -44577,9 +44375,9 @@ async def test_get_enhanced_measurement_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_async( +async def test_update_channel_group_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest, + request_type=analytics_admin.UpdateChannelGroupRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -44592,69 +44390,57 @@ async def test_get_enhanced_measurement_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings( + gaa_channel_group.ChannelGroup( name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) ) - response = await client.get_enhanced_measurement_settings(request) + response = await client.update_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + request = analytics_admin.UpdateChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.EnhancedMeasurementSettings) + assert isinstance(response, gaa_channel_group.ChannelGroup) assert response.name == "name_value" - assert response.stream_enabled is True - assert response.scrolls_enabled is True - assert response.outbound_clicks_enabled is True - assert response.site_search_enabled is True - assert response.video_engagement_enabled is True - assert response.file_downloads_enabled is True - assert response.page_changes_enabled is True - assert response.form_interactions_enabled is True - assert response.search_query_parameter == "search_query_parameter_value" - assert response.uri_query_parameter == "uri_query_parameter_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_async_from_dict(): - await test_get_enhanced_measurement_settings_async(request_type=dict) +async def test_update_channel_group_async_from_dict(): + await test_update_channel_group_async(request_type=dict) -def test_get_enhanced_measurement_settings_field_headers(): +def test_update_channel_group_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + request = analytics_admin.UpdateChannelGroupRequest() - request.name = "name_value" + request.channel_group.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: - call.return_value = resources.EnhancedMeasurementSettings() - client.get_enhanced_measurement_settings(request) + call.return_value = gaa_channel_group.ChannelGroup() + client.update_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -44665,30 +44451,30 @@ def test_get_enhanced_measurement_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "channel_group.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_field_headers_async(): +async def test_update_channel_group_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + request = analytics_admin.UpdateChannelGroupRequest() - request.name = "name_value" + request.channel_group.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings() + gaa_channel_group.ChannelGroup() ) - await client.get_enhanced_measurement_settings(request) + await client.update_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -44699,37 +44485,41 @@ async def test_get_enhanced_measurement_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "channel_group.name=name_value", ) in kw["metadata"] -def test_get_enhanced_measurement_settings_flattened(): +def test_update_channel_group_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.EnhancedMeasurementSettings() + call.return_value = gaa_channel_group.ChannelGroup() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_enhanced_measurement_settings( - name="name_value", + client.update_channel_group( + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].channel_group + mock_val = gaa_channel_group.ChannelGroup(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_get_enhanced_measurement_settings_flattened_error(): +def test_update_channel_group_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -44737,45 +44527,50 @@ def test_get_enhanced_measurement_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_enhanced_measurement_settings( - analytics_admin.GetEnhancedMeasurementSettingsRequest(), - name="name_value", + client.update_channel_group( + analytics_admin.UpdateChannelGroupRequest(), + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_flattened_async(): +async def test_update_channel_group_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_enhanced_measurement_settings), "__call__" + type(client.transport.update_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.EnhancedMeasurementSettings() + call.return_value = gaa_channel_group.ChannelGroup() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings() + gaa_channel_group.ChannelGroup() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_enhanced_measurement_settings( - name="name_value", + response = await client.update_channel_group( + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].channel_group + mock_val = gaa_channel_group.ChannelGroup(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_get_enhanced_measurement_settings_flattened_error_async(): +async def test_update_channel_group_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -44783,20 +44578,21 @@ async def test_get_enhanced_measurement_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_enhanced_measurement_settings( - analytics_admin.GetEnhancedMeasurementSettingsRequest(), - name="name_value", + await client.update_channel_group( + analytics_admin.UpdateChannelGroupRequest(), + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateEnhancedMeasurementSettingsRequest, + analytics_admin.DeleteChannelGroupRequest, dict, ], ) -def test_update_enhanced_measurement_settings(request_type, transport: str = "grpc"): +def test_delete_channel_group(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -44808,46 +44604,23 @@ def test_update_enhanced_measurement_settings(request_type, transport: str = "gr # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.EnhancedMeasurementSettings( - name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", - ) - response = client.update_enhanced_measurement_settings(request) + call.return_value = None + response = client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + request = analytics_admin.DeleteChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.EnhancedMeasurementSettings) - assert response.name == "name_value" - assert response.stream_enabled is True - assert response.scrolls_enabled is True - assert response.outbound_clicks_enabled is True - assert response.site_search_enabled is True - assert response.video_engagement_enabled is True - assert response.file_downloads_enabled is True - assert response.page_changes_enabled is True - assert response.form_interactions_enabled is True - assert response.search_query_parameter == "search_query_parameter_value" - assert response.uri_query_parameter == "uri_query_parameter_value" + assert response is None -def test_update_enhanced_measurement_settings_empty_call(): +def test_delete_channel_group_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -44857,18 +44630,18 @@ def test_update_enhanced_measurement_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_enhanced_measurement_settings() + client.delete_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + assert args[0] == analytics_admin.DeleteChannelGroupRequest() -def test_update_enhanced_measurement_settings_non_empty_request_with_auto_populated_field(): +def test_delete_channel_group_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -44879,22 +44652,26 @@ def test_update_enhanced_measurement_settings_non_empty_request_with_auto_popula # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + request = analytics_admin.DeleteChannelGroupRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_enhanced_measurement_settings(request=request) + client.delete_channel_group(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + assert args[0] == analytics_admin.DeleteChannelGroupRequest( + name="name_value", + ) -def test_update_enhanced_measurement_settings_use_cached_wrapped_rpc(): +def test_delete_channel_group_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -44909,8 +44686,7 @@ def test_update_enhanced_measurement_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_enhanced_measurement_settings - in client._transport._wrapped_methods + client._transport.delete_channel_group in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -44919,15 +44695,15 @@ def test_update_enhanced_measurement_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_enhanced_measurement_settings + client._transport.delete_channel_group ] = mock_rpc request = {} - client.update_enhanced_measurement_settings(request) + client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_enhanced_measurement_settings(request) + client.delete_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -44935,7 +44711,7 @@ def test_update_enhanced_measurement_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_empty_call_async(): +async def test_delete_channel_group_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -44945,32 +44721,18 @@ async def test_update_enhanced_measurement_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings( - name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", - ) - ) - response = await client.update_enhanced_measurement_settings() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_channel_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + assert args[0] == analytics_admin.DeleteChannelGroupRequest() @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_async_use_cached_wrapped_rpc( +async def test_delete_channel_group_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -44987,23 +44749,23 @@ async def test_update_enhanced_measurement_settings_async_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._client._transport.update_enhanced_measurement_settings + client._client._transport.delete_channel_group in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_enhanced_measurement_settings + client._client._transport.delete_channel_group ] = mock_object request = {} - await client.update_enhanced_measurement_settings(request) + await client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_enhanced_measurement_settings(request) + await client.delete_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45011,9 +44773,9 @@ async def test_update_enhanced_measurement_settings_async_use_cached_wrapped_rpc @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_async( +async def test_delete_channel_group_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest, + request_type=analytics_admin.DeleteChannelGroupRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -45026,69 +44788,44 @@ async def test_update_enhanced_measurement_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings( - name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", - ) - ) - response = await client.update_enhanced_measurement_settings(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + request = analytics_admin.DeleteChannelGroupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.EnhancedMeasurementSettings) - assert response.name == "name_value" - assert response.stream_enabled is True - assert response.scrolls_enabled is True - assert response.outbound_clicks_enabled is True - assert response.site_search_enabled is True - assert response.video_engagement_enabled is True - assert response.file_downloads_enabled is True - assert response.page_changes_enabled is True - assert response.form_interactions_enabled is True - assert response.search_query_parameter == "search_query_parameter_value" - assert response.uri_query_parameter == "uri_query_parameter_value" + assert response is None @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_async_from_dict(): - await test_update_enhanced_measurement_settings_async(request_type=dict) +async def test_delete_channel_group_async_from_dict(): + await test_delete_channel_group_async(request_type=dict) -def test_update_enhanced_measurement_settings_field_headers(): +def test_delete_channel_group_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + request = analytics_admin.DeleteChannelGroupRequest() - request.enhanced_measurement_settings.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: - call.return_value = resources.EnhancedMeasurementSettings() - client.update_enhanced_measurement_settings(request) + call.return_value = None + client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -45099,30 +44836,28 @@ def test_update_enhanced_measurement_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "enhanced_measurement_settings.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_field_headers_async(): +async def test_delete_channel_group_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + request = analytics_admin.DeleteChannelGroupRequest() - request.enhanced_measurement_settings.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings() - ) - await client.update_enhanced_measurement_settings(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -45133,43 +44868,37 @@ async def test_update_enhanced_measurement_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "enhanced_measurement_settings.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_enhanced_measurement_settings_flattened(): +def test_delete_channel_group_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.EnhancedMeasurementSettings() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_enhanced_measurement_settings( - enhanced_measurement_settings=resources.EnhancedMeasurementSettings( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_channel_group( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].enhanced_measurement_settings - mock_val = resources.EnhancedMeasurementSettings(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_enhanced_measurement_settings_flattened_error(): +def test_delete_channel_group_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -45177,54 +44906,43 @@ def test_update_enhanced_measurement_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_enhanced_measurement_settings( - analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), - enhanced_measurement_settings=resources.EnhancedMeasurementSettings( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_channel_group( + analytics_admin.DeleteChannelGroupRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_flattened_async(): +async def test_delete_channel_group_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_enhanced_measurement_settings), "__call__" + type(client.transport.delete_channel_group), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.EnhancedMeasurementSettings() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.EnhancedMeasurementSettings() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_enhanced_measurement_settings( - enhanced_measurement_settings=resources.EnhancedMeasurementSettings( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.delete_channel_group( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].enhanced_measurement_settings - mock_val = resources.EnhancedMeasurementSettings(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_enhanced_measurement_settings_flattened_error_async(): +async def test_delete_channel_group_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -45232,23 +44950,20 @@ async def test_update_enhanced_measurement_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_enhanced_measurement_settings( - analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), - enhanced_measurement_settings=resources.EnhancedMeasurementSettings( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.delete_channel_group( + analytics_admin.DeleteChannelGroupRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateConnectedSiteTagRequest, + analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict, ], ) -def test_create_connected_site_tag(request_type, transport: str = "grpc"): +def test_set_automated_ga4_configuration_opt_out(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -45260,23 +44975,25 @@ def test_create_connected_site_tag(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_connected_site_tag), "__call__" + type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.CreateConnectedSiteTagResponse() - response = client.create_connected_site_tag(request) + call.return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + response = client.set_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateConnectedSiteTagRequest() + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) + assert isinstance( + response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse + ) -def test_create_connected_site_tag_empty_call(): +def test_set_automated_ga4_configuration_opt_out_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -45286,18 +45003,18 @@ def test_create_connected_site_tag_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_connected_site_tag), "__call__" + type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_connected_site_tag() + client.set_automated_ga4_configuration_opt_out() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateConnectedSiteTagRequest() + assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() -def test_create_connected_site_tag_non_empty_request_with_auto_populated_field(): +def test_set_automated_ga4_configuration_opt_out_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -45308,26 +45025,26 @@ def test_create_connected_site_tag_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateConnectedSiteTagRequest( + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest( property="property_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_connected_site_tag), "__call__" + type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_connected_site_tag(request=request) + client.set_automated_ga4_configuration_opt_out(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateConnectedSiteTagRequest( + assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest( property="property_value", ) -def test_create_connected_site_tag_use_cached_wrapped_rpc(): +def test_set_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -45342,7 +45059,7 @@ def test_create_connected_site_tag_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_connected_site_tag + client._transport.set_automated_ga4_configuration_opt_out in client._transport._wrapped_methods ) @@ -45352,15 +45069,15 @@ def test_create_connected_site_tag_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_connected_site_tag + client._transport.set_automated_ga4_configuration_opt_out ] = mock_rpc request = {} - client.create_connected_site_tag(request) + client.set_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_connected_site_tag(request) + client.set_automated_ga4_configuration_opt_out(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45368,7 +45085,7 @@ def test_create_connected_site_tag_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_connected_site_tag_empty_call_async(): +async def test_set_automated_ga4_configuration_opt_out_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -45378,20 +45095,20 @@ async def test_create_connected_site_tag_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_connected_site_tag), "__call__" + type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.CreateConnectedSiteTagResponse() + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() ) - response = await client.create_connected_site_tag() + response = await client.set_automated_ga4_configuration_opt_out() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateConnectedSiteTagRequest() + assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() @pytest.mark.asyncio -async def test_create_connected_site_tag_async_use_cached_wrapped_rpc( +async def test_set_automated_ga4_configuration_opt_out_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -45408,23 +45125,23 @@ async def test_create_connected_site_tag_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_connected_site_tag + client._client._transport.set_automated_ga4_configuration_opt_out in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_connected_site_tag + client._client._transport.set_automated_ga4_configuration_opt_out ] = mock_object request = {} - await client.create_connected_site_tag(request) + await client.set_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_connected_site_tag(request) + await client.set_automated_ga4_configuration_opt_out(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45432,9 +45149,9 @@ async def test_create_connected_site_tag_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_connected_site_tag_async( +async def test_set_automated_ga4_configuration_opt_out_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateConnectedSiteTagRequest, + request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -45447,37 +45164,41 @@ async def test_create_connected_site_tag_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_connected_site_tag), "__call__" + type(client.transport.set_automated_ga4_configuration_opt_out), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.CreateConnectedSiteTagResponse() + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() ) - response = await client.create_connected_site_tag(request) + response = await client.set_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateConnectedSiteTagRequest() + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) + assert isinstance( + response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse + ) @pytest.mark.asyncio -async def test_create_connected_site_tag_async_from_dict(): - await test_create_connected_site_tag_async(request_type=dict) +async def test_set_automated_ga4_configuration_opt_out_async_from_dict(): + await test_set_automated_ga4_configuration_opt_out_async(request_type=dict) @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteConnectedSiteTagRequest, + analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict, ], ) -def test_delete_connected_site_tag(request_type, transport: str = "grpc"): +def test_fetch_automated_ga4_configuration_opt_out( + request_type, transport: str = "grpc" +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -45489,23 +45210,30 @@ def test_delete_connected_site_tag(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_connected_site_tag), "__call__" + type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_connected_site_tag(request) + call.return_value = ( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + ) + ) + response = client.fetch_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteConnectedSiteTagRequest() + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance( + response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse + ) + assert response.opt_out is True -def test_delete_connected_site_tag_empty_call(): +def test_fetch_automated_ga4_configuration_opt_out_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -45515,18 +45243,18 @@ def test_delete_connected_site_tag_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_connected_site_tag), "__call__" + type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_connected_site_tag() + client.fetch_automated_ga4_configuration_opt_out() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest() + assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() -def test_delete_connected_site_tag_non_empty_request_with_auto_populated_field(): +def test_fetch_automated_ga4_configuration_opt_out_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -45537,28 +45265,26 @@ def test_delete_connected_site_tag_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteConnectedSiteTagRequest( + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( property="property_value", - tag_id="tag_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_connected_site_tag), "__call__" + type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_connected_site_tag(request=request) + client.fetch_automated_ga4_configuration_opt_out(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest( + assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( property="property_value", - tag_id="tag_id_value", ) -def test_delete_connected_site_tag_use_cached_wrapped_rpc(): +def test_fetch_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -45573,7 +45299,7 @@ def test_delete_connected_site_tag_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_connected_site_tag + client._transport.fetch_automated_ga4_configuration_opt_out in client._transport._wrapped_methods ) @@ -45583,15 +45309,15 @@ def test_delete_connected_site_tag_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_connected_site_tag + client._transport.fetch_automated_ga4_configuration_opt_out ] = mock_rpc request = {} - client.delete_connected_site_tag(request) + client.fetch_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_connected_site_tag(request) + client.fetch_automated_ga4_configuration_opt_out(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45599,7 +45325,7 @@ def test_delete_connected_site_tag_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_connected_site_tag_empty_call_async(): +async def test_fetch_automated_ga4_configuration_opt_out_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -45609,18 +45335,22 @@ async def test_delete_connected_site_tag_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_connected_site_tag), "__call__" + type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_connected_site_tag() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + ) + ) + response = await client.fetch_automated_ga4_configuration_opt_out() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest() + assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() @pytest.mark.asyncio -async def test_delete_connected_site_tag_async_use_cached_wrapped_rpc( +async def test_fetch_automated_ga4_configuration_opt_out_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -45637,23 +45367,23 @@ async def test_delete_connected_site_tag_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_connected_site_tag + client._client._transport.fetch_automated_ga4_configuration_opt_out in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_connected_site_tag + client._client._transport.fetch_automated_ga4_configuration_opt_out ] = mock_object request = {} - await client.delete_connected_site_tag(request) + await client.fetch_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_connected_site_tag(request) + await client.fetch_automated_ga4_configuration_opt_out(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45661,9 +45391,9 @@ async def test_delete_connected_site_tag_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_connected_site_tag_async( +async def test_fetch_automated_ga4_configuration_opt_out_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteConnectedSiteTagRequest, + request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -45676,35 +45406,42 @@ async def test_delete_connected_site_tag_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_connected_site_tag), "__call__" + type(client.transport.fetch_automated_ga4_configuration_opt_out), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_connected_site_tag(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + ) + ) + response = await client.fetch_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteConnectedSiteTagRequest() + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance( + response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse + ) + assert response.opt_out is True @pytest.mark.asyncio -async def test_delete_connected_site_tag_async_from_dict(): - await test_delete_connected_site_tag_async(request_type=dict) +async def test_fetch_automated_ga4_configuration_opt_out_async_from_dict(): + await test_fetch_automated_ga4_configuration_opt_out_async(request_type=dict) @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListConnectedSiteTagsRequest, + analytics_admin.CreateBigQueryLinkRequest, dict, ], ) -def test_list_connected_site_tags(request_type, transport: str = "grpc"): +def test_create_big_query_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -45716,23 +45453,42 @@ def test_list_connected_site_tags(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_connected_site_tags), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListConnectedSiteTagsResponse() - response = client.list_connected_site_tags(request) + call.return_value = resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", + ) + response = client.create_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListConnectedSiteTagsRequest() + request = analytics_admin.CreateBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) + assert isinstance(response, resources.BigQueryLink) + assert response.name == "name_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" -def test_list_connected_site_tags_empty_call(): +def test_create_big_query_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -45742,18 +45498,18 @@ def test_list_connected_site_tags_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_connected_site_tags), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_connected_site_tags() + client.create_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListConnectedSiteTagsRequest() + assert args[0] == analytics_admin.CreateBigQueryLinkRequest() -def test_list_connected_site_tags_non_empty_request_with_auto_populated_field(): +def test_create_big_query_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -45764,26 +45520,26 @@ def test_list_connected_site_tags_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListConnectedSiteTagsRequest( - property="property_value", + request = analytics_admin.CreateBigQueryLinkRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_connected_site_tags), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_connected_site_tags(request=request) + client.create_big_query_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListConnectedSiteTagsRequest( - property="property_value", + assert args[0] == analytics_admin.CreateBigQueryLinkRequest( + parent="parent_value", ) -def test_list_connected_site_tags_use_cached_wrapped_rpc(): +def test_create_big_query_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -45798,7 +45554,7 @@ def test_list_connected_site_tags_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_connected_site_tags + client._transport.create_big_query_link in client._transport._wrapped_methods ) @@ -45808,15 +45564,15 @@ def test_list_connected_site_tags_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_connected_site_tags + client._transport.create_big_query_link ] = mock_rpc request = {} - client.list_connected_site_tags(request) + client.create_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_connected_site_tags(request) + client.create_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45824,7 +45580,7 @@ def test_list_connected_site_tags_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_connected_site_tags_empty_call_async(): +async def test_create_big_query_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -45834,20 +45590,30 @@ async def test_list_connected_site_tags_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_connected_site_tags), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListConnectedSiteTagsResponse() + resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", + ) ) - response = await client.list_connected_site_tags() + response = await client.create_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListConnectedSiteTagsRequest() + assert args[0] == analytics_admin.CreateBigQueryLinkRequest() @pytest.mark.asyncio -async def test_list_connected_site_tags_async_use_cached_wrapped_rpc( +async def test_create_big_query_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -45864,23 +45630,23 @@ async def test_list_connected_site_tags_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_connected_site_tags + client._client._transport.create_big_query_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_connected_site_tags + client._client._transport.create_big_query_link ] = mock_object request = {} - await client.list_connected_site_tags(request) + await client.create_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_connected_site_tags(request) + await client.create_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -45888,9 +45654,9 @@ async def test_list_connected_site_tags_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_connected_site_tags_async( +async def test_create_big_query_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListConnectedSiteTagsRequest, + request_type=analytics_admin.CreateBigQueryLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -45903,274 +45669,217 @@ async def test_list_connected_site_tags_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_connected_site_tags), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListConnectedSiteTagsResponse() + resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", + ) ) - response = await client.list_connected_site_tags(request) + response = await client.create_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListConnectedSiteTagsRequest() + request = analytics_admin.CreateBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) + assert isinstance(response, resources.BigQueryLink) + assert response.name == "name_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" @pytest.mark.asyncio -async def test_list_connected_site_tags_async_from_dict(): - await test_list_connected_site_tags_async(request_type=dict) +async def test_create_big_query_link_async_from_dict(): + await test_create_big_query_link_async(request_type=dict) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.FetchConnectedGa4PropertyRequest, - dict, - ], -) -def test_fetch_connected_ga4_property(request_type, transport: str = "grpc"): +def test_create_big_query_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateBigQueryLinkRequest() + + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_connected_ga4_property), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_admin.FetchConnectedGa4PropertyResponse( - property="property_value", - ) - response = client.fetch_connected_ga4_property(request) + call.return_value = resources.BigQueryLink() + client.create_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.FetchConnectedGa4PropertyRequest() assert args[0] == request - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) - assert response.property == "property_value" + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_fetch_connected_ga4_property_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_create_big_query_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateBigQueryLinkRequest() + + request.parent = "parent_value" + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_connected_ga4_property), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.BigQueryLink() ) - client.fetch_connected_ga4_property() - call.assert_called() + await client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest() + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_fetch_connected_ga4_property_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. +def test_create_big_query_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.FetchConnectedGa4PropertyRequest( - property="property_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_connected_ga4_property), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_link( + parent="parent_value", + bigquery_link=resources.BigQueryLink(name="name_value"), ) - client.fetch_connected_ga4_property(request=request) - call.assert_called() + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest( - property="property_value", - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].bigquery_link + mock_val = resources.BigQueryLink(name="name_value") + assert arg == mock_val -def test_fetch_connected_ga4_property_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.fetch_connected_ga4_property - in client._transport._wrapped_methods - ) +def test_create_big_query_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_big_query_link( + analytics_admin.CreateBigQueryLinkRequest(), + parent="parent_value", + bigquery_link=resources.BigQueryLink(name="name_value"), ) - client._transport._wrapped_methods[ - client._transport.fetch_connected_ga4_property - ] = mock_rpc - request = {} - client.fetch_connected_ga4_property(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_connected_ga4_property(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 @pytest.mark.asyncio -async def test_fetch_connected_ga4_property_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +async def test_create_big_query_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_connected_ga4_property), "__call__" + type(client.transport.create_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.FetchConnectedGa4PropertyResponse( - property="property_value", - ) - ) - response = await client.fetch_connected_ga4_property() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest() - + call.return_value = resources.BigQueryLink() -@pytest.mark.asyncio -async def test_fetch_connected_ga4_property_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.BigQueryLink() ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.fetch_connected_ga4_property - in client._client._transport._wrapped_methods + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_link( + parent="parent_value", + bigquery_link=resources.BigQueryLink(name="name_value"), ) - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[ - client._client._transport.fetch_connected_ga4_property - ] = mock_object - - request = {} - await client.fetch_connected_ga4_property(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.fetch_connected_ga4_property(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].bigquery_link + mock_val = resources.BigQueryLink(name="name_value") + assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_connected_ga4_property_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.FetchConnectedGa4PropertyRequest, -): +async def test_create_big_query_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_connected_ga4_property), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.FetchConnectedGa4PropertyResponse( - property="property_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_big_query_link( + analytics_admin.CreateBigQueryLinkRequest(), + parent="parent_value", + bigquery_link=resources.BigQueryLink(name="name_value"), ) - response = await client.fetch_connected_ga4_property(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = analytics_admin.FetchConnectedGa4PropertyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) - assert response.property == "property_value" - - -@pytest.mark.asyncio -async def test_fetch_connected_ga4_property_async_from_dict(): - await test_fetch_connected_ga4_property_async(request_type=dict) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAdSenseLinkRequest, + analytics_admin.GetBigQueryLinkRequest, dict, ], ) -def test_get_ad_sense_link(request_type, transport: str = "grpc"): +def test_get_big_query_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -46182,28 +45891,42 @@ def test_get_ad_sense_link(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AdSenseLink( + call.return_value = resources.BigQueryLink( name="name_value", - ad_client_code="ad_client_code_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) - response = client.get_ad_sense_link(request) + response = client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAdSenseLinkRequest() + request = analytics_admin.GetBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AdSenseLink) + assert isinstance(response, resources.BigQueryLink) assert response.name == "name_value" - assert response.ad_client_code == "ad_client_code_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" -def test_get_ad_sense_link_empty_call(): +def test_get_big_query_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -46213,18 +45936,18 @@ def test_get_ad_sense_link_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_ad_sense_link() + client.get_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAdSenseLinkRequest() + assert args[0] == analytics_admin.GetBigQueryLinkRequest() -def test_get_ad_sense_link_non_empty_request_with_auto_populated_field(): +def test_get_big_query_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -46235,26 +45958,26 @@ def test_get_ad_sense_link_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetAdSenseLinkRequest( + request = analytics_admin.GetBigQueryLinkRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_ad_sense_link(request=request) + client.get_big_query_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAdSenseLinkRequest( + assert args[0] == analytics_admin.GetBigQueryLinkRequest( name="name_value", ) -def test_get_ad_sense_link_use_cached_wrapped_rpc(): +def test_get_big_query_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -46268,7 +45991,9 @@ def test_get_ad_sense_link_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_ad_sense_link in client._transport._wrapped_methods + assert ( + client._transport.get_big_query_link in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -46276,15 +46001,15 @@ def test_get_ad_sense_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_ad_sense_link + client._transport.get_big_query_link ] = mock_rpc request = {} - client.get_ad_sense_link(request) + client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_ad_sense_link(request) + client.get_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -46292,7 +46017,7 @@ def test_get_ad_sense_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_ad_sense_link_empty_call_async(): +async def test_get_big_query_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -46302,23 +46027,30 @@ async def test_get_ad_sense_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink( + resources.BigQueryLink( name="name_value", - ad_client_code="ad_client_code_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) ) - response = await client.get_ad_sense_link() + response = await client.get_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetAdSenseLinkRequest() + assert args[0] == analytics_admin.GetBigQueryLinkRequest() @pytest.mark.asyncio -async def test_get_ad_sense_link_async_use_cached_wrapped_rpc( +async def test_get_big_query_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -46335,23 +46067,23 @@ async def test_get_ad_sense_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_ad_sense_link + client._client._transport.get_big_query_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_ad_sense_link + client._client._transport.get_big_query_link ] = mock_object request = {} - await client.get_ad_sense_link(request) + await client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_ad_sense_link(request) + await client.get_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -46359,8 +46091,8 @@ async def test_get_ad_sense_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_ad_sense_link_async( - transport: str = "grpc_asyncio", request_type=analytics_admin.GetAdSenseLinkRequest +async def test_get_big_query_link_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetBigQueryLinkRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -46373,51 +46105,65 @@ async def test_get_ad_sense_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink( + resources.BigQueryLink( name="name_value", - ad_client_code="ad_client_code_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) ) - response = await client.get_ad_sense_link(request) + response = await client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetAdSenseLinkRequest() + request = analytics_admin.GetBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AdSenseLink) + assert isinstance(response, resources.BigQueryLink) assert response.name == "name_value" - assert response.ad_client_code == "ad_client_code_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" @pytest.mark.asyncio -async def test_get_ad_sense_link_async_from_dict(): - await test_get_ad_sense_link_async(request_type=dict) +async def test_get_big_query_link_async_from_dict(): + await test_get_big_query_link_async(request_type=dict) -def test_get_ad_sense_link_field_headers(): +def test_get_big_query_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAdSenseLinkRequest() + request = analytics_admin.GetBigQueryLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: - call.return_value = resources.AdSenseLink() - client.get_ad_sense_link(request) + call.return_value = resources.BigQueryLink() + client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -46433,25 +46179,25 @@ def test_get_ad_sense_link_field_headers(): @pytest.mark.asyncio -async def test_get_ad_sense_link_field_headers_async(): +async def test_get_big_query_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetAdSenseLinkRequest() + request = analytics_admin.GetBigQueryLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink() + resources.BigQueryLink() ) - await client.get_ad_sense_link(request) + await client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -46466,20 +46212,20 @@ async def test_get_ad_sense_link_field_headers_async(): ) in kw["metadata"] -def test_get_ad_sense_link_flattened(): +def test_get_big_query_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AdSenseLink() + call.return_value = resources.BigQueryLink() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_ad_sense_link( + client.get_big_query_link( name="name_value", ) @@ -46492,7 +46238,7 @@ def test_get_ad_sense_link_flattened(): assert arg == mock_val -def test_get_ad_sense_link_flattened_error(): +def test_get_big_query_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -46500,31 +46246,31 @@ def test_get_ad_sense_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_ad_sense_link( - analytics_admin.GetAdSenseLinkRequest(), + client.get_big_query_link( + analytics_admin.GetBigQueryLinkRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_ad_sense_link_flattened_async(): +async def test_get_big_query_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ad_sense_link), "__call__" + type(client.transport.get_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AdSenseLink() + call.return_value = resources.BigQueryLink() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink() + resources.BigQueryLink() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_ad_sense_link( + response = await client.get_big_query_link( name="name_value", ) @@ -46538,7 +46284,7 @@ async def test_get_ad_sense_link_flattened_async(): @pytest.mark.asyncio -async def test_get_ad_sense_link_flattened_error_async(): +async def test_get_big_query_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -46546,8 +46292,8 @@ async def test_get_ad_sense_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_ad_sense_link( - analytics_admin.GetAdSenseLinkRequest(), + await client.get_big_query_link( + analytics_admin.GetBigQueryLinkRequest(), name="name_value", ) @@ -46555,11 +46301,11 @@ async def test_get_ad_sense_link_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateAdSenseLinkRequest, + analytics_admin.ListBigQueryLinksRequest, dict, ], ) -def test_create_ad_sense_link(request_type, transport: str = "grpc"): +def test_list_big_query_links(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -46571,28 +46317,26 @@ def test_create_ad_sense_link(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AdSenseLink( - name="name_value", - ad_client_code="ad_client_code_value", + call.return_value = analytics_admin.ListBigQueryLinksResponse( + next_page_token="next_page_token_value", ) - response = client.create_ad_sense_link(request) + response = client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateAdSenseLinkRequest() + request = analytics_admin.ListBigQueryLinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AdSenseLink) - assert response.name == "name_value" - assert response.ad_client_code == "ad_client_code_value" + assert isinstance(response, pagers.ListBigQueryLinksPager) + assert response.next_page_token == "next_page_token_value" -def test_create_ad_sense_link_empty_call(): +def test_list_big_query_links_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -46602,18 +46346,18 @@ def test_create_ad_sense_link_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_ad_sense_link() + client.list_big_query_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAdSenseLinkRequest() + assert args[0] == analytics_admin.ListBigQueryLinksRequest() -def test_create_ad_sense_link_non_empty_request_with_auto_populated_field(): +def test_list_big_query_links_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -46624,26 +46368,28 @@ def test_create_ad_sense_link_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateAdSenseLinkRequest( + request = analytics_admin.ListBigQueryLinksRequest( parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_ad_sense_link(request=request) + client.list_big_query_links(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAdSenseLinkRequest( + assert args[0] == analytics_admin.ListBigQueryLinksRequest( parent="parent_value", + page_token="page_token_value", ) -def test_create_ad_sense_link_use_cached_wrapped_rpc(): +def test_list_big_query_links_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -46658,7 +46404,7 @@ def test_create_ad_sense_link_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_ad_sense_link in client._transport._wrapped_methods + client._transport.list_big_query_links in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -46667,15 +46413,15 @@ def test_create_ad_sense_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_ad_sense_link + client._transport.list_big_query_links ] = mock_rpc request = {} - client.create_ad_sense_link(request) + client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_ad_sense_link(request) + client.list_big_query_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -46683,7 +46429,7 @@ def test_create_ad_sense_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_ad_sense_link_empty_call_async(): +async def test_list_big_query_links_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -46693,23 +46439,22 @@ async def test_create_ad_sense_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink( - name="name_value", - ad_client_code="ad_client_code_value", + analytics_admin.ListBigQueryLinksResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_ad_sense_link() + response = await client.list_big_query_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateAdSenseLinkRequest() + assert args[0] == analytics_admin.ListBigQueryLinksRequest() @pytest.mark.asyncio -async def test_create_ad_sense_link_async_use_cached_wrapped_rpc( +async def test_list_big_query_links_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -46726,23 +46471,23 @@ async def test_create_ad_sense_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_ad_sense_link + client._client._transport.list_big_query_links in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_ad_sense_link + client._client._transport.list_big_query_links ] = mock_object request = {} - await client.create_ad_sense_link(request) + await client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_ad_sense_link(request) + await client.list_big_query_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -46750,9 +46495,9 @@ async def test_create_ad_sense_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_ad_sense_link_async( +async def test_list_big_query_links_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateAdSenseLinkRequest, + request_type=analytics_admin.ListBigQueryLinksRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -46765,51 +46510,49 @@ async def test_create_ad_sense_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink( - name="name_value", - ad_client_code="ad_client_code_value", + analytics_admin.ListBigQueryLinksResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_ad_sense_link(request) + response = await client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateAdSenseLinkRequest() + request = analytics_admin.ListBigQueryLinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.AdSenseLink) - assert response.name == "name_value" - assert response.ad_client_code == "ad_client_code_value" + assert isinstance(response, pagers.ListBigQueryLinksAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_create_ad_sense_link_async_from_dict(): - await test_create_ad_sense_link_async(request_type=dict) +async def test_list_big_query_links_async_from_dict(): + await test_list_big_query_links_async(request_type=dict) -def test_create_ad_sense_link_field_headers(): +def test_list_big_query_links_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateAdSenseLinkRequest() + request = analytics_admin.ListBigQueryLinksRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: - call.return_value = resources.AdSenseLink() - client.create_ad_sense_link(request) + call.return_value = analytics_admin.ListBigQueryLinksResponse() + client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -46825,25 +46568,25 @@ def test_create_ad_sense_link_field_headers(): @pytest.mark.asyncio -async def test_create_ad_sense_link_field_headers_async(): +async def test_list_big_query_links_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateAdSenseLinkRequest() + request = analytics_admin.ListBigQueryLinksRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink() + analytics_admin.ListBigQueryLinksResponse() ) - await client.create_ad_sense_link(request) + await client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -46858,22 +46601,21 @@ async def test_create_ad_sense_link_field_headers_async(): ) in kw["metadata"] -def test_create_ad_sense_link_flattened(): +def test_list_big_query_links_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AdSenseLink() + call.return_value = analytics_admin.ListBigQueryLinksResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_ad_sense_link( + client.list_big_query_links( parent="parent_value", - adsense_link=resources.AdSenseLink(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -46883,12 +46625,9 @@ def test_create_ad_sense_link_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].adsense_link - mock_val = resources.AdSenseLink(name="name_value") - assert arg == mock_val -def test_create_ad_sense_link_flattened_error(): +def test_list_big_query_links_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -46896,34 +46635,32 @@ def test_create_ad_sense_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_ad_sense_link( - analytics_admin.CreateAdSenseLinkRequest(), + client.list_big_query_links( + analytics_admin.ListBigQueryLinksRequest(), parent="parent_value", - adsense_link=resources.AdSenseLink(name="name_value"), ) @pytest.mark.asyncio -async def test_create_ad_sense_link_flattened_async(): +async def test_list_big_query_links_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.AdSenseLink() + call.return_value = analytics_admin.ListBigQueryLinksResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.AdSenseLink() + analytics_admin.ListBigQueryLinksResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_ad_sense_link( + response = await client.list_big_query_links( parent="parent_value", - adsense_link=resources.AdSenseLink(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -46933,13 +46670,10 @@ async def test_create_ad_sense_link_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].adsense_link - mock_val = resources.AdSenseLink(name="name_value") - assert arg == mock_val @pytest.mark.asyncio -async def test_create_ad_sense_link_flattened_error_async(): +async def test_list_big_query_links_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -46947,70 +46681,271 @@ async def test_create_ad_sense_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_ad_sense_link( - analytics_admin.CreateAdSenseLinkRequest(), + await client.list_big_query_links( + analytics_admin.ListBigQueryLinksRequest(), parent="parent_value", - adsense_link=resources.AdSenseLink(name="name_value"), ) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.DeleteAdSenseLinkRequest, - dict, - ], -) -def test_delete_ad_sense_link(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_ad_sense_link(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteAdSenseLinkRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_ad_sense_link_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_list_big_query_links_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.list_big_query_links), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token="def", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_big_query_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.BigQueryLink) for i in results) + + +def test_list_big_query_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token="def", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_links(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_big_query_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token="def", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_links( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.BigQueryLink) for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token="def", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_big_query_links(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteBigQueryLinkRequest, + dict, + ], +) +def test_delete_big_query_link(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_ad_sense_link() + client.delete_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteAdSenseLinkRequest() + assert args[0] == analytics_admin.DeleteBigQueryLinkRequest() -def test_delete_ad_sense_link_non_empty_request_with_auto_populated_field(): +def test_delete_big_query_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -47021,26 +46956,26 @@ def test_delete_ad_sense_link_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteAdSenseLinkRequest( + request = analytics_admin.DeleteBigQueryLinkRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_ad_sense_link(request=request) + client.delete_big_query_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteAdSenseLinkRequest( + assert args[0] == analytics_admin.DeleteBigQueryLinkRequest( name="name_value", ) -def test_delete_ad_sense_link_use_cached_wrapped_rpc(): +def test_delete_big_query_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -47055,7 +46990,8 @@ def test_delete_ad_sense_link_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_ad_sense_link in client._transport._wrapped_methods + client._transport.delete_big_query_link + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -47064,15 +47000,15 @@ def test_delete_ad_sense_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_ad_sense_link + client._transport.delete_big_query_link ] = mock_rpc request = {} - client.delete_ad_sense_link(request) + client.delete_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_ad_sense_link(request) + client.delete_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -47080,7 +47016,7 @@ def test_delete_ad_sense_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_ad_sense_link_empty_call_async(): +async def test_delete_big_query_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -47090,18 +47026,18 @@ async def test_delete_ad_sense_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_ad_sense_link() + response = await client.delete_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteAdSenseLinkRequest() + assert args[0] == analytics_admin.DeleteBigQueryLinkRequest() @pytest.mark.asyncio -async def test_delete_ad_sense_link_async_use_cached_wrapped_rpc( +async def test_delete_big_query_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -47118,23 +47054,23 @@ async def test_delete_ad_sense_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_ad_sense_link + client._client._transport.delete_big_query_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_ad_sense_link + client._client._transport.delete_big_query_link ] = mock_object request = {} - await client.delete_ad_sense_link(request) + await client.delete_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_ad_sense_link(request) + await client.delete_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -47142,9 +47078,9 @@ async def test_delete_ad_sense_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_ad_sense_link_async( +async def test_delete_big_query_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteAdSenseLinkRequest, + request_type=analytics_admin.DeleteBigQueryLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -47157,16 +47093,16 @@ async def test_delete_ad_sense_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_ad_sense_link(request) + response = await client.delete_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteAdSenseLinkRequest() + request = analytics_admin.DeleteBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -47174,27 +47110,27 @@ async def test_delete_ad_sense_link_async( @pytest.mark.asyncio -async def test_delete_ad_sense_link_async_from_dict(): - await test_delete_ad_sense_link_async(request_type=dict) +async def test_delete_big_query_link_async_from_dict(): + await test_delete_big_query_link_async(request_type=dict) -def test_delete_ad_sense_link_field_headers(): +def test_delete_big_query_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteAdSenseLinkRequest() + request = analytics_admin.DeleteBigQueryLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: call.return_value = None - client.delete_ad_sense_link(request) + client.delete_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -47210,23 +47146,23 @@ def test_delete_ad_sense_link_field_headers(): @pytest.mark.asyncio -async def test_delete_ad_sense_link_field_headers_async(): +async def test_delete_big_query_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteAdSenseLinkRequest() + request = analytics_admin.DeleteBigQueryLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_ad_sense_link(request) + await client.delete_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -47241,20 +47177,20 @@ async def test_delete_ad_sense_link_field_headers_async(): ) in kw["metadata"] -def test_delete_ad_sense_link_flattened(): +def test_delete_big_query_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_ad_sense_link( + client.delete_big_query_link( name="name_value", ) @@ -47267,7 +47203,7 @@ def test_delete_ad_sense_link_flattened(): assert arg == mock_val -def test_delete_ad_sense_link_flattened_error(): +def test_delete_big_query_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -47275,21 +47211,21 @@ def test_delete_ad_sense_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_ad_sense_link( - analytics_admin.DeleteAdSenseLinkRequest(), + client.delete_big_query_link( + analytics_admin.DeleteBigQueryLinkRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_ad_sense_link_flattened_async(): +async def test_delete_big_query_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_ad_sense_link), "__call__" + type(client.transport.delete_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -47297,7 +47233,7 @@ async def test_delete_ad_sense_link_flattened_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_ad_sense_link( + response = await client.delete_big_query_link( name="name_value", ) @@ -47311,7 +47247,7 @@ async def test_delete_ad_sense_link_flattened_async(): @pytest.mark.asyncio -async def test_delete_ad_sense_link_flattened_error_async(): +async def test_delete_big_query_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -47319,8 +47255,8 @@ async def test_delete_ad_sense_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_ad_sense_link( - analytics_admin.DeleteAdSenseLinkRequest(), + await client.delete_big_query_link( + analytics_admin.DeleteBigQueryLinkRequest(), name="name_value", ) @@ -47328,11 +47264,11 @@ async def test_delete_ad_sense_link_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListAdSenseLinksRequest, + analytics_admin.UpdateBigQueryLinkRequest, dict, ], ) -def test_list_ad_sense_links(request_type, transport: str = "grpc"): +def test_update_big_query_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -47344,26 +47280,42 @@ def test_list_ad_sense_links(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAdSenseLinksResponse( - next_page_token="next_page_token_value", + call.return_value = resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) - response = client.list_ad_sense_links(request) + response = client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListAdSenseLinksRequest() + request = analytics_admin.UpdateBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAdSenseLinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.BigQueryLink) + assert response.name == "name_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" -def test_list_ad_sense_links_empty_call(): +def test_update_big_query_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -47373,18 +47325,18 @@ def test_list_ad_sense_links_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_ad_sense_links() + client.update_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAdSenseLinksRequest() + assert args[0] == analytics_admin.UpdateBigQueryLinkRequest() -def test_list_ad_sense_links_non_empty_request_with_auto_populated_field(): +def test_update_big_query_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -47395,28 +47347,22 @@ def test_list_ad_sense_links_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListAdSenseLinksRequest( - parent="parent_value", - page_token="page_token_value", - ) + request = analytics_admin.UpdateBigQueryLinkRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_ad_sense_links(request=request) + client.update_big_query_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAdSenseLinksRequest( - parent="parent_value", - page_token="page_token_value", - ) + assert args[0] == analytics_admin.UpdateBigQueryLinkRequest() -def test_list_ad_sense_links_use_cached_wrapped_rpc(): +def test_update_big_query_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -47431,7 +47377,8 @@ def test_list_ad_sense_links_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_ad_sense_links in client._transport._wrapped_methods + client._transport.update_big_query_link + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -47440,15 +47387,15 @@ def test_list_ad_sense_links_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_ad_sense_links + client._transport.update_big_query_link ] = mock_rpc request = {} - client.list_ad_sense_links(request) + client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_ad_sense_links(request) + client.update_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -47456,7 +47403,7 @@ def test_list_ad_sense_links_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_ad_sense_links_empty_call_async(): +async def test_update_big_query_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -47466,22 +47413,30 @@ async def test_list_ad_sense_links_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAdSenseLinksResponse( - next_page_token="next_page_token_value", + resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) ) - response = await client.list_ad_sense_links() + response = await client.update_big_query_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListAdSenseLinksRequest() + assert args[0] == analytics_admin.UpdateBigQueryLinkRequest() @pytest.mark.asyncio -async def test_list_ad_sense_links_async_use_cached_wrapped_rpc( +async def test_update_big_query_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -47498,23 +47453,23 @@ async def test_list_ad_sense_links_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_ad_sense_links + client._client._transport.update_big_query_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_ad_sense_links + client._client._transport.update_big_query_link ] = mock_object request = {} - await client.list_ad_sense_links(request) + await client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_ad_sense_links(request) + await client.update_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -47522,9 +47477,9 @@ async def test_list_ad_sense_links_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_ad_sense_links_async( +async def test_update_big_query_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListAdSenseLinksRequest, + request_type=analytics_admin.UpdateBigQueryLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -47537,49 +47492,65 @@ async def test_list_ad_sense_links_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAdSenseLinksResponse( - next_page_token="next_page_token_value", + resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) ) - response = await client.list_ad_sense_links(request) + response = await client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListAdSenseLinksRequest() + request = analytics_admin.UpdateBigQueryLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAdSenseLinksAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.BigQueryLink) + assert response.name == "name_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" @pytest.mark.asyncio -async def test_list_ad_sense_links_async_from_dict(): - await test_list_ad_sense_links_async(request_type=dict) +async def test_update_big_query_link_async_from_dict(): + await test_update_big_query_link_async(request_type=dict) -def test_list_ad_sense_links_field_headers(): +def test_update_big_query_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListAdSenseLinksRequest() + request = analytics_admin.UpdateBigQueryLinkRequest() - request.parent = "parent_value" + request.bigquery_link.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: - call.return_value = analytics_admin.ListAdSenseLinksResponse() - client.list_ad_sense_links(request) + call.return_value = resources.BigQueryLink() + client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -47590,30 +47561,30 @@ def test_list_ad_sense_links_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "bigquery_link.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_ad_sense_links_field_headers_async(): +async def test_update_big_query_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListAdSenseLinksRequest() + request = analytics_admin.UpdateBigQueryLinkRequest() - request.parent = "parent_value" + request.bigquery_link.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAdSenseLinksResponse() + resources.BigQueryLink() ) - await client.list_ad_sense_links(request) + await client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -47624,37 +47595,41 @@ async def test_list_ad_sense_links_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "bigquery_link.name=name_value", ) in kw["metadata"] -def test_list_ad_sense_links_flattened(): +def test_update_big_query_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAdSenseLinksResponse() + call.return_value = resources.BigQueryLink() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_ad_sense_links( - parent="parent_value", + client.update_big_query_link( + bigquery_link=resources.BigQueryLink(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].bigquery_link + mock_val = resources.BigQueryLink(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_list_ad_sense_links_flattened_error(): +def test_update_big_query_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -47662,45 +47637,50 @@ def test_list_ad_sense_links_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_ad_sense_links( - analytics_admin.ListAdSenseLinksRequest(), - parent="parent_value", + client.update_big_query_link( + analytics_admin.UpdateBigQueryLinkRequest(), + bigquery_link=resources.BigQueryLink(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_list_ad_sense_links_flattened_async(): +async def test_update_big_query_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.update_big_query_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListAdSenseLinksResponse() + call.return_value = resources.BigQueryLink() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListAdSenseLinksResponse() + resources.BigQueryLink() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_ad_sense_links( - parent="parent_value", + response = await client.update_big_query_link( + bigquery_link=resources.BigQueryLink(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].bigquery_link + mock_val = resources.BigQueryLink(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_list_ad_sense_links_flattened_error_async(): +async def test_update_big_query_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -47708,257 +47688,72 @@ async def test_list_ad_sense_links_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_ad_sense_links( - analytics_admin.ListAdSenseLinksRequest(), - parent="parent_value", + await client.update_big_query_link( + analytics_admin.UpdateBigQueryLinkRequest(), + bigquery_link=resources.BigQueryLink(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_ad_sense_links_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetEnhancedMeasurementSettingsRequest, + dict, + ], +) +def test_get_enhanced_measurement_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[], - next_page_token="def", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings( + name="name_value", + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) - pager = client.list_ad_sense_links(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.AdSenseLink) for i in results) + response = client.get_enhanced_measurement_settings(request) - -def test_list_ad_sense_links_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ad_sense_links), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[], - next_page_token="def", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - ), - RuntimeError, - ) - pages = list(client.list_ad_sense_links(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_ad_sense_links_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ad_sense_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[], - next_page_token="def", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_ad_sense_links( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.AdSenseLink) for i in responses) - - -@pytest.mark.asyncio -async def test_list_ad_sense_links_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ad_sense_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[], - next_page_token="def", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_ad_sense_links(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetEventCreateRuleRequest, - dict, - ], -) -def test_get_event_create_rule(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) - response = client.get_event_create_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.GetEventCreateRuleRequest() - assert args[0] == request + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) + assert isinstance(response, resources.EnhancedMeasurementSettings) assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == "search_query_parameter_value" + assert response.uri_query_parameter == "uri_query_parameter_value" -def test_get_event_create_rule_empty_call(): +def test_get_enhanced_measurement_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -47968,18 +47763,18 @@ def test_get_event_create_rule_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_event_create_rule() + client.get_enhanced_measurement_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetEventCreateRuleRequest() + assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest() -def test_get_event_create_rule_non_empty_request_with_auto_populated_field(): +def test_get_enhanced_measurement_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -47990,26 +47785,26 @@ def test_get_event_create_rule_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetEventCreateRuleRequest( + request = analytics_admin.GetEnhancedMeasurementSettingsRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_event_create_rule(request=request) + client.get_enhanced_measurement_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetEventCreateRuleRequest( + assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest( name="name_value", ) -def test_get_event_create_rule_use_cached_wrapped_rpc(): +def test_get_enhanced_measurement_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -48024,7 +47819,7 @@ def test_get_event_create_rule_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_event_create_rule + client._transport.get_enhanced_measurement_settings in client._transport._wrapped_methods ) @@ -48034,15 +47829,15 @@ def test_get_event_create_rule_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_event_create_rule + client._transport.get_enhanced_measurement_settings ] = mock_rpc request = {} - client.get_event_create_rule(request) + client.get_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_event_create_rule(request) + client.get_enhanced_measurement_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -48050,7 +47845,7 @@ def test_get_event_create_rule_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_event_create_rule_empty_call_async(): +async def test_get_enhanced_measurement_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -48060,24 +47855,32 @@ async def test_get_event_create_rule_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule( + resources.EnhancedMeasurementSettings( name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) ) - response = await client.get_event_create_rule() + response = await client.get_enhanced_measurement_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetEventCreateRuleRequest() + assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest() @pytest.mark.asyncio -async def test_get_event_create_rule_async_use_cached_wrapped_rpc( +async def test_get_enhanced_measurement_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -48094,23 +47897,23 @@ async def test_get_event_create_rule_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_event_create_rule + client._client._transport.get_enhanced_measurement_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_event_create_rule + client._client._transport.get_enhanced_measurement_settings ] = mock_object request = {} - await client.get_event_create_rule(request) + await client.get_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_event_create_rule(request) + await client.get_enhanced_measurement_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -48118,9 +47921,9 @@ async def test_get_event_create_rule_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_event_create_rule_async( +async def test_get_enhanced_measurement_settings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetEventCreateRuleRequest, + request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -48133,53 +47936,69 @@ async def test_get_event_create_rule_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule( + resources.EnhancedMeasurementSettings( name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) ) - response = await client.get_event_create_rule(request) + response = await client.get_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetEventCreateRuleRequest() + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) + assert isinstance(response, resources.EnhancedMeasurementSettings) assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == "search_query_parameter_value" + assert response.uri_query_parameter == "uri_query_parameter_value" @pytest.mark.asyncio -async def test_get_event_create_rule_async_from_dict(): - await test_get_event_create_rule_async(request_type=dict) +async def test_get_enhanced_measurement_settings_async_from_dict(): + await test_get_enhanced_measurement_settings_async(request_type=dict) -def test_get_event_create_rule_field_headers(): +def test_get_enhanced_measurement_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetEventCreateRuleRequest() + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: - call.return_value = event_create_and_edit.EventCreateRule() - client.get_event_create_rule(request) + call.return_value = resources.EnhancedMeasurementSettings() + client.get_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -48195,25 +48014,25 @@ def test_get_event_create_rule_field_headers(): @pytest.mark.asyncio -async def test_get_event_create_rule_field_headers_async(): +async def test_get_enhanced_measurement_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetEventCreateRuleRequest() + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule() + resources.EnhancedMeasurementSettings() ) - await client.get_event_create_rule(request) + await client.get_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -48228,20 +48047,20 @@ async def test_get_event_create_rule_field_headers_async(): ) in kw["metadata"] -def test_get_event_create_rule_flattened(): +def test_get_enhanced_measurement_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule() + call.return_value = resources.EnhancedMeasurementSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_event_create_rule( + client.get_enhanced_measurement_settings( name="name_value", ) @@ -48254,7 +48073,7 @@ def test_get_event_create_rule_flattened(): assert arg == mock_val -def test_get_event_create_rule_flattened_error(): +def test_get_enhanced_measurement_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -48262,31 +48081,31 @@ def test_get_event_create_rule_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_event_create_rule( - analytics_admin.GetEventCreateRuleRequest(), + client.get_enhanced_measurement_settings( + analytics_admin.GetEnhancedMeasurementSettingsRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_event_create_rule_flattened_async(): +async def test_get_enhanced_measurement_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_event_create_rule), "__call__" + type(client.transport.get_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule() + call.return_value = resources.EnhancedMeasurementSettings() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule() + resources.EnhancedMeasurementSettings() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_event_create_rule( + response = await client.get_enhanced_measurement_settings( name="name_value", ) @@ -48300,7 +48119,7 @@ async def test_get_event_create_rule_flattened_async(): @pytest.mark.asyncio -async def test_get_event_create_rule_flattened_error_async(): +async def test_get_enhanced_measurement_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -48308,8 +48127,8 @@ async def test_get_event_create_rule_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_event_create_rule( - analytics_admin.GetEventCreateRuleRequest(), + await client.get_enhanced_measurement_settings( + analytics_admin.GetEnhancedMeasurementSettingsRequest(), name="name_value", ) @@ -48317,11 +48136,11 @@ async def test_get_event_create_rule_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListEventCreateRulesRequest, + analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict, ], ) -def test_list_event_create_rules(request_type, transport: str = "grpc"): +def test_update_enhanced_measurement_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -48333,26 +48152,46 @@ def test_list_event_create_rules(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListEventCreateRulesResponse( - next_page_token="next_page_token_value", + call.return_value = resources.EnhancedMeasurementSettings( + name="name_value", + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) - response = client.list_event_create_rules(request) + response = client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListEventCreateRulesRequest() + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventCreateRulesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == "name_value" + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == "search_query_parameter_value" + assert response.uri_query_parameter == "uri_query_parameter_value" -def test_list_event_create_rules_empty_call(): +def test_update_enhanced_measurement_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -48362,18 +48201,18 @@ def test_list_event_create_rules_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_event_create_rules() + client.update_enhanced_measurement_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListEventCreateRulesRequest() + assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() -def test_list_event_create_rules_non_empty_request_with_auto_populated_field(): +def test_update_enhanced_measurement_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -48384,28 +48223,22 @@ def test_list_event_create_rules_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListEventCreateRulesRequest( - parent="parent_value", - page_token="page_token_value", - ) + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_event_create_rules(request=request) + client.update_enhanced_measurement_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListEventCreateRulesRequest( - parent="parent_value", - page_token="page_token_value", - ) + assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() -def test_list_event_create_rules_use_cached_wrapped_rpc(): +def test_update_enhanced_measurement_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -48420,7 +48253,7 @@ def test_list_event_create_rules_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_event_create_rules + client._transport.update_enhanced_measurement_settings in client._transport._wrapped_methods ) @@ -48430,15 +48263,15 @@ def test_list_event_create_rules_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_event_create_rules + client._transport.update_enhanced_measurement_settings ] = mock_rpc request = {} - client.list_event_create_rules(request) + client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_event_create_rules(request) + client.update_enhanced_measurement_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -48446,7 +48279,7 @@ def test_list_event_create_rules_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_event_create_rules_empty_call_async(): +async def test_update_enhanced_measurement_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -48456,22 +48289,32 @@ async def test_list_event_create_rules_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListEventCreateRulesResponse( - next_page_token="next_page_token_value", + resources.EnhancedMeasurementSettings( + name="name_value", + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) ) - response = await client.list_event_create_rules() + response = await client.update_enhanced_measurement_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListEventCreateRulesRequest() + assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() @pytest.mark.asyncio -async def test_list_event_create_rules_async_use_cached_wrapped_rpc( +async def test_update_enhanced_measurement_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -48488,23 +48331,23 @@ async def test_list_event_create_rules_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_event_create_rules + client._client._transport.update_enhanced_measurement_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_event_create_rules + client._client._transport.update_enhanced_measurement_settings ] = mock_object request = {} - await client.list_event_create_rules(request) + await client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_event_create_rules(request) + await client.update_enhanced_measurement_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -48512,9 +48355,9 @@ async def test_list_event_create_rules_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_event_create_rules_async( +async def test_update_enhanced_measurement_settings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListEventCreateRulesRequest, + request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -48527,49 +48370,69 @@ async def test_list_event_create_rules_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListEventCreateRulesResponse( - next_page_token="next_page_token_value", + resources.EnhancedMeasurementSettings( + name="name_value", + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) ) - response = await client.list_event_create_rules(request) + response = await client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListEventCreateRulesRequest() + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventCreateRulesAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == "name_value" + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == "search_query_parameter_value" + assert response.uri_query_parameter == "uri_query_parameter_value" @pytest.mark.asyncio -async def test_list_event_create_rules_async_from_dict(): - await test_list_event_create_rules_async(request_type=dict) +async def test_update_enhanced_measurement_settings_async_from_dict(): + await test_update_enhanced_measurement_settings_async(request_type=dict) -def test_list_event_create_rules_field_headers(): +def test_update_enhanced_measurement_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListEventCreateRulesRequest() + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() - request.parent = "parent_value" + request.enhanced_measurement_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: - call.return_value = analytics_admin.ListEventCreateRulesResponse() - client.list_event_create_rules(request) + call.return_value = resources.EnhancedMeasurementSettings() + client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -48580,30 +48443,30 @@ def test_list_event_create_rules_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "enhanced_measurement_settings.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_event_create_rules_field_headers_async(): +async def test_update_enhanced_measurement_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListEventCreateRulesRequest() + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() - request.parent = "parent_value" + request.enhanced_measurement_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListEventCreateRulesResponse() + resources.EnhancedMeasurementSettings() ) - await client.list_event_create_rules(request) + await client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -48614,37 +48477,43 @@ async def test_list_event_create_rules_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "enhanced_measurement_settings.name=name_value", ) in kw["metadata"] -def test_list_event_create_rules_flattened(): +def test_update_enhanced_measurement_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListEventCreateRulesResponse() + call.return_value = resources.EnhancedMeasurementSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_event_create_rules( - parent="parent_value", + client.update_enhanced_measurement_settings( + enhanced_measurement_settings=resources.EnhancedMeasurementSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].enhanced_measurement_settings + mock_val = resources.EnhancedMeasurementSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_list_event_create_rules_flattened_error(): +def test_update_enhanced_measurement_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -48652,45 +48521,54 @@ def test_list_event_create_rules_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_event_create_rules( - analytics_admin.ListEventCreateRulesRequest(), - parent="parent_value", + client.update_enhanced_measurement_settings( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), + enhanced_measurement_settings=resources.EnhancedMeasurementSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_list_event_create_rules_flattened_async(): +async def test_update_enhanced_measurement_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" + type(client.transport.update_enhanced_measurement_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListEventCreateRulesResponse() + call.return_value = resources.EnhancedMeasurementSettings() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListEventCreateRulesResponse() + resources.EnhancedMeasurementSettings() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_event_create_rules( - parent="parent_value", + response = await client.update_enhanced_measurement_settings( + enhanced_measurement_settings=resources.EnhancedMeasurementSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].enhanced_measurement_settings + mock_val = resources.EnhancedMeasurementSettings(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_list_event_create_rules_flattened_error_async(): +async def test_update_enhanced_measurement_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -48698,226 +48576,23 @@ async def test_list_event_create_rules_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_event_create_rules( - analytics_admin.ListEventCreateRulesRequest(), - parent="parent_value", - ) - - -def test_list_event_create_rules_pager(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - next_page_token="abc", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[], - next_page_token="def", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - ], - next_page_token="ghi", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_event_create_rules(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, event_create_and_edit.EventCreateRule) for i in results - ) - - -def test_list_event_create_rules_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_create_rules), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - next_page_token="abc", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[], - next_page_token="def", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - ], - next_page_token="ghi", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - ), - RuntimeError, - ) - pages = list(client.list_event_create_rules(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_event_create_rules_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_create_rules), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - next_page_token="abc", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[], - next_page_token="def", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - ], - next_page_token="ghi", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_event_create_rules( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all( - isinstance(i, event_create_and_edit.EventCreateRule) for i in responses - ) - - -@pytest.mark.asyncio -async def test_list_event_create_rules_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_event_create_rules), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], - next_page_token="abc", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[], - next_page_token="def", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - ], - next_page_token="ghi", - ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - ], + await client.update_enhanced_measurement_settings( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), + enhanced_measurement_settings=resources.EnhancedMeasurementSettings( + name="name_value" ), - RuntimeError, + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_event_create_rules(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateEventCreateRuleRequest, + analytics_admin.CreateConnectedSiteTagRequest, dict, ], ) -def test_create_event_create_rule(request_type, transport: str = "grpc"): +def test_create_connected_site_tag(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -48929,30 +48604,23 @@ def test_create_event_create_rule(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.create_connected_site_tag), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) - response = client.create_event_create_rule(request) + call.return_value = analytics_admin.CreateConnectedSiteTagResponse() + response = client.create_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateEventCreateRuleRequest() + request = analytics_admin.CreateConnectedSiteTagRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) - assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) -def test_create_event_create_rule_empty_call(): +def test_create_connected_site_tag_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -48962,18 +48630,18 @@ def test_create_event_create_rule_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.create_connected_site_tag), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_event_create_rule() + client.create_connected_site_tag() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateEventCreateRuleRequest() + assert args[0] == analytics_admin.CreateConnectedSiteTagRequest() -def test_create_event_create_rule_non_empty_request_with_auto_populated_field(): +def test_create_connected_site_tag_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -48984,26 +48652,26 @@ def test_create_event_create_rule_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateEventCreateRuleRequest( - parent="parent_value", + request = analytics_admin.CreateConnectedSiteTagRequest( + property="property_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.create_connected_site_tag), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_event_create_rule(request=request) + client.create_connected_site_tag(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateEventCreateRuleRequest( - parent="parent_value", + assert args[0] == analytics_admin.CreateConnectedSiteTagRequest( + property="property_value", ) -def test_create_event_create_rule_use_cached_wrapped_rpc(): +def test_create_connected_site_tag_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -49018,7 +48686,7 @@ def test_create_event_create_rule_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_event_create_rule + client._transport.create_connected_site_tag in client._transport._wrapped_methods ) @@ -49028,15 +48696,15 @@ def test_create_event_create_rule_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_event_create_rule + client._transport.create_connected_site_tag ] = mock_rpc request = {} - client.create_event_create_rule(request) + client.create_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_event_create_rule(request) + client.create_connected_site_tag(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -49044,7 +48712,7 @@ def test_create_event_create_rule_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_event_create_rule_empty_call_async(): +async def test_create_connected_site_tag_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -49054,24 +48722,20 @@ async def test_create_event_create_rule_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.create_connected_site_tag), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) + analytics_admin.CreateConnectedSiteTagResponse() ) - response = await client.create_event_create_rule() + response = await client.create_connected_site_tag() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateEventCreateRuleRequest() + assert args[0] == analytics_admin.CreateConnectedSiteTagRequest() @pytest.mark.asyncio -async def test_create_event_create_rule_async_use_cached_wrapped_rpc( +async def test_create_connected_site_tag_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -49088,23 +48752,23 @@ async def test_create_event_create_rule_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_event_create_rule + client._client._transport.create_connected_site_tag in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_event_create_rule + client._client._transport.create_connected_site_tag ] = mock_object request = {} - await client.create_event_create_rule(request) + await client.create_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_event_create_rule(request) + await client.create_connected_site_tag(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -49112,9 +48776,9 @@ async def test_create_event_create_rule_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_event_create_rule_async( +async def test_create_connected_site_tag_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateEventCreateRuleRequest, + request_type=analytics_admin.CreateConnectedSiteTagRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -49127,205 +48791,264 @@ async def test_create_event_create_rule_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.create_connected_site_tag), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) + analytics_admin.CreateConnectedSiteTagResponse() ) - response = await client.create_event_create_rule(request) + response = await client.create_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateEventCreateRuleRequest() + request = analytics_admin.CreateConnectedSiteTagRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) - assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) @pytest.mark.asyncio -async def test_create_event_create_rule_async_from_dict(): - await test_create_event_create_rule_async(request_type=dict) +async def test_create_connected_site_tag_async_from_dict(): + await test_create_connected_site_tag_async(request_type=dict) -def test_create_event_create_rule_field_headers(): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteConnectedSiteTagRequest, + dict, + ], +) +def test_delete_connected_site_tag(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.CreateEventCreateRuleRequest() - - request.parent = "parent_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.delete_connected_site_tag), "__call__" ) as call: - call.return_value = event_create_and_edit.EventCreateRule() - client.create_event_create_rule(request) + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConnectedSiteTagRequest() assert args[0] == request - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + # Establish that the response is the type that we expect. + assert response is None -@pytest.mark.asyncio -async def test_create_event_create_rule_field_headers_async(): - client = AnalyticsAdminServiceAsyncClient( +def test_delete_connected_site_tag_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.CreateEventCreateRuleRequest() - - request.parent = "parent_value" - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.delete_connected_site_tag), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule() + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.create_event_create_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) + client.delete_connected_site_tag() + call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] + assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest() -def test_create_event_create_rule_flattened(): +def test_delete_connected_site_tag_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.DeleteConnectedSiteTagRequest( + property="property_value", + tag_id="tag_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.delete_connected_site_tag), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_event_create_rule( - parent="parent_value", - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 + client.delete_connected_site_tag(request=request) + call.assert_called() _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].event_create_rule - mock_val = event_create_and_edit.EventCreateRule(name="name_value") - assert arg == mock_val - + assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest( + property="property_value", + tag_id="tag_id_value", + ) -def test_create_event_create_rule_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_event_create_rule( - analytics_admin.CreateEventCreateRuleRequest(), - parent="parent_value", - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), +def test_delete_connected_site_tag_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.asyncio -async def test_create_event_create_rule_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + # Ensure method has been cached + assert ( + client._transport.delete_connected_site_tag + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_connected_site_tag + ] = mock_rpc + request = {} + client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_connected_site_tag_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_event_create_rule), "__call__" + type(client.transport.delete_connected_site_tag), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_connected_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule() + +@pytest.mark.asyncio +async def test_delete_connected_site_tag_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_event_create_rule( - parent="parent_value", - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_connected_site_tag + in client._client._transport._wrapped_methods ) - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].event_create_rule - mock_val = event_create_and_edit.EventCreateRule(name="name_value") - assert arg == mock_val + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_connected_site_tag + ] = mock_object + + request = {} + await client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 @pytest.mark.asyncio -async def test_create_event_create_rule_flattened_error_async(): +async def test_delete_connected_site_tag_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.DeleteConnectedSiteTagRequest, +): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_event_create_rule( - analytics_admin.CreateEventCreateRuleRequest(), - parent="parent_value", - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connected_site_tag), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConnectedSiteTagRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_connected_site_tag_async_from_dict(): + await test_delete_connected_site_tag_async(request_type=dict) @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateEventCreateRuleRequest, + analytics_admin.ListConnectedSiteTagsRequest, dict, ], ) -def test_update_event_create_rule(request_type, transport: str = "grpc"): +def test_list_connected_site_tags(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -49337,30 +49060,23 @@ def test_update_event_create_rule(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" + type(client.transport.list_connected_site_tags), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) - response = client.update_event_create_rule(request) + call.return_value = analytics_admin.ListConnectedSiteTagsResponse() + response = client.list_connected_site_tags(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateEventCreateRuleRequest() + request = analytics_admin.ListConnectedSiteTagsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) - assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) -def test_update_event_create_rule_empty_call(): +def test_list_connected_site_tags_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -49370,18 +49086,18 @@ def test_update_event_create_rule_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" + type(client.transport.list_connected_site_tags), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_event_create_rule() + client.list_connected_site_tags() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() + assert args[0] == analytics_admin.ListConnectedSiteTagsRequest() -def test_update_event_create_rule_non_empty_request_with_auto_populated_field(): +def test_list_connected_site_tags_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -49392,22 +49108,26 @@ def test_update_event_create_rule_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateEventCreateRuleRequest() + request = analytics_admin.ListConnectedSiteTagsRequest( + property="property_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" + type(client.transport.list_connected_site_tags), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_event_create_rule(request=request) + client.list_connected_site_tags(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() + assert args[0] == analytics_admin.ListConnectedSiteTagsRequest( + property="property_value", + ) -def test_update_event_create_rule_use_cached_wrapped_rpc(): +def test_list_connected_site_tags_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -49422,7 +49142,7 @@ def test_update_event_create_rule_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_event_create_rule + client._transport.list_connected_site_tags in client._transport._wrapped_methods ) @@ -49432,15 +49152,15 @@ def test_update_event_create_rule_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_event_create_rule + client._transport.list_connected_site_tags ] = mock_rpc request = {} - client.update_event_create_rule(request) + client.list_connected_site_tags(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_event_create_rule(request) + client.list_connected_site_tags(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -49448,7 +49168,7 @@ def test_update_event_create_rule_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_event_create_rule_empty_call_async(): +async def test_list_connected_site_tags_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -49458,24 +49178,20 @@ async def test_update_event_create_rule_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" + type(client.transport.list_connected_site_tags), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) + analytics_admin.ListConnectedSiteTagsResponse() ) - response = await client.update_event_create_rule() + response = await client.list_connected_site_tags() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() + assert args[0] == analytics_admin.ListConnectedSiteTagsRequest() @pytest.mark.asyncio -async def test_update_event_create_rule_async_use_cached_wrapped_rpc( +async def test_list_connected_site_tags_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -49492,23 +49208,23 @@ async def test_update_event_create_rule_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_event_create_rule + client._client._transport.list_connected_site_tags in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_event_create_rule + client._client._transport.list_connected_site_tags ] = mock_object request = {} - await client.update_event_create_rule(request) + await client.list_connected_site_tags(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_event_create_rule(request) + await client.list_connected_site_tags(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -49516,9 +49232,9 @@ async def test_update_event_create_rule_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_event_create_rule_async( +async def test_list_connected_site_tags_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateEventCreateRuleRequest, + request_type=analytics_admin.ListConnectedSiteTagsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -49531,205 +49247,37 @@ async def test_update_event_create_rule_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" + type(client.transport.list_connected_site_tags), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) + analytics_admin.ListConnectedSiteTagsResponse() ) - response = await client.update_event_create_rule(request) + response = await client.list_connected_site_tags(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateEventCreateRuleRequest() + request = analytics_admin.ListConnectedSiteTagsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) - assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True - - -@pytest.mark.asyncio -async def test_update_event_create_rule_async_from_dict(): - await test_update_event_create_rule_async(request_type=dict) - - -def test_update_event_create_rule_field_headers(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateEventCreateRuleRequest() - - request.event_create_rule.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" - ) as call: - call.return_value = event_create_and_edit.EventCreateRule() - client.update_event_create_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "event_create_rule.name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_update_event_create_rule_field_headers_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateEventCreateRuleRequest() - - request.event_create_rule.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule() - ) - await client.update_event_create_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "event_create_rule.name=name_value", - ) in kw["metadata"] - - -def test_update_event_create_rule_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_event_create_rule( - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].event_create_rule - mock_val = event_create_and_edit.EventCreateRule(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_event_create_rule_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_event_create_rule( - analytics_admin.UpdateEventCreateRuleRequest(), - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_event_create_rule_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_event_create_rule), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = event_create_and_edit.EventCreateRule() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - event_create_and_edit.EventCreateRule() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_event_create_rule( - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].event_create_rule - mock_val = event_create_and_edit.EventCreateRule(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val + assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) @pytest.mark.asyncio -async def test_update_event_create_rule_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_event_create_rule( - analytics_admin.UpdateEventCreateRuleRequest(), - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) +async def test_list_connected_site_tags_async_from_dict(): + await test_list_connected_site_tags_async(request_type=dict) @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteEventCreateRuleRequest, + analytics_admin.FetchConnectedGa4PropertyRequest, dict, ], ) -def test_delete_event_create_rule(request_type, transport: str = "grpc"): +def test_fetch_connected_ga4_property(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -49741,23 +49289,26 @@ def test_delete_event_create_rule(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" + type(client.transport.fetch_connected_ga4_property), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_event_create_rule(request) + call.return_value = analytics_admin.FetchConnectedGa4PropertyResponse( + property="property_value", + ) + response = client.fetch_connected_ga4_property(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteEventCreateRuleRequest() + request = analytics_admin.FetchConnectedGa4PropertyRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) + assert response.property == "property_value" -def test_delete_event_create_rule_empty_call(): +def test_fetch_connected_ga4_property_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -49767,18 +49318,18 @@ def test_delete_event_create_rule_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" + type(client.transport.fetch_connected_ga4_property), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_event_create_rule() + client.fetch_connected_ga4_property() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteEventCreateRuleRequest() + assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest() -def test_delete_event_create_rule_non_empty_request_with_auto_populated_field(): +def test_fetch_connected_ga4_property_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -49789,26 +49340,26 @@ def test_delete_event_create_rule_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteEventCreateRuleRequest( - name="name_value", + request = analytics_admin.FetchConnectedGa4PropertyRequest( + property="property_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" + type(client.transport.fetch_connected_ga4_property), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_event_create_rule(request=request) + client.fetch_connected_ga4_property(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteEventCreateRuleRequest( - name="name_value", + assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest( + property="property_value", ) -def test_delete_event_create_rule_use_cached_wrapped_rpc(): +def test_fetch_connected_ga4_property_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -49823,7 +49374,7 @@ def test_delete_event_create_rule_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_event_create_rule + client._transport.fetch_connected_ga4_property in client._transport._wrapped_methods ) @@ -49833,15 +49384,15 @@ def test_delete_event_create_rule_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_event_create_rule + client._transport.fetch_connected_ga4_property ] = mock_rpc request = {} - client.delete_event_create_rule(request) + client.fetch_connected_ga4_property(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_event_create_rule(request) + client.fetch_connected_ga4_property(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -49849,7 +49400,7 @@ def test_delete_event_create_rule_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_event_create_rule_empty_call_async(): +async def test_fetch_connected_ga4_property_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -49859,18 +49410,22 @@ async def test_delete_event_create_rule_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" + type(client.transport.fetch_connected_ga4_property), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_event_create_rule() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.FetchConnectedGa4PropertyResponse( + property="property_value", + ) + ) + response = await client.fetch_connected_ga4_property() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteEventCreateRuleRequest() + assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest() @pytest.mark.asyncio -async def test_delete_event_create_rule_async_use_cached_wrapped_rpc( +async def test_fetch_connected_ga4_property_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -49887,23 +49442,23 @@ async def test_delete_event_create_rule_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_event_create_rule + client._client._transport.fetch_connected_ga4_property in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_event_create_rule + client._client._transport.fetch_connected_ga4_property ] = mock_object request = {} - await client.delete_event_create_rule(request) + await client.fetch_connected_ga4_property(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_event_create_rule(request) + await client.fetch_connected_ga4_property(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -49911,9 +49466,9 @@ async def test_delete_event_create_rule_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_event_create_rule_async( +async def test_fetch_connected_ga4_property_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteEventCreateRuleRequest, + request_type=analytics_admin.FetchConnectedGa4PropertyRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -49926,219 +49481,73 @@ async def test_delete_event_create_rule_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" + type(client.transport.fetch_connected_ga4_property), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_event_create_rule(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.FetchConnectedGa4PropertyResponse( + property="property_value", + ) + ) + response = await client.fetch_connected_ga4_property(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteEventCreateRuleRequest() + request = analytics_admin.FetchConnectedGa4PropertyRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) + assert response.property == "property_value" @pytest.mark.asyncio -async def test_delete_event_create_rule_async_from_dict(): - await test_delete_event_create_rule_async(request_type=dict) +async def test_fetch_connected_ga4_property_async_from_dict(): + await test_fetch_connected_ga4_property_async(request_type=dict) -def test_delete_event_create_rule_field_headers(): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetAdSenseLinkRequest, + dict, + ], +) +def test_get_ad_sense_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteEventCreateRuleRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" - ) as call: - call.return_value = None - client.delete_event_create_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_delete_event_create_rule_field_headers_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteEventCreateRuleRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_event_create_rule(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "name=name_value", - ) in kw["metadata"] - - -def test_delete_event_create_rule_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_event_create_rule( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -def test_delete_event_create_rule_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_event_create_rule( - analytics_admin.DeleteEventCreateRuleRequest(), - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_delete_event_create_rule_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_event_create_rule), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_event_create_rule( - name="name_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_delete_event_create_rule_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_event_create_rule( - analytics_admin.DeleteEventCreateRuleRequest(), - name="name_value", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.UpdateDataRedactionSettingsRequest, - dict, - ], -) -def test_update_data_redaction_settings(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRedactionSettings( + call.return_value = resources.AdSenseLink( name="name_value", - email_redaction_enabled=True, - query_parameter_redaction_enabled=True, - query_parameter_keys=["query_parameter_keys_value"], + ad_client_code="ad_client_code_value", ) - response = client.update_data_redaction_settings(request) + response = client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDataRedactionSettingsRequest() + request = analytics_admin.GetAdSenseLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRedactionSettings) + assert isinstance(response, resources.AdSenseLink) assert response.name == "name_value" - assert response.email_redaction_enabled is True - assert response.query_parameter_redaction_enabled is True - assert response.query_parameter_keys == ["query_parameter_keys_value"] + assert response.ad_client_code == "ad_client_code_value" -def test_update_data_redaction_settings_empty_call(): +def test_get_ad_sense_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -50148,18 +49557,18 @@ def test_update_data_redaction_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_redaction_settings() + client.get_ad_sense_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() + assert args[0] == analytics_admin.GetAdSenseLinkRequest() -def test_update_data_redaction_settings_non_empty_request_with_auto_populated_field(): +def test_get_ad_sense_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -50170,22 +49579,26 @@ def test_update_data_redaction_settings_non_empty_request_with_auto_populated_fi # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateDataRedactionSettingsRequest() + request = analytics_admin.GetAdSenseLinkRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_redaction_settings(request=request) + client.get_ad_sense_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() + assert args[0] == analytics_admin.GetAdSenseLinkRequest( + name="name_value", + ) -def test_update_data_redaction_settings_use_cached_wrapped_rpc(): +def test_get_ad_sense_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -50199,10 +49612,7 @@ def test_update_data_redaction_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_data_redaction_settings - in client._transport._wrapped_methods - ) + assert client._transport.get_ad_sense_link in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -50210,15 +49620,15 @@ def test_update_data_redaction_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_data_redaction_settings + client._transport.get_ad_sense_link ] = mock_rpc request = {} - client.update_data_redaction_settings(request) + client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_redaction_settings(request) + client.get_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -50226,7 +49636,7 @@ def test_update_data_redaction_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_data_redaction_settings_empty_call_async(): +async def test_get_ad_sense_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -50236,25 +49646,23 @@ async def test_update_data_redaction_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings( + resources.AdSenseLink( name="name_value", - email_redaction_enabled=True, - query_parameter_redaction_enabled=True, - query_parameter_keys=["query_parameter_keys_value"], + ad_client_code="ad_client_code_value", ) ) - response = await client.update_data_redaction_settings() + response = await client.get_ad_sense_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() + assert args[0] == analytics_admin.GetAdSenseLinkRequest() @pytest.mark.asyncio -async def test_update_data_redaction_settings_async_use_cached_wrapped_rpc( +async def test_get_ad_sense_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -50271,23 +49679,23 @@ async def test_update_data_redaction_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_data_redaction_settings + client._client._transport.get_ad_sense_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_data_redaction_settings + client._client._transport.get_ad_sense_link ] = mock_object request = {} - await client.update_data_redaction_settings(request) + await client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_data_redaction_settings(request) + await client.get_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -50295,9 +49703,8 @@ async def test_update_data_redaction_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_data_redaction_settings_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateDataRedactionSettingsRequest, +async def test_get_ad_sense_link_async( + transport: str = "grpc_asyncio", request_type=analytics_admin.GetAdSenseLinkRequest ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -50310,55 +49717,51 @@ async def test_update_data_redaction_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings( + resources.AdSenseLink( name="name_value", - email_redaction_enabled=True, - query_parameter_redaction_enabled=True, - query_parameter_keys=["query_parameter_keys_value"], + ad_client_code="ad_client_code_value", ) ) - response = await client.update_data_redaction_settings(request) + response = await client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateDataRedactionSettingsRequest() + request = analytics_admin.GetAdSenseLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRedactionSettings) + assert isinstance(response, resources.AdSenseLink) assert response.name == "name_value" - assert response.email_redaction_enabled is True - assert response.query_parameter_redaction_enabled is True - assert response.query_parameter_keys == ["query_parameter_keys_value"] + assert response.ad_client_code == "ad_client_code_value" @pytest.mark.asyncio -async def test_update_data_redaction_settings_async_from_dict(): - await test_update_data_redaction_settings_async(request_type=dict) +async def test_get_ad_sense_link_async_from_dict(): + await test_get_ad_sense_link_async(request_type=dict) -def test_update_data_redaction_settings_field_headers(): +def test_get_ad_sense_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDataRedactionSettingsRequest() + request = analytics_admin.GetAdSenseLinkRequest() - request.data_redaction_settings.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: - call.return_value = resources.DataRedactionSettings() - client.update_data_redaction_settings(request) + call.return_value = resources.AdSenseLink() + client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -50369,30 +49772,30 @@ def test_update_data_redaction_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_redaction_settings.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_data_redaction_settings_field_headers_async(): +async def test_get_ad_sense_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateDataRedactionSettingsRequest() + request = analytics_admin.GetAdSenseLinkRequest() - request.data_redaction_settings.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings() + resources.AdSenseLink() ) - await client.update_data_redaction_settings(request) + await client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -50403,41 +49806,37 @@ async def test_update_data_redaction_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_redaction_settings.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_data_redaction_settings_flattened(): +def test_get_ad_sense_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRedactionSettings() + call.return_value = resources.AdSenseLink() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_data_redaction_settings( - data_redaction_settings=resources.DataRedactionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_ad_sense_link( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].data_redaction_settings - mock_val = resources.DataRedactionSettings(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_data_redaction_settings_flattened_error(): +def test_get_ad_sense_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -50445,50 +49844,45 @@ def test_update_data_redaction_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_redaction_settings( - analytics_admin.UpdateDataRedactionSettingsRequest(), - data_redaction_settings=resources.DataRedactionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_ad_sense_link( + analytics_admin.GetAdSenseLinkRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_data_redaction_settings_flattened_async(): +async def test_get_ad_sense_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_redaction_settings), "__call__" + type(client.transport.get_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRedactionSettings() + call.return_value = resources.AdSenseLink() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings() + resources.AdSenseLink() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_data_redaction_settings( - data_redaction_settings=resources.DataRedactionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_ad_sense_link( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].data_redaction_settings - mock_val = resources.DataRedactionSettings(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_data_redaction_settings_flattened_error_async(): +async def test_get_ad_sense_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -50496,21 +49890,20 @@ async def test_update_data_redaction_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_data_redaction_settings( - analytics_admin.UpdateDataRedactionSettingsRequest(), - data_redaction_settings=resources.DataRedactionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_ad_sense_link( + analytics_admin.GetAdSenseLinkRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDataRedactionSettingsRequest, + analytics_admin.CreateAdSenseLinkRequest, dict, ], ) -def test_get_data_redaction_settings(request_type, transport: str = "grpc"): +def test_create_ad_sense_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -50522,32 +49915,28 @@ def test_get_data_redaction_settings(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRedactionSettings( + call.return_value = resources.AdSenseLink( name="name_value", - email_redaction_enabled=True, - query_parameter_redaction_enabled=True, - query_parameter_keys=["query_parameter_keys_value"], + ad_client_code="ad_client_code_value", ) - response = client.get_data_redaction_settings(request) + response = client.create_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDataRedactionSettingsRequest() + request = analytics_admin.CreateAdSenseLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRedactionSettings) + assert isinstance(response, resources.AdSenseLink) assert response.name == "name_value" - assert response.email_redaction_enabled is True - assert response.query_parameter_redaction_enabled is True - assert response.query_parameter_keys == ["query_parameter_keys_value"] + assert response.ad_client_code == "ad_client_code_value" -def test_get_data_redaction_settings_empty_call(): +def test_create_ad_sense_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -50557,18 +49946,18 @@ def test_get_data_redaction_settings_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_redaction_settings() + client.create_ad_sense_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataRedactionSettingsRequest() + assert args[0] == analytics_admin.CreateAdSenseLinkRequest() -def test_get_data_redaction_settings_non_empty_request_with_auto_populated_field(): +def test_create_ad_sense_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -50579,26 +49968,26 @@ def test_get_data_redaction_settings_non_empty_request_with_auto_populated_field # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetDataRedactionSettingsRequest( - name="name_value", + request = analytics_admin.CreateAdSenseLinkRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_redaction_settings(request=request) + client.create_ad_sense_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataRedactionSettingsRequest( - name="name_value", + assert args[0] == analytics_admin.CreateAdSenseLinkRequest( + parent="parent_value", ) -def test_get_data_redaction_settings_use_cached_wrapped_rpc(): +def test_create_ad_sense_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -50613,8 +50002,7 @@ def test_get_data_redaction_settings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_data_redaction_settings - in client._transport._wrapped_methods + client._transport.create_ad_sense_link in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -50623,15 +50011,15 @@ def test_get_data_redaction_settings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_data_redaction_settings + client._transport.create_ad_sense_link ] = mock_rpc request = {} - client.get_data_redaction_settings(request) + client.create_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_redaction_settings(request) + client.create_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -50639,7 +50027,7 @@ def test_get_data_redaction_settings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_data_redaction_settings_empty_call_async(): +async def test_create_ad_sense_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -50649,25 +50037,23 @@ async def test_get_data_redaction_settings_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings( + resources.AdSenseLink( name="name_value", - email_redaction_enabled=True, - query_parameter_redaction_enabled=True, - query_parameter_keys=["query_parameter_keys_value"], + ad_client_code="ad_client_code_value", ) ) - response = await client.get_data_redaction_settings() + response = await client.create_ad_sense_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetDataRedactionSettingsRequest() + assert args[0] == analytics_admin.CreateAdSenseLinkRequest() @pytest.mark.asyncio -async def test_get_data_redaction_settings_async_use_cached_wrapped_rpc( +async def test_create_ad_sense_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -50684,23 +50070,23 @@ async def test_get_data_redaction_settings_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_data_redaction_settings + client._client._transport.create_ad_sense_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_data_redaction_settings + client._client._transport.create_ad_sense_link ] = mock_object request = {} - await client.get_data_redaction_settings(request) + await client.create_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_data_redaction_settings(request) + await client.create_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -50708,9 +50094,9 @@ async def test_get_data_redaction_settings_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_data_redaction_settings_async( +async def test_create_ad_sense_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetDataRedactionSettingsRequest, + request_type=analytics_admin.CreateAdSenseLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -50723,55 +50109,51 @@ async def test_get_data_redaction_settings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings( + resources.AdSenseLink( name="name_value", - email_redaction_enabled=True, - query_parameter_redaction_enabled=True, - query_parameter_keys=["query_parameter_keys_value"], + ad_client_code="ad_client_code_value", ) ) - response = await client.get_data_redaction_settings(request) + response = await client.create_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetDataRedactionSettingsRequest() + request = analytics_admin.CreateAdSenseLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRedactionSettings) + assert isinstance(response, resources.AdSenseLink) assert response.name == "name_value" - assert response.email_redaction_enabled is True - assert response.query_parameter_redaction_enabled is True - assert response.query_parameter_keys == ["query_parameter_keys_value"] + assert response.ad_client_code == "ad_client_code_value" @pytest.mark.asyncio -async def test_get_data_redaction_settings_async_from_dict(): - await test_get_data_redaction_settings_async(request_type=dict) +async def test_create_ad_sense_link_async_from_dict(): + await test_create_ad_sense_link_async(request_type=dict) -def test_get_data_redaction_settings_field_headers(): +def test_create_ad_sense_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDataRedactionSettingsRequest() + request = analytics_admin.CreateAdSenseLinkRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: - call.return_value = resources.DataRedactionSettings() - client.get_data_redaction_settings(request) + call.return_value = resources.AdSenseLink() + client.create_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -50782,30 +50164,30 @@ def test_get_data_redaction_settings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_data_redaction_settings_field_headers_async(): +async def test_create_ad_sense_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetDataRedactionSettingsRequest() + request = analytics_admin.CreateAdSenseLinkRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings() + resources.AdSenseLink() ) - await client.get_data_redaction_settings(request) + await client.create_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -50816,37 +50198,41 @@ async def test_get_data_redaction_settings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_data_redaction_settings_flattened(): +def test_create_ad_sense_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRedactionSettings() + call.return_value = resources.AdSenseLink() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_data_redaction_settings( - name="name_value", + client.create_ad_sense_link( + parent="parent_value", + adsense_link=resources.AdSenseLink(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].adsense_link + mock_val = resources.AdSenseLink(name="name_value") assert arg == mock_val -def test_get_data_redaction_settings_flattened_error(): +def test_create_ad_sense_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -50854,45 +50240,50 @@ def test_get_data_redaction_settings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_redaction_settings( - analytics_admin.GetDataRedactionSettingsRequest(), - name="name_value", + client.create_ad_sense_link( + analytics_admin.CreateAdSenseLinkRequest(), + parent="parent_value", + adsense_link=resources.AdSenseLink(name="name_value"), ) @pytest.mark.asyncio -async def test_get_data_redaction_settings_flattened_async(): +async def test_create_ad_sense_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_redaction_settings), "__call__" + type(client.transport.create_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.DataRedactionSettings() + call.return_value = resources.AdSenseLink() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.DataRedactionSettings() + resources.AdSenseLink() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_data_redaction_settings( - name="name_value", + response = await client.create_ad_sense_link( + parent="parent_value", + adsense_link=resources.AdSenseLink(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].adsense_link + mock_val = resources.AdSenseLink(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_get_data_redaction_settings_flattened_error_async(): +async def test_create_ad_sense_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -50900,20 +50291,21 @@ async def test_get_data_redaction_settings_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_data_redaction_settings( - analytics_admin.GetDataRedactionSettingsRequest(), - name="name_value", + await client.create_ad_sense_link( + analytics_admin.CreateAdSenseLinkRequest(), + parent="parent_value", + adsense_link=resources.AdSenseLink(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetCalculatedMetricRequest, + analytics_admin.DeleteAdSenseLinkRequest, dict, ], ) -def test_get_calculated_metric(request_type, transport: str = "grpc"): +def test_delete_ad_sense_link(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -50925,44 +50317,23 @@ def test_get_calculated_metric(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, - ) - response = client.get_calculated_metric(request) + call.return_value = None + response = client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetCalculatedMetricRequest() + request = analytics_admin.DeleteAdSenseLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CalculatedMetric) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" - assert response.calculated_metric_id == "calculated_metric_id_value" - assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD - assert response.restricted_metric_type == [ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ] - assert response.formula == "formula_value" - assert response.invalid_metric_reference is True + assert response is None -def test_get_calculated_metric_empty_call(): +def test_delete_ad_sense_link_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -50972,18 +50343,18 @@ def test_get_calculated_metric_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_calculated_metric() + client.delete_ad_sense_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCalculatedMetricRequest() + assert args[0] == analytics_admin.DeleteAdSenseLinkRequest() -def test_get_calculated_metric_non_empty_request_with_auto_populated_field(): +def test_delete_ad_sense_link_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -50994,26 +50365,26 @@ def test_get_calculated_metric_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetCalculatedMetricRequest( + request = analytics_admin.DeleteAdSenseLinkRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_calculated_metric(request=request) + client.delete_ad_sense_link(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCalculatedMetricRequest( + assert args[0] == analytics_admin.DeleteAdSenseLinkRequest( name="name_value", ) -def test_get_calculated_metric_use_cached_wrapped_rpc(): +def test_delete_ad_sense_link_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -51028,8 +50399,7 @@ def test_get_calculated_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_calculated_metric - in client._transport._wrapped_methods + client._transport.delete_ad_sense_link in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -51038,15 +50408,15 @@ def test_get_calculated_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_calculated_metric + client._transport.delete_ad_sense_link ] = mock_rpc request = {} - client.get_calculated_metric(request) + client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_calculated_metric(request) + client.delete_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -51054,7 +50424,7 @@ def test_get_calculated_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_calculated_metric_empty_call_async(): +async def test_delete_ad_sense_link_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -51064,31 +50434,18 @@ async def test_get_calculated_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, - ) - ) - response = await client.get_calculated_metric() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_ad_sense_link() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetCalculatedMetricRequest() + assert args[0] == analytics_admin.DeleteAdSenseLinkRequest() @pytest.mark.asyncio -async def test_get_calculated_metric_async_use_cached_wrapped_rpc( +async def test_delete_ad_sense_link_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -51105,23 +50462,23 @@ async def test_get_calculated_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_calculated_metric + client._client._transport.delete_ad_sense_link in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_calculated_metric + client._client._transport.delete_ad_sense_link ] = mock_object request = {} - await client.get_calculated_metric(request) + await client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_calculated_metric(request) + await client.delete_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -51129,9 +50486,9 @@ async def test_get_calculated_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_calculated_metric_async( +async def test_delete_ad_sense_link_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetCalculatedMetricRequest, + request_type=analytics_admin.DeleteAdSenseLinkRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -51144,67 +50501,44 @@ async def test_get_calculated_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, - ) - ) - response = await client.get_calculated_metric(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetCalculatedMetricRequest() + request = analytics_admin.DeleteAdSenseLinkRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CalculatedMetric) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" - assert response.calculated_metric_id == "calculated_metric_id_value" - assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD - assert response.restricted_metric_type == [ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ] - assert response.formula == "formula_value" - assert response.invalid_metric_reference is True + assert response is None @pytest.mark.asyncio -async def test_get_calculated_metric_async_from_dict(): - await test_get_calculated_metric_async(request_type=dict) +async def test_delete_ad_sense_link_async_from_dict(): + await test_delete_ad_sense_link_async(request_type=dict) -def test_get_calculated_metric_field_headers(): +def test_delete_ad_sense_link_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetCalculatedMetricRequest() + request = analytics_admin.DeleteAdSenseLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: - call.return_value = resources.CalculatedMetric() - client.get_calculated_metric(request) + call.return_value = None + client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -51220,25 +50554,23 @@ def test_get_calculated_metric_field_headers(): @pytest.mark.asyncio -async def test_get_calculated_metric_field_headers_async(): +async def test_delete_ad_sense_link_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetCalculatedMetricRequest() + request = analytics_admin.DeleteAdSenseLinkRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric() - ) - await client.get_calculated_metric(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -51253,20 +50585,20 @@ async def test_get_calculated_metric_field_headers_async(): ) in kw["metadata"] -def test_get_calculated_metric_flattened(): +def test_delete_ad_sense_link_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_calculated_metric( + client.delete_ad_sense_link( name="name_value", ) @@ -51279,7 +50611,7 @@ def test_get_calculated_metric_flattened(): assert arg == mock_val -def test_get_calculated_metric_flattened_error(): +def test_delete_ad_sense_link_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -51287,31 +50619,29 @@ def test_get_calculated_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_calculated_metric( - analytics_admin.GetCalculatedMetricRequest(), + client.delete_ad_sense_link( + analytics_admin.DeleteAdSenseLinkRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_calculated_metric_flattened_async(): +async def test_delete_ad_sense_link_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_calculated_metric), "__call__" + type(client.transport.delete_ad_sense_link), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_calculated_metric( + response = await client.delete_ad_sense_link( name="name_value", ) @@ -51325,7 +50655,7 @@ async def test_get_calculated_metric_flattened_async(): @pytest.mark.asyncio -async def test_get_calculated_metric_flattened_error_async(): +async def test_delete_ad_sense_link_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -51333,8 +50663,8 @@ async def test_get_calculated_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_calculated_metric( - analytics_admin.GetCalculatedMetricRequest(), + await client.delete_ad_sense_link( + analytics_admin.DeleteAdSenseLinkRequest(), name="name_value", ) @@ -51342,11 +50672,11 @@ async def test_get_calculated_metric_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateCalculatedMetricRequest, + analytics_admin.ListAdSenseLinksRequest, dict, ], ) -def test_create_calculated_metric(request_type, transport: str = "grpc"): +def test_list_ad_sense_links(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -51358,44 +50688,26 @@ def test_create_calculated_metric(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, + call.return_value = analytics_admin.ListAdSenseLinksResponse( + next_page_token="next_page_token_value", ) - response = client.create_calculated_metric(request) + response = client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateCalculatedMetricRequest() + request = analytics_admin.ListAdSenseLinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CalculatedMetric) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" - assert response.calculated_metric_id == "calculated_metric_id_value" - assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD - assert response.restricted_metric_type == [ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ] - assert response.formula == "formula_value" - assert response.invalid_metric_reference is True + assert isinstance(response, pagers.ListAdSenseLinksPager) + assert response.next_page_token == "next_page_token_value" -def test_create_calculated_metric_empty_call(): +def test_list_ad_sense_links_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -51405,18 +50717,18 @@ def test_create_calculated_metric_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_calculated_metric() + client.list_ad_sense_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCalculatedMetricRequest() + assert args[0] == analytics_admin.ListAdSenseLinksRequest() -def test_create_calculated_metric_non_empty_request_with_auto_populated_field(): +def test_list_ad_sense_links_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -51427,28 +50739,28 @@ def test_create_calculated_metric_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateCalculatedMetricRequest( + request = analytics_admin.ListAdSenseLinksRequest( parent="parent_value", - calculated_metric_id="calculated_metric_id_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_calculated_metric(request=request) + client.list_ad_sense_links(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCalculatedMetricRequest( + assert args[0] == analytics_admin.ListAdSenseLinksRequest( parent="parent_value", - calculated_metric_id="calculated_metric_id_value", + page_token="page_token_value", ) -def test_create_calculated_metric_use_cached_wrapped_rpc(): +def test_list_ad_sense_links_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -51463,8 +50775,7 @@ def test_create_calculated_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_calculated_metric - in client._transport._wrapped_methods + client._transport.list_ad_sense_links in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -51473,15 +50784,15 @@ def test_create_calculated_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_calculated_metric + client._transport.list_ad_sense_links ] = mock_rpc request = {} - client.create_calculated_metric(request) + client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_calculated_metric(request) + client.list_ad_sense_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -51489,7 +50800,7 @@ def test_create_calculated_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_calculated_metric_empty_call_async(): +async def test_list_ad_sense_links_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -51499,31 +50810,22 @@ async def test_create_calculated_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, + analytics_admin.ListAdSenseLinksResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_calculated_metric() + response = await client.list_ad_sense_links() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateCalculatedMetricRequest() + assert args[0] == analytics_admin.ListAdSenseLinksRequest() @pytest.mark.asyncio -async def test_create_calculated_metric_async_use_cached_wrapped_rpc( +async def test_list_ad_sense_links_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -51540,23 +50842,23 @@ async def test_create_calculated_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_calculated_metric + client._client._transport.list_ad_sense_links in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_calculated_metric + client._client._transport.list_ad_sense_links ] = mock_object request = {} - await client.create_calculated_metric(request) + await client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_calculated_metric(request) + await client.list_ad_sense_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -51564,9 +50866,9 @@ async def test_create_calculated_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_calculated_metric_async( +async def test_list_ad_sense_links_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateCalculatedMetricRequest, + request_type=analytics_admin.ListAdSenseLinksRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -51579,67 +50881,49 @@ async def test_create_calculated_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, + analytics_admin.ListAdSenseLinksResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_calculated_metric(request) + response = await client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateCalculatedMetricRequest() + request = analytics_admin.ListAdSenseLinksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CalculatedMetric) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" - assert response.calculated_metric_id == "calculated_metric_id_value" - assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD - assert response.restricted_metric_type == [ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ] - assert response.formula == "formula_value" - assert response.invalid_metric_reference is True + assert isinstance(response, pagers.ListAdSenseLinksAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_create_calculated_metric_async_from_dict(): - await test_create_calculated_metric_async(request_type=dict) +async def test_list_ad_sense_links_async_from_dict(): + await test_list_ad_sense_links_async(request_type=dict) -def test_create_calculated_metric_field_headers(): +def test_list_ad_sense_links_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateCalculatedMetricRequest() + request = analytics_admin.ListAdSenseLinksRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: - call.return_value = resources.CalculatedMetric() - client.create_calculated_metric(request) + call.return_value = analytics_admin.ListAdSenseLinksResponse() + client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -51655,25 +50939,25 @@ def test_create_calculated_metric_field_headers(): @pytest.mark.asyncio -async def test_create_calculated_metric_field_headers_async(): +async def test_list_ad_sense_links_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateCalculatedMetricRequest() + request = analytics_admin.ListAdSenseLinksRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric() + analytics_admin.ListAdSenseLinksResponse() ) - await client.create_calculated_metric(request) + await client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -51688,23 +50972,21 @@ async def test_create_calculated_metric_field_headers_async(): ) in kw["metadata"] -def test_create_calculated_metric_flattened(): +def test_list_ad_sense_links_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric() + call.return_value = analytics_admin.ListAdSenseLinksResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_calculated_metric( + client.list_ad_sense_links( parent="parent_value", - calculated_metric=resources.CalculatedMetric(name="name_value"), - calculated_metric_id="calculated_metric_id_value", ) # Establish that the underlying call was made with the expected @@ -51714,15 +50996,9 @@ def test_create_calculated_metric_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].calculated_metric - mock_val = resources.CalculatedMetric(name="name_value") - assert arg == mock_val - arg = args[0].calculated_metric_id - mock_val = "calculated_metric_id_value" - assert arg == mock_val -def test_create_calculated_metric_flattened_error(): +def test_list_ad_sense_links_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -51730,36 +51006,32 @@ def test_create_calculated_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_calculated_metric( - analytics_admin.CreateCalculatedMetricRequest(), + client.list_ad_sense_links( + analytics_admin.ListAdSenseLinksRequest(), parent="parent_value", - calculated_metric=resources.CalculatedMetric(name="name_value"), - calculated_metric_id="calculated_metric_id_value", ) @pytest.mark.asyncio -async def test_create_calculated_metric_flattened_async(): +async def test_list_ad_sense_links_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_calculated_metric), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric() + call.return_value = analytics_admin.ListAdSenseLinksResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric() + analytics_admin.ListAdSenseLinksResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_calculated_metric( + response = await client.list_ad_sense_links( parent="parent_value", - calculated_metric=resources.CalculatedMetric(name="name_value"), - calculated_metric_id="calculated_metric_id_value", ) # Establish that the underlying call was made with the expected @@ -51769,16 +51041,10 @@ async def test_create_calculated_metric_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].calculated_metric - mock_val = resources.CalculatedMetric(name="name_value") - assert arg == mock_val - arg = args[0].calculated_metric_id - mock_val = "calculated_metric_id_value" - assert arg == mock_val @pytest.mark.asyncio -async def test_create_calculated_metric_flattened_error_async(): +async def test_list_ad_sense_links_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -51786,77 +51052,281 @@ async def test_create_calculated_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_calculated_metric( - analytics_admin.CreateCalculatedMetricRequest(), + await client.list_ad_sense_links( + analytics_admin.ListAdSenseLinksRequest(), parent="parent_value", - calculated_metric=resources.CalculatedMetric(name="name_value"), - calculated_metric_id="calculated_metric_id_value", ) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.ListCalculatedMetricsRequest, - dict, - ], -) -def test_list_calculated_metrics(request_type, transport: str = "grpc"): +def test_list_ad_sense_links_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCalculatedMetricsResponse( - next_page_token="next_page_token_value", + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token="def", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, ) - response = client.list_calculated_metrics(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.ListCalculatedMetricsRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_ad_sense_links(request={}, retry=retry, timeout=timeout) - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCalculatedMetricsPager) - assert response.next_page_token == "next_page_token_value" + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AdSenseLink) for i in results) -def test_list_calculated_metrics_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. +def test_list_ad_sense_links_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.list_ad_sense_links), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_calculated_metrics() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCalculatedMetricsRequest() - - -def test_list_calculated_metrics_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token="def", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ad_sense_links(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_ad_sense_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token="def", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ad_sense_links( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.AdSenseLink) for i in responses) + + +@pytest.mark.asyncio +async def test_list_ad_sense_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token="def", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_ad_sense_links(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetEventCreateRuleRequest, + dict, + ], +) +def test_get_event_create_rule(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) + response = client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True + + +def test_get_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventCreateRuleRequest() + + +def test_get_event_create_rule_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) @@ -51864,28 +51334,26 @@ def test_list_calculated_metrics_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListCalculatedMetricsRequest( - parent="parent_value", - page_token="page_token_value", + request = analytics_admin.GetEventCreateRuleRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_calculated_metrics(request=request) + client.get_event_create_rule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCalculatedMetricsRequest( - parent="parent_value", - page_token="page_token_value", + assert args[0] == analytics_admin.GetEventCreateRuleRequest( + name="name_value", ) -def test_list_calculated_metrics_use_cached_wrapped_rpc(): +def test_get_event_create_rule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -51900,7 +51368,7 @@ def test_list_calculated_metrics_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_calculated_metrics + client._transport.get_event_create_rule in client._transport._wrapped_methods ) @@ -51910,15 +51378,15 @@ def test_list_calculated_metrics_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_calculated_metrics + client._transport.get_event_create_rule ] = mock_rpc request = {} - client.list_calculated_metrics(request) + client.get_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_calculated_metrics(request) + client.get_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -51926,7 +51394,7 @@ def test_list_calculated_metrics_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_calculated_metrics_empty_call_async(): +async def test_get_event_create_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -51936,22 +51404,24 @@ async def test_list_calculated_metrics_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCalculatedMetricsResponse( - next_page_token="next_page_token_value", + event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, ) ) - response = await client.list_calculated_metrics() + response = await client.get_event_create_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListCalculatedMetricsRequest() + assert args[0] == analytics_admin.GetEventCreateRuleRequest() @pytest.mark.asyncio -async def test_list_calculated_metrics_async_use_cached_wrapped_rpc( +async def test_get_event_create_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -51968,23 +51438,23 @@ async def test_list_calculated_metrics_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_calculated_metrics + client._client._transport.get_event_create_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_calculated_metrics + client._client._transport.get_event_create_rule ] = mock_object request = {} - await client.list_calculated_metrics(request) + await client.get_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_calculated_metrics(request) + await client.get_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -51992,9 +51462,9 @@ async def test_list_calculated_metrics_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_calculated_metrics_async( +async def test_get_event_create_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListCalculatedMetricsRequest, + request_type=analytics_admin.GetEventCreateRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -52007,49 +51477,53 @@ async def test_list_calculated_metrics_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCalculatedMetricsResponse( - next_page_token="next_page_token_value", + event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, ) ) - response = await client.list_calculated_metrics(request) + response = await client.get_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListCalculatedMetricsRequest() + request = analytics_admin.GetEventCreateRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCalculatedMetricsAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True @pytest.mark.asyncio -async def test_list_calculated_metrics_async_from_dict(): - await test_list_calculated_metrics_async(request_type=dict) +async def test_get_event_create_rule_async_from_dict(): + await test_get_event_create_rule_async(request_type=dict) -def test_list_calculated_metrics_field_headers(): +def test_get_event_create_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListCalculatedMetricsRequest() + request = analytics_admin.GetEventCreateRuleRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: - call.return_value = analytics_admin.ListCalculatedMetricsResponse() - client.list_calculated_metrics(request) + call.return_value = event_create_and_edit.EventCreateRule() + client.get_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -52060,30 +51534,30 @@ def test_list_calculated_metrics_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_calculated_metrics_field_headers_async(): +async def test_get_event_create_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListCalculatedMetricsRequest() + request = analytics_admin.GetEventCreateRuleRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCalculatedMetricsResponse() + event_create_and_edit.EventCreateRule() ) - await client.list_calculated_metrics(request) + await client.get_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -52094,37 +51568,37 @@ async def test_list_calculated_metrics_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_calculated_metrics_flattened(): +def test_get_event_create_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCalculatedMetricsResponse() + call.return_value = event_create_and_edit.EventCreateRule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_calculated_metrics( - parent="parent_value", + client.get_event_create_rule( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_calculated_metrics_flattened_error(): +def test_get_event_create_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -52132,45 +51606,45 @@ def test_list_calculated_metrics_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_calculated_metrics( - analytics_admin.ListCalculatedMetricsRequest(), - parent="parent_value", + client.get_event_create_rule( + analytics_admin.GetEventCreateRuleRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_calculated_metrics_flattened_async(): +async def test_get_event_create_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.get_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListCalculatedMetricsResponse() + call.return_value = event_create_and_edit.EventCreateRule() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListCalculatedMetricsResponse() + event_create_and_edit.EventCreateRule() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_calculated_metrics( - parent="parent_value", + response = await client.get_event_create_rule( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_calculated_metrics_flattened_error_async(): +async def test_get_event_create_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -52178,318 +51652,104 @@ async def test_list_calculated_metrics_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_calculated_metrics( - analytics_admin.ListCalculatedMetricsRequest(), - parent="parent_value", + await client.get_event_create_rule( + analytics_admin.GetEventCreateRuleRequest(), + name="name_value", ) -def test_list_calculated_metrics_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListEventCreateRulesRequest, + dict, + ], +) +def test_list_event_create_rules(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - next_page_token="abc", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[], - next_page_token="def", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventCreateRulesResponse( + next_page_token="next_page_token_value", ) - pager = client.list_calculated_metrics(request={}, retry=retry, timeout=timeout) + response = client.list_event_create_rules(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListEventCreateRulesRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CalculatedMetric) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventCreateRulesPager) + assert response.next_page_token == "next_page_token_value" -def test_list_calculated_metrics_pages(transport_name: str = "grpc"): +def test_list_event_create_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - next_page_token="abc", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[], - next_page_token="def", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.list_calculated_metrics(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.list_event_create_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventCreateRulesRequest() -@pytest.mark.asyncio -async def test_list_calculated_metrics_async_pager(): - client = AnalyticsAdminServiceAsyncClient( +def test_list_event_create_rules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ListEventCreateRulesRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_calculated_metrics), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - next_page_token="abc", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[], - next_page_token="def", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_calculated_metrics( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.CalculatedMetric) for i in responses) - - -@pytest.mark.asyncio -async def test_list_calculated_metrics_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_calculated_metrics), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - next_page_token="abc", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[], - next_page_token="def", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCalculatedMetricsResponse( - calculated_metrics=[ - resources.CalculatedMetric(), - resources.CalculatedMetric(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_calculated_metrics(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.UpdateCalculatedMetricRequest, - dict, - ], -) -def test_update_calculated_metric(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, - ) - response = client.update_calculated_metric(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateCalculatedMetricRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CalculatedMetric) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" - assert response.calculated_metric_id == "calculated_metric_id_value" - assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD - assert response.restricted_metric_type == [ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ] - assert response.formula == "formula_value" - assert response.invalid_metric_reference is True - - -def test_update_calculated_metric_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_calculated_metric() + client.list_event_create_rules(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() - - -def test_update_calculated_metric_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateCalculatedMetricRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + assert args[0] == analytics_admin.ListEventCreateRulesRequest( + parent="parent_value", + page_token="page_token_value", ) - client.update_calculated_metric(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() -def test_update_calculated_metric_use_cached_wrapped_rpc(): +def test_list_event_create_rules_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -52504,7 +51764,7 @@ def test_update_calculated_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_calculated_metric + client._transport.list_event_create_rules in client._transport._wrapped_methods ) @@ -52514,15 +51774,15 @@ def test_update_calculated_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_calculated_metric + client._transport.list_event_create_rules ] = mock_rpc request = {} - client.update_calculated_metric(request) + client.list_event_create_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_calculated_metric(request) + client.list_event_create_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -52530,7 +51790,7 @@ def test_update_calculated_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_calculated_metric_empty_call_async(): +async def test_list_event_create_rules_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -52540,31 +51800,22 @@ async def test_update_calculated_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, + analytics_admin.ListEventCreateRulesResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_calculated_metric() + response = await client.list_event_create_rules() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() + assert args[0] == analytics_admin.ListEventCreateRulesRequest() @pytest.mark.asyncio -async def test_update_calculated_metric_async_use_cached_wrapped_rpc( +async def test_list_event_create_rules_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -52581,23 +51832,23 @@ async def test_update_calculated_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_calculated_metric + client._client._transport.list_event_create_rules in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_calculated_metric + client._client._transport.list_event_create_rules ] = mock_object request = {} - await client.update_calculated_metric(request) + await client.list_event_create_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_calculated_metric(request) + await client.list_event_create_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -52605,9 +51856,9 @@ async def test_update_calculated_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_calculated_metric_async( +async def test_list_event_create_rules_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateCalculatedMetricRequest, + request_type=analytics_admin.ListEventCreateRulesRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -52620,67 +51871,49 @@ async def test_update_calculated_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric( - name="name_value", - description="description_value", - display_name="display_name_value", - calculated_metric_id="calculated_metric_id_value", - metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, - restricted_metric_type=[ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ], - formula="formula_value", - invalid_metric_reference=True, + analytics_admin.ListEventCreateRulesResponse( + next_page_token="next_page_token_value", ) ) - response = await client.update_calculated_metric(request) + response = await client.list_event_create_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateCalculatedMetricRequest() + request = analytics_admin.ListEventCreateRulesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CalculatedMetric) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.display_name == "display_name_value" - assert response.calculated_metric_id == "calculated_metric_id_value" - assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD - assert response.restricted_metric_type == [ - resources.CalculatedMetric.RestrictedMetricType.COST_DATA - ] - assert response.formula == "formula_value" - assert response.invalid_metric_reference is True + assert isinstance(response, pagers.ListEventCreateRulesAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_update_calculated_metric_async_from_dict(): - await test_update_calculated_metric_async(request_type=dict) +async def test_list_event_create_rules_async_from_dict(): + await test_list_event_create_rules_async(request_type=dict) -def test_update_calculated_metric_field_headers(): +def test_list_event_create_rules_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateCalculatedMetricRequest() + request = analytics_admin.ListEventCreateRulesRequest() - request.calculated_metric.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: - call.return_value = resources.CalculatedMetric() - client.update_calculated_metric(request) + call.return_value = analytics_admin.ListEventCreateRulesResponse() + client.list_event_create_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -52691,30 +51924,30 @@ def test_update_calculated_metric_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "calculated_metric.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_calculated_metric_field_headers_async(): +async def test_list_event_create_rules_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateCalculatedMetricRequest() + request = analytics_admin.ListEventCreateRulesRequest() - request.calculated_metric.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric() + analytics_admin.ListEventCreateRulesResponse() ) - await client.update_calculated_metric(request) + await client.list_event_create_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -52725,41 +51958,37 @@ async def test_update_calculated_metric_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "calculated_metric.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_calculated_metric_flattened(): +def test_list_event_create_rules_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric() + call.return_value = analytics_admin.ListEventCreateRulesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_calculated_metric( - calculated_metric=resources.CalculatedMetric(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_event_create_rules( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].calculated_metric - mock_val = resources.CalculatedMetric(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_update_calculated_metric_flattened_error(): +def test_list_event_create_rules_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -52767,50 +51996,45 @@ def test_update_calculated_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_calculated_metric( - analytics_admin.UpdateCalculatedMetricRequest(), - calculated_metric=resources.CalculatedMetric(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_event_create_rules( + analytics_admin.ListEventCreateRulesRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_update_calculated_metric_flattened_async(): +async def test_list_event_create_rules_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CalculatedMetric() + call.return_value = analytics_admin.ListEventCreateRulesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CalculatedMetric() + analytics_admin.ListEventCreateRulesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_calculated_metric( - calculated_metric=resources.CalculatedMetric(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.list_event_create_rules( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].calculated_metric - mock_val = resources.CalculatedMetric(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_calculated_metric_flattened_error_async(): +async def test_list_event_create_rules_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -52818,105 +52042,317 @@ async def test_update_calculated_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_calculated_metric( - analytics_admin.UpdateCalculatedMetricRequest(), - calculated_metric=resources.CalculatedMetric(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.list_event_create_rules( + analytics_admin.ListEventCreateRulesRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.DeleteCalculatedMetricRequest, - dict, - ], -) -def test_delete_calculated_metric(request_type, transport: str = "grpc"): +def test_list_event_create_rules_pager(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_calculated_metric(request) + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteCalculatedMetricRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_event_create_rules(request={}, retry=retry, timeout=timeout) - # Establish that the response is the type that we expect. - assert response is None + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, event_create_and_edit.EventCreateRule) for i in results + ) -def test_delete_calculated_metric_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. + +def test_list_event_create_rules_pages(transport_name: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, ) - client.delete_calculated_metric() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteCalculatedMetricRequest() + pages = list(client.list_event_create_rules(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_delete_calculated_metric_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_list_event_create_rules_async_pager(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteCalculatedMetricRequest( - name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.list_event_create_rules), + "__call__", + new_callable=mock.AsyncMock, ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, ) - client.delete_calculated_metric(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteCalculatedMetricRequest( - name="name_value", + async_pager = await client.list_event_create_rules( + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + assert len(responses) == 6 + assert all( + isinstance(i, event_create_and_edit.EventCreateRule) for i in responses + ) -def test_delete_calculated_metric_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + +@pytest.mark.asyncio +async def test_list_event_create_rules_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_event_create_rules(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateEventCreateRuleRequest, + dict, + ], +) +def test_create_event_create_rule(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) + response = client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True + + +def test_create_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventCreateRuleRequest() + + +def test_create_event_create_rule_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.CreateEventCreateRuleRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_event_create_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventCreateRuleRequest( + parent="parent_value", + ) + + +def test_create_event_create_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) @@ -52926,7 +52362,7 @@ def test_delete_calculated_metric_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_calculated_metric + client._transport.create_event_create_rule in client._transport._wrapped_methods ) @@ -52936,15 +52372,15 @@ def test_delete_calculated_metric_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_calculated_metric + client._transport.create_event_create_rule ] = mock_rpc request = {} - client.delete_calculated_metric(request) + client.create_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_calculated_metric(request) + client.create_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -52952,7 +52388,7 @@ def test_delete_calculated_metric_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_calculated_metric_empty_call_async(): +async def test_create_event_create_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -52962,18 +52398,24 @@ async def test_delete_calculated_metric_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.create_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_calculated_metric() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) + ) + response = await client.create_event_create_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteCalculatedMetricRequest() + assert args[0] == analytics_admin.CreateEventCreateRuleRequest() @pytest.mark.asyncio -async def test_delete_calculated_metric_async_use_cached_wrapped_rpc( +async def test_create_event_create_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -52990,23 +52432,23 @@ async def test_delete_calculated_metric_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_calculated_metric + client._client._transport.create_event_create_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_calculated_metric + client._client._transport.create_event_create_rule ] = mock_object request = {} - await client.delete_calculated_metric(request) + await client.create_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_calculated_metric(request) + await client.create_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -53014,9 +52456,9 @@ async def test_delete_calculated_metric_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_calculated_metric_async( +async def test_create_event_create_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteCalculatedMetricRequest, + request_type=analytics_admin.CreateEventCreateRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -53029,44 +52471,53 @@ async def test_delete_calculated_metric_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.create_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_calculated_metric(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) + ) + response = await client.create_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteCalculatedMetricRequest() + request = analytics_admin.CreateEventCreateRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True @pytest.mark.asyncio -async def test_delete_calculated_metric_async_from_dict(): - await test_delete_calculated_metric_async(request_type=dict) +async def test_create_event_create_rule_async_from_dict(): + await test_create_event_create_rule_async(request_type=dict) -def test_delete_calculated_metric_field_headers(): +def test_create_event_create_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteCalculatedMetricRequest() + request = analytics_admin.CreateEventCreateRuleRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.create_event_create_rule), "__call__" ) as call: - call.return_value = None - client.delete_calculated_metric(request) + call.return_value = event_create_and_edit.EventCreateRule() + client.create_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -53077,28 +52528,30 @@ def test_delete_calculated_metric_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_calculated_metric_field_headers_async(): +async def test_create_event_create_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteCalculatedMetricRequest() + request = analytics_admin.CreateEventCreateRuleRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.create_event_create_rule), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_calculated_metric(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventCreateRule() + ) + await client.create_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -53109,37 +52562,41 @@ async def test_delete_calculated_metric_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_calculated_metric_flattened(): +def test_create_event_create_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.create_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = event_create_and_edit.EventCreateRule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_calculated_metric( - name="name_value", + client.create_event_create_rule( + parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name="name_value") assert arg == mock_val -def test_delete_calculated_metric_flattened_error(): +def test_create_event_create_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -53147,43 +52604,50 @@ def test_delete_calculated_metric_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_calculated_metric( - analytics_admin.DeleteCalculatedMetricRequest(), - name="name_value", + client.create_event_create_rule( + analytics_admin.CreateEventCreateRuleRequest(), + parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), ) @pytest.mark.asyncio -async def test_delete_calculated_metric_flattened_async(): +async def test_create_event_create_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_calculated_metric), "__call__" + type(client.transport.create_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = event_create_and_edit.EventCreateRule() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventCreateRule() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_calculated_metric( - name="name_value", + response = await client.create_event_create_rule( + parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_delete_calculated_metric_flattened_error_async(): +async def test_create_event_create_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -53191,20 +52655,21 @@ async def test_delete_calculated_metric_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_calculated_metric( - analytics_admin.DeleteCalculatedMetricRequest(), - name="name_value", + await client.create_event_create_rule( + analytics_admin.CreateEventCreateRuleRequest(), + parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateRollupPropertyRequest, + analytics_admin.UpdateEventCreateRuleRequest, dict, ], ) -def test_create_rollup_property(request_type, transport: str = "grpc"): +def test_update_event_create_rule(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -53216,23 +52681,30 @@ def test_create_rollup_property(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.CreateRollupPropertyResponse() - response = client.create_rollup_property(request) + call.return_value = event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) + response = client.update_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateRollupPropertyRequest() + request = analytics_admin.UpdateEventCreateRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True -def test_create_rollup_property_empty_call(): +def test_update_event_create_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -53242,18 +52714,18 @@ def test_create_rollup_property_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_rollup_property() + client.update_event_create_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateRollupPropertyRequest() + assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() -def test_create_rollup_property_non_empty_request_with_auto_populated_field(): +def test_update_event_create_rule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -53264,22 +52736,22 @@ def test_create_rollup_property_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateRollupPropertyRequest() + request = analytics_admin.UpdateEventCreateRuleRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_rollup_property(request=request) + client.update_event_create_rule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateRollupPropertyRequest() + assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() -def test_create_rollup_property_use_cached_wrapped_rpc(): +def test_update_event_create_rule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -53294,7 +52766,7 @@ def test_create_rollup_property_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_rollup_property + client._transport.update_event_create_rule in client._transport._wrapped_methods ) @@ -53304,15 +52776,15 @@ def test_create_rollup_property_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_rollup_property + client._transport.update_event_create_rule ] = mock_rpc request = {} - client.create_rollup_property(request) + client.update_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_rollup_property(request) + client.update_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -53320,7 +52792,7 @@ def test_create_rollup_property_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_rollup_property_empty_call_async(): +async def test_update_event_create_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -53330,20 +52802,24 @@ async def test_create_rollup_property_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.CreateRollupPropertyResponse() + event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) ) - response = await client.create_rollup_property() + response = await client.update_event_create_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateRollupPropertyRequest() + assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() @pytest.mark.asyncio -async def test_create_rollup_property_async_use_cached_wrapped_rpc( +async def test_update_event_create_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -53360,23 +52836,23 @@ async def test_create_rollup_property_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_rollup_property + client._client._transport.update_event_create_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_rollup_property + client._client._transport.update_event_create_rule ] = mock_object request = {} - await client.create_rollup_property(request) + await client.update_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_rollup_property(request) + await client.update_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -53384,9 +52860,9 @@ async def test_create_rollup_property_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_rollup_property_async( +async def test_update_event_create_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateRollupPropertyRequest, + request_type=analytics_admin.UpdateEventCreateRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -53399,122 +52875,285 @@ async def test_create_rollup_property_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.CreateRollupPropertyResponse() + event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) ) - response = await client.create_rollup_property(request) + response = await client.update_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateRollupPropertyRequest() + request = analytics_admin.UpdateEventCreateRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True @pytest.mark.asyncio -async def test_create_rollup_property_async_from_dict(): - await test_create_rollup_property_async(request_type=dict) +async def test_update_event_create_rule_async_from_dict(): + await test_update_event_create_rule_async(request_type=dict) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetRollupPropertySourceLinkRequest, - dict, - ], -) -def test_get_rollup_property_source_link(request_type, transport: str = "grpc"): +def test_update_event_create_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEventCreateRuleRequest() + + request.event_create_rule.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.RollupPropertySourceLink( - name="name_value", - source_property="source_property_value", - ) - response = client.get_rollup_property_source_link(request) + call.return_value = event_create_and_edit.EventCreateRule() + client.update_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetRollupPropertySourceLinkRequest() assert args[0] == request - # Establish that the response is the type that we expect. - assert isinstance(response, resources.RollupPropertySourceLink) - assert response.name == "name_value" - assert response.source_property == "source_property_value" + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "event_create_rule.name=name_value", + ) in kw["metadata"] -def test_get_rollup_property_source_link_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( +@pytest.mark.asyncio +async def test_update_event_create_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEventCreateRuleRequest() + + request.event_create_rule.name = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventCreateRule() ) - client.get_rollup_property_source_link() - call.assert_called() + await client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest() + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "event_create_rule.name=name_value", + ) in kw["metadata"] -def test_get_rollup_property_source_link_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. + +def test_update_event_create_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.GetRollupPropertySourceLinkRequest( - name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.update_event_create_rule), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event_create_rule( + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client.get_rollup_property_source_link(request=request) - call.assert_called() + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest( - name="name_value", - ) + arg = args[0].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_get_rollup_property_source_link_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, +def test_update_event_create_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event_create_rule( + analytics_admin.UpdateEventCreateRuleRequest(), + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_event_create_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventCreateRule() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event_create_rule( + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_event_create_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_event_create_rule( + analytics_admin.UpdateEventCreateRuleRequest(), + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteEventCreateRuleRequest, + dict, + ], +) +def test_delete_event_create_rule(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventCreateRuleRequest() + + +def test_delete_event_create_rule_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.DeleteEventCreateRuleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_event_create_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventCreateRuleRequest( + name="name_value", + ) + + +def test_delete_event_create_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = AnalyticsAdminServiceClient( @@ -53528,7 +53167,7 @@ def test_get_rollup_property_source_link_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_rollup_property_source_link + client._transport.delete_event_create_rule in client._transport._wrapped_methods ) @@ -53538,15 +53177,15 @@ def test_get_rollup_property_source_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_rollup_property_source_link + client._transport.delete_event_create_rule ] = mock_rpc request = {} - client.get_rollup_property_source_link(request) + client.delete_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_rollup_property_source_link(request) + client.delete_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -53554,7 +53193,7 @@ def test_get_rollup_property_source_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_rollup_property_source_link_empty_call_async(): +async def test_delete_event_create_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -53564,23 +53203,18 @@ async def test_get_rollup_property_source_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.delete_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink( - name="name_value", - source_property="source_property_value", - ) - ) - response = await client.get_rollup_property_source_link() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_create_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest() + assert args[0] == analytics_admin.DeleteEventCreateRuleRequest() @pytest.mark.asyncio -async def test_get_rollup_property_source_link_async_use_cached_wrapped_rpc( +async def test_delete_event_create_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -53597,23 +53231,23 @@ async def test_get_rollup_property_source_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_rollup_property_source_link + client._client._transport.delete_event_create_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_rollup_property_source_link + client._client._transport.delete_event_create_rule ] = mock_object request = {} - await client.get_rollup_property_source_link(request) + await client.delete_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_rollup_property_source_link(request) + await client.delete_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -53621,9 +53255,9 @@ async def test_get_rollup_property_source_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_rollup_property_source_link_async( +async def test_delete_event_create_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetRollupPropertySourceLinkRequest, + request_type=analytics_admin.DeleteEventCreateRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -53636,51 +53270,44 @@ async def test_get_rollup_property_source_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.delete_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink( - name="name_value", - source_property="source_property_value", - ) - ) - response = await client.get_rollup_property_source_link(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetRollupPropertySourceLinkRequest() + request = analytics_admin.DeleteEventCreateRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.RollupPropertySourceLink) - assert response.name == "name_value" - assert response.source_property == "source_property_value" + assert response is None @pytest.mark.asyncio -async def test_get_rollup_property_source_link_async_from_dict(): - await test_get_rollup_property_source_link_async(request_type=dict) +async def test_delete_event_create_rule_async_from_dict(): + await test_delete_event_create_rule_async(request_type=dict) -def test_get_rollup_property_source_link_field_headers(): +def test_delete_event_create_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetRollupPropertySourceLinkRequest() + request = analytics_admin.DeleteEventCreateRuleRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.delete_event_create_rule), "__call__" ) as call: - call.return_value = resources.RollupPropertySourceLink() - client.get_rollup_property_source_link(request) + call.return_value = None + client.delete_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -53696,25 +53323,23 @@ def test_get_rollup_property_source_link_field_headers(): @pytest.mark.asyncio -async def test_get_rollup_property_source_link_field_headers_async(): +async def test_delete_event_create_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetRollupPropertySourceLinkRequest() + request = analytics_admin.DeleteEventCreateRuleRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.delete_event_create_rule), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink() - ) - await client.get_rollup_property_source_link(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -53729,20 +53354,20 @@ async def test_get_rollup_property_source_link_field_headers_async(): ) in kw["metadata"] -def test_get_rollup_property_source_link_flattened(): +def test_delete_event_create_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.delete_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.RollupPropertySourceLink() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_rollup_property_source_link( + client.delete_event_create_rule( name="name_value", ) @@ -53755,7 +53380,7 @@ def test_get_rollup_property_source_link_flattened(): assert arg == mock_val -def test_get_rollup_property_source_link_flattened_error(): +def test_delete_event_create_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -53763,31 +53388,29 @@ def test_get_rollup_property_source_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_rollup_property_source_link( - analytics_admin.GetRollupPropertySourceLinkRequest(), + client.delete_event_create_rule( + analytics_admin.DeleteEventCreateRuleRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_rollup_property_source_link_flattened_async(): +async def test_delete_event_create_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_rollup_property_source_link), "__call__" + type(client.transport.delete_event_create_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.RollupPropertySourceLink() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_rollup_property_source_link( + response = await client.delete_event_create_rule( name="name_value", ) @@ -53801,7 +53424,7 @@ async def test_get_rollup_property_source_link_flattened_async(): @pytest.mark.asyncio -async def test_get_rollup_property_source_link_flattened_error_async(): +async def test_delete_event_create_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -53809,8 +53432,8 @@ async def test_get_rollup_property_source_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_rollup_property_source_link( - analytics_admin.GetRollupPropertySourceLinkRequest(), + await client.delete_event_create_rule( + analytics_admin.DeleteEventCreateRuleRequest(), name="name_value", ) @@ -53818,11 +53441,11 @@ async def test_get_rollup_property_source_link_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListRollupPropertySourceLinksRequest, + analytics_admin.GetEventEditRuleRequest, dict, ], ) -def test_list_rollup_property_source_links(request_type, transport: str = "grpc"): +def test_get_event_edit_rule(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -53834,26 +53457,30 @@ def test_list_rollup_property_source_links(request_type, transport: str = "grpc" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse( - next_page_token="next_page_token_value", + call.return_value = event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, ) - response = client.list_rollup_property_source_links(request) + response = client.get_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListRollupPropertySourceLinksRequest() + request = analytics_admin.GetEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRollupPropertySourceLinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 -def test_list_rollup_property_source_links_empty_call(): +def test_get_event_edit_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -53863,18 +53490,18 @@ def test_list_rollup_property_source_links_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_rollup_property_source_links() + client.get_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest() + assert args[0] == analytics_admin.GetEventEditRuleRequest() -def test_list_rollup_property_source_links_non_empty_request_with_auto_populated_field(): +def test_get_event_edit_rule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -53885,28 +53512,26 @@ def test_list_rollup_property_source_links_non_empty_request_with_auto_populated # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListRollupPropertySourceLinksRequest( - parent="parent_value", - page_token="page_token_value", + request = analytics_admin.GetEventEditRuleRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_rollup_property_source_links(request=request) + client.get_event_edit_rule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest( - parent="parent_value", - page_token="page_token_value", + assert args[0] == analytics_admin.GetEventEditRuleRequest( + name="name_value", ) -def test_list_rollup_property_source_links_use_cached_wrapped_rpc(): +def test_get_event_edit_rule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -53921,8 +53546,7 @@ def test_list_rollup_property_source_links_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_rollup_property_source_links - in client._transport._wrapped_methods + client._transport.get_event_edit_rule in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -53931,15 +53555,15 @@ def test_list_rollup_property_source_links_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_rollup_property_source_links + client._transport.get_event_edit_rule ] = mock_rpc request = {} - client.list_rollup_property_source_links(request) + client.get_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_rollup_property_source_links(request) + client.get_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -53947,7 +53571,7 @@ def test_list_rollup_property_source_links_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_rollup_property_source_links_empty_call_async(): +async def test_get_event_edit_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -53957,22 +53581,24 @@ async def test_list_rollup_property_source_links_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListRollupPropertySourceLinksResponse( - next_page_token="next_page_token_value", + event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, ) ) - response = await client.list_rollup_property_source_links() + response = await client.get_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest() + assert args[0] == analytics_admin.GetEventEditRuleRequest() @pytest.mark.asyncio -async def test_list_rollup_property_source_links_async_use_cached_wrapped_rpc( +async def test_get_event_edit_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -53989,23 +53615,23 @@ async def test_list_rollup_property_source_links_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_rollup_property_source_links + client._client._transport.get_event_edit_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_rollup_property_source_links + client._client._transport.get_event_edit_rule ] = mock_object request = {} - await client.list_rollup_property_source_links(request) + await client.get_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_rollup_property_source_links(request) + await client.get_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -54013,9 +53639,9 @@ async def test_list_rollup_property_source_links_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_rollup_property_source_links_async( +async def test_get_event_edit_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListRollupPropertySourceLinksRequest, + request_type=analytics_admin.GetEventEditRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -54028,49 +53654,53 @@ async def test_list_rollup_property_source_links_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListRollupPropertySourceLinksResponse( - next_page_token="next_page_token_value", + event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, ) ) - response = await client.list_rollup_property_source_links(request) + response = await client.get_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListRollupPropertySourceLinksRequest() + request = analytics_admin.GetEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRollupPropertySourceLinksAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 @pytest.mark.asyncio -async def test_list_rollup_property_source_links_async_from_dict(): - await test_list_rollup_property_source_links_async(request_type=dict) +async def test_get_event_edit_rule_async_from_dict(): + await test_get_event_edit_rule_async(request_type=dict) -def test_list_rollup_property_source_links_field_headers(): +def test_get_event_edit_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListRollupPropertySourceLinksRequest() + request = analytics_admin.GetEventEditRuleRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: - call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() - client.list_rollup_property_source_links(request) + call.return_value = event_create_and_edit.EventEditRule() + client.get_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -54081,30 +53711,30 @@ def test_list_rollup_property_source_links_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_rollup_property_source_links_field_headers_async(): +async def test_get_event_edit_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListRollupPropertySourceLinksRequest() + request = analytics_admin.GetEventEditRuleRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListRollupPropertySourceLinksResponse() + event_create_and_edit.EventEditRule() ) - await client.list_rollup_property_source_links(request) + await client.get_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -54115,37 +53745,37 @@ async def test_list_rollup_property_source_links_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_rollup_property_source_links_flattened(): +def test_get_event_edit_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + call.return_value = event_create_and_edit.EventEditRule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_rollup_property_source_links( - parent="parent_value", + client.get_event_edit_rule( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_rollup_property_source_links_flattened_error(): +def test_get_event_edit_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -54153,45 +53783,45 @@ def test_list_rollup_property_source_links_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_rollup_property_source_links( - analytics_admin.ListRollupPropertySourceLinksRequest(), - parent="parent_value", + client.get_event_edit_rule( + analytics_admin.GetEventEditRuleRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_rollup_property_source_links_flattened_async(): +async def test_get_event_edit_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.get_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + call.return_value = event_create_and_edit.EventEditRule() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListRollupPropertySourceLinksResponse() + event_create_and_edit.EventEditRule() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_rollup_property_source_links( - parent="parent_value", + response = await client.get_event_edit_rule( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_rollup_property_source_links_flattened_error_async(): +async def test_get_event_edit_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -54199,308 +53829,104 @@ async def test_list_rollup_property_source_links_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_rollup_property_source_links( - analytics_admin.ListRollupPropertySourceLinksRequest(), - parent="parent_value", + await client.get_event_edit_rule( + analytics_admin.GetEventEditRuleRequest(), + name="name_value", ) -def test_list_rollup_property_source_links_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListEventEditRulesRequest, + dict, + ], +) +def test_list_event_edit_rules(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[], - next_page_token="def", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_rollup_property_source_links( - request={}, retry=retry, timeout=timeout + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventEditRulesResponse( + next_page_token="next_page_token_value", ) + response = client.list_event_edit_rules(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListEventEditRulesRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.RollupPropertySourceLink) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventEditRulesPager) + assert response.next_page_token == "next_page_token_value" -def test_list_rollup_property_source_links_pages(transport_name: str = "grpc"): +def test_list_event_edit_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[], - next_page_token="def", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.list_rollup_property_source_links(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.list_event_edit_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventEditRulesRequest() -@pytest.mark.asyncio -async def test_list_rollup_property_source_links_async_pager(): - client = AnalyticsAdminServiceAsyncClient( +def test_list_event_edit_rules_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ListEventEditRulesRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_rollup_property_source_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[], - next_page_token="def", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_rollup_property_source_links( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, resources.RollupPropertySourceLink) for i in responses) - - -@pytest.mark.asyncio -async def test_list_rollup_property_source_links_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_rollup_property_source_links), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[], - next_page_token="def", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListRollupPropertySourceLinksResponse( - rollup_property_source_links=[ - resources.RollupPropertySourceLink(), - resources.RollupPropertySourceLink(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_rollup_property_source_links(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.CreateRollupPropertySourceLinkRequest, - dict, - ], -) -def test_create_rollup_property_source_link(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.RollupPropertySourceLink( - name="name_value", - source_property="source_property_value", - ) - response = client.create_rollup_property_source_link(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateRollupPropertySourceLinkRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.RollupPropertySourceLink) - assert response.name == "name_value" - assert response.source_property == "source_property_value" - - -def test_create_rollup_property_source_link_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_rollup_property_source_link() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest() - - -def test_create_rollup_property_source_link_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateRollupPropertySourceLinkRequest( - parent="parent_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_rollup_property_source_link(request=request) + client.list_event_edit_rules(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest( + assert args[0] == analytics_admin.ListEventEditRulesRequest( parent="parent_value", + page_token="page_token_value", ) -def test_create_rollup_property_source_link_use_cached_wrapped_rpc(): +def test_list_event_edit_rules_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -54515,7 +53941,7 @@ def test_create_rollup_property_source_link_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_rollup_property_source_link + client._transport.list_event_edit_rules in client._transport._wrapped_methods ) @@ -54525,15 +53951,15 @@ def test_create_rollup_property_source_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_rollup_property_source_link + client._transport.list_event_edit_rules ] = mock_rpc request = {} - client.create_rollup_property_source_link(request) + client.list_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_rollup_property_source_link(request) + client.list_event_edit_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -54541,7 +53967,7 @@ def test_create_rollup_property_source_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_rollup_property_source_link_empty_call_async(): +async def test_list_event_edit_rules_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -54551,23 +53977,22 @@ async def test_create_rollup_property_source_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink( - name="name_value", - source_property="source_property_value", + analytics_admin.ListEventEditRulesResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_rollup_property_source_link() + response = await client.list_event_edit_rules() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest() + assert args[0] == analytics_admin.ListEventEditRulesRequest() @pytest.mark.asyncio -async def test_create_rollup_property_source_link_async_use_cached_wrapped_rpc( +async def test_list_event_edit_rules_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -54584,23 +54009,23 @@ async def test_create_rollup_property_source_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_rollup_property_source_link + client._client._transport.list_event_edit_rules in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_rollup_property_source_link + client._client._transport.list_event_edit_rules ] = mock_object request = {} - await client.create_rollup_property_source_link(request) + await client.list_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_rollup_property_source_link(request) + await client.list_event_edit_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -54608,9 +54033,9 @@ async def test_create_rollup_property_source_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_rollup_property_source_link_async( +async def test_list_event_edit_rules_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateRollupPropertySourceLinkRequest, + request_type=analytics_admin.ListEventEditRulesRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -54623,51 +54048,49 @@ async def test_create_rollup_property_source_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink( - name="name_value", - source_property="source_property_value", + analytics_admin.ListEventEditRulesResponse( + next_page_token="next_page_token_value", ) ) - response = await client.create_rollup_property_source_link(request) + response = await client.list_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateRollupPropertySourceLinkRequest() + request = analytics_admin.ListEventEditRulesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.RollupPropertySourceLink) - assert response.name == "name_value" - assert response.source_property == "source_property_value" + assert isinstance(response, pagers.ListEventEditRulesAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_create_rollup_property_source_link_async_from_dict(): - await test_create_rollup_property_source_link_async(request_type=dict) +async def test_list_event_edit_rules_async_from_dict(): + await test_list_event_edit_rules_async(request_type=dict) -def test_create_rollup_property_source_link_field_headers(): +def test_list_event_edit_rules_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateRollupPropertySourceLinkRequest() + request = analytics_admin.ListEventEditRulesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: - call.return_value = resources.RollupPropertySourceLink() - client.create_rollup_property_source_link(request) + call.return_value = analytics_admin.ListEventEditRulesResponse() + client.list_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -54683,25 +54106,25 @@ def test_create_rollup_property_source_link_field_headers(): @pytest.mark.asyncio -async def test_create_rollup_property_source_link_field_headers_async(): +async def test_list_event_edit_rules_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateRollupPropertySourceLinkRequest() + request = analytics_admin.ListEventEditRulesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink() + analytics_admin.ListEventEditRulesResponse() ) - await client.create_rollup_property_source_link(request) + await client.list_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -54716,24 +54139,21 @@ async def test_create_rollup_property_source_link_field_headers_async(): ) in kw["metadata"] -def test_create_rollup_property_source_link_flattened(): +def test_list_event_edit_rules_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.RollupPropertySourceLink() + call.return_value = analytics_admin.ListEventEditRulesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_rollup_property_source_link( + client.list_event_edit_rules( parent="parent_value", - rollup_property_source_link=resources.RollupPropertySourceLink( - name="name_value" - ), ) # Establish that the underlying call was made with the expected @@ -54743,12 +54163,9 @@ def test_create_rollup_property_source_link_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].rollup_property_source_link - mock_val = resources.RollupPropertySourceLink(name="name_value") - assert arg == mock_val -def test_create_rollup_property_source_link_flattened_error(): +def test_list_event_edit_rules_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -54756,38 +54173,32 @@ def test_create_rollup_property_source_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_rollup_property_source_link( - analytics_admin.CreateRollupPropertySourceLinkRequest(), + client.list_event_edit_rules( + analytics_admin.ListEventEditRulesRequest(), parent="parent_value", - rollup_property_source_link=resources.RollupPropertySourceLink( - name="name_value" - ), ) @pytest.mark.asyncio -async def test_create_rollup_property_source_link_flattened_async(): +async def test_list_event_edit_rules_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_rollup_property_source_link), "__call__" + type(client.transport.list_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.RollupPropertySourceLink() + call.return_value = analytics_admin.ListEventEditRulesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.RollupPropertySourceLink() + analytics_admin.ListEventEditRulesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_rollup_property_source_link( + response = await client.list_event_edit_rules( parent="parent_value", - rollup_property_source_link=resources.RollupPropertySourceLink( - name="name_value" - ), ) # Establish that the underlying call was made with the expected @@ -54797,13 +54208,10 @@ async def test_create_rollup_property_source_link_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].rollup_property_source_link - mock_val = resources.RollupPropertySourceLink(name="name_value") - assert arg == mock_val @pytest.mark.asyncio -async def test_create_rollup_property_source_link_flattened_error_async(): +async def test_list_event_edit_rules_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -54811,23 +54219,224 @@ async def test_create_rollup_property_source_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_rollup_property_source_link( - analytics_admin.CreateRollupPropertySourceLinkRequest(), + await client.list_event_edit_rules( + analytics_admin.ListEventEditRulesRequest(), parent="parent_value", - rollup_property_source_link=resources.RollupPropertySourceLink( - name="name_value" + ) + + +def test_list_event_edit_rules_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token="ghi", ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_event_edit_rules(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_create_and_edit.EventEditRule) for i in results) + + +def test_list_event_edit_rules_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_event_edit_rules(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_event_edit_rules_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_event_edit_rules( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, event_create_and_edit.EventEditRule) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_event_edit_rules_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_event_edit_rules(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteRollupPropertySourceLinkRequest, + analytics_admin.CreateEventEditRuleRequest, dict, ], ) -def test_delete_rollup_property_source_link(request_type, transport: str = "grpc"): +def test_create_event_edit_rule(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -54839,23 +54448,30 @@ def test_delete_rollup_property_source_link(request_type, transport: str = "grpc # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_rollup_property_source_link(request) + call.return_value = event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) + response = client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + request = analytics_admin.CreateEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 -def test_delete_rollup_property_source_link_empty_call(): +def test_create_event_edit_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -54865,18 +54481,18 @@ def test_delete_rollup_property_source_link_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_rollup_property_source_link() + client.create_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest() + assert args[0] == analytics_admin.CreateEventEditRuleRequest() -def test_delete_rollup_property_source_link_non_empty_request_with_auto_populated_field(): +def test_create_event_edit_rule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -54887,26 +54503,26 @@ def test_delete_rollup_property_source_link_non_empty_request_with_auto_populate # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteRollupPropertySourceLinkRequest( - name="name_value", + request = analytics_admin.CreateEventEditRuleRequest( + parent="parent_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_rollup_property_source_link(request=request) + client.create_event_edit_rule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest( - name="name_value", + assert args[0] == analytics_admin.CreateEventEditRuleRequest( + parent="parent_value", ) -def test_delete_rollup_property_source_link_use_cached_wrapped_rpc(): +def test_create_event_edit_rule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -54921,7 +54537,7 @@ def test_delete_rollup_property_source_link_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_rollup_property_source_link + client._transport.create_event_edit_rule in client._transport._wrapped_methods ) @@ -54931,15 +54547,15 @@ def test_delete_rollup_property_source_link_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_rollup_property_source_link + client._transport.create_event_edit_rule ] = mock_rpc request = {} - client.delete_rollup_property_source_link(request) + client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_rollup_property_source_link(request) + client.create_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -54947,7 +54563,7 @@ def test_delete_rollup_property_source_link_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_empty_call_async(): +async def test_create_event_edit_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -54957,18 +54573,24 @@ async def test_delete_rollup_property_source_link_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_rollup_property_source_link() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) + ) + response = await client.create_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest() + assert args[0] == analytics_admin.CreateEventEditRuleRequest() @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_async_use_cached_wrapped_rpc( +async def test_create_event_edit_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -54985,23 +54607,23 @@ async def test_delete_rollup_property_source_link_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_rollup_property_source_link + client._client._transport.create_event_edit_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_rollup_property_source_link + client._client._transport.create_event_edit_rule ] = mock_object request = {} - await client.delete_rollup_property_source_link(request) + await client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_rollup_property_source_link(request) + await client.create_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -55009,9 +54631,9 @@ async def test_delete_rollup_property_source_link_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_async( +async def test_create_event_edit_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteRollupPropertySourceLinkRequest, + request_type=analytics_admin.CreateEventEditRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -55024,44 +54646,53 @@ async def test_delete_rollup_property_source_link_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_rollup_property_source_link(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) + ) + response = await client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + request = analytics_admin.CreateEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_async_from_dict(): - await test_delete_rollup_property_source_link_async(request_type=dict) +async def test_create_event_edit_rule_async_from_dict(): + await test_create_event_edit_rule_async(request_type=dict) -def test_delete_rollup_property_source_link_field_headers(): +def test_create_event_edit_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + request = analytics_admin.CreateEventEditRuleRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: - call.return_value = None - client.delete_rollup_property_source_link(request) + call.return_value = event_create_and_edit.EventEditRule() + client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -55072,28 +54703,30 @@ def test_delete_rollup_property_source_link_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_field_headers_async(): +async def test_create_event_edit_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + request = analytics_admin.CreateEventEditRuleRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_rollup_property_source_link(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventEditRule() + ) + await client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -55104,37 +54737,41 @@ async def test_delete_rollup_property_source_link_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_rollup_property_source_link_flattened(): +def test_create_event_edit_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = event_create_and_edit.EventEditRule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_rollup_property_source_link( - name="name_value", + client.create_event_edit_rule( + parent="parent_value", + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name="name_value") assert arg == mock_val -def test_delete_rollup_property_source_link_flattened_error(): +def test_create_event_edit_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -55142,43 +54779,50 @@ def test_delete_rollup_property_source_link_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_rollup_property_source_link( - analytics_admin.DeleteRollupPropertySourceLinkRequest(), - name="name_value", + client.create_event_edit_rule( + analytics_admin.CreateEventEditRuleRequest(), + parent="parent_value", + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), ) @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_flattened_async(): +async def test_create_event_edit_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_rollup_property_source_link), "__call__" + type(client.transport.create_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = event_create_and_edit.EventEditRule() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + event_create_and_edit.EventEditRule() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_rollup_property_source_link( - name="name_value", + response = await client.create_event_edit_rule( + parent="parent_value", + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_delete_rollup_property_source_link_flattened_error_async(): +async def test_create_event_edit_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -55186,20 +54830,21 @@ async def test_delete_rollup_property_source_link_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_rollup_property_source_link( - analytics_admin.DeleteRollupPropertySourceLinkRequest(), - name="name_value", + await client.create_event_edit_rule( + analytics_admin.CreateEventEditRuleRequest(), + parent="parent_value", + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateSubpropertyRequest, + analytics_admin.UpdateEventEditRuleRequest, dict, ], ) -def test_create_subproperty(request_type, transport: str = "grpc"): +def test_update_event_edit_rule(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -55211,23 +54856,30 @@ def test_create_subproperty(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.CreateSubpropertyResponse() - response = client.create_subproperty(request) + call.return_value = event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) + response = client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateSubpropertyRequest() + request = analytics_admin.UpdateEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateSubpropertyResponse) + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 -def test_create_subproperty_empty_call(): +def test_update_event_edit_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -55237,18 +54889,18 @@ def test_create_subproperty_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_subproperty() + client.update_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSubpropertyRequest() + assert args[0] == analytics_admin.UpdateEventEditRuleRequest() -def test_create_subproperty_non_empty_request_with_auto_populated_field(): +def test_update_event_edit_rule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -55259,26 +54911,22 @@ def test_create_subproperty_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateSubpropertyRequest( - parent="parent_value", - ) + request = analytics_admin.UpdateEventEditRuleRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_subproperty(request=request) + client.update_event_edit_rule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSubpropertyRequest( - parent="parent_value", - ) + assert args[0] == analytics_admin.UpdateEventEditRuleRequest() -def test_create_subproperty_use_cached_wrapped_rpc(): +def test_update_event_edit_rule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -55293,7 +54941,8 @@ def test_create_subproperty_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_subproperty in client._transport._wrapped_methods + client._transport.update_event_edit_rule + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -55302,15 +54951,15 @@ def test_create_subproperty_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_subproperty + client._transport.update_event_edit_rule ] = mock_rpc request = {} - client.create_subproperty(request) + client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_subproperty(request) + client.update_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -55318,7 +54967,7 @@ def test_create_subproperty_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_subproperty_empty_call_async(): +async def test_update_event_edit_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -55328,20 +54977,24 @@ async def test_create_subproperty_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.CreateSubpropertyResponse() + event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) ) - response = await client.create_subproperty() + response = await client.update_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSubpropertyRequest() + assert args[0] == analytics_admin.UpdateEventEditRuleRequest() @pytest.mark.asyncio -async def test_create_subproperty_async_use_cached_wrapped_rpc( +async def test_update_event_edit_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -55358,23 +55011,23 @@ async def test_create_subproperty_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_subproperty + client._client._transport.update_event_edit_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.create_subproperty + client._client._transport.update_event_edit_rule ] = mock_object request = {} - await client.create_subproperty(request) + await client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.create_subproperty(request) + await client.update_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -55382,9 +55035,9 @@ async def test_create_subproperty_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_subproperty_async( +async def test_update_event_edit_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateSubpropertyRequest, + request_type=analytics_admin.UpdateEventEditRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -55397,288 +55050,53 @@ async def test_create_subproperty_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.CreateSubpropertyResponse() + event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) ) - response = await client.create_subproperty(request) + response = await client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateSubpropertyRequest() + request = analytics_admin.UpdateEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateSubpropertyResponse) + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 @pytest.mark.asyncio -async def test_create_subproperty_async_from_dict(): - await test_create_subproperty_async(request_type=dict) +async def test_update_event_edit_rule_async_from_dict(): + await test_update_event_edit_rule_async(request_type=dict) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.CreateSubpropertyEventFilterRequest, - dict, - ], -) -def test_create_subproperty_event_filter(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - response = client.create_subproperty_event_filter(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateSubpropertyEventFilterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) - assert response.name == "name_value" - assert response.apply_to_property == "apply_to_property_value" - - -def test_create_subproperty_event_filter_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_subproperty_event_filter() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest() - - -def test_create_subproperty_event_filter_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = analytics_admin.CreateSubpropertyEventFilterRequest( - parent="parent_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_subproperty_event_filter(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest( - parent="parent_value", - ) - - -def test_create_subproperty_event_filter_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._transport.create_subproperty_event_filter - in client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.create_subproperty_event_filter - ] = mock_rpc - request = {} - client.create_subproperty_event_filter(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_subproperty_event_filter(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_subproperty_event_filter_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - ) - response = await client.create_subproperty_event_filter() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest() - - -@pytest.mark.asyncio -async def test_create_subproperty_event_filter_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert ( - client._client._transport.create_subproperty_event_filter - in client._client._transport._wrapped_methods - ) - - # Replace cached wrapped function with mock - mock_object = mock.AsyncMock() - client._client._transport._wrapped_methods[ - client._client._transport.create_subproperty_event_filter - ] = mock_object - - request = {} - await client.create_subproperty_event_filter(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_object.call_count == 1 - - await client.create_subproperty_event_filter(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_object.call_count == 2 - - -@pytest.mark.asyncio -async def test_create_subproperty_event_filter_async( - transport: str = "grpc_asyncio", - request_type=analytics_admin.CreateSubpropertyEventFilterRequest, -): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - ) - response = await client.create_subproperty_event_filter(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = analytics_admin.CreateSubpropertyEventFilterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) - assert response.name == "name_value" - assert response.apply_to_property == "apply_to_property_value" - - -@pytest.mark.asyncio -async def test_create_subproperty_event_filter_async_from_dict(): - await test_create_subproperty_event_filter_async(request_type=dict) - - -def test_create_subproperty_event_filter_field_headers(): +def test_update_event_edit_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateSubpropertyEventFilterRequest() + request = analytics_admin.UpdateEventEditRuleRequest() - request.parent = "parent_value" + request.event_edit_rule.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() - client.create_subproperty_event_filter(request) + call.return_value = event_create_and_edit.EventEditRule() + client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -55689,30 +55107,30 @@ def test_create_subproperty_event_filter_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "event_edit_rule.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_subproperty_event_filter_field_headers_async(): +async def test_update_event_edit_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.CreateSubpropertyEventFilterRequest() + request = analytics_admin.UpdateEventEditRuleRequest() - request.parent = "parent_value" + request.event_edit_rule.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter() + event_create_and_edit.EventEditRule() ) - await client.create_subproperty_event_filter(request) + await client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -55723,45 +55141,41 @@ async def test_create_subproperty_event_filter_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "event_edit_rule.name=name_value", ) in kw["metadata"] -def test_create_subproperty_event_filter_flattened(): +def test_update_event_edit_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + call.return_value = event_create_and_edit.EventEditRule() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_subproperty_event_filter( - parent="parent_value", - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + client.update_event_edit_rule( + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name="name_value") assert arg == mock_val - arg = args[0].subproperty_event_filter - mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ) + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_subproperty_event_filter_flattened_error(): +def test_update_event_edit_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -55769,56 +55183,50 @@ def test_create_subproperty_event_filter_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_subproperty_event_filter( - analytics_admin.CreateSubpropertyEventFilterRequest(), - parent="parent_value", - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + client.update_event_edit_rule( + analytics_admin.UpdateEventEditRuleRequest(), + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_create_subproperty_event_filter_flattened_async(): +async def test_update_event_edit_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_subproperty_event_filter), "__call__" + type(client.transport.update_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + call.return_value = event_create_and_edit.EventEditRule() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter() + event_create_and_edit.EventEditRule() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_subproperty_event_filter( - parent="parent_value", - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + response = await client.update_event_edit_rule( + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name="name_value") assert arg == mock_val - arg = args[0].subproperty_event_filter - mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ) + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_subproperty_event_filter_flattened_error_async(): +async def test_update_event_edit_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -55826,23 +55234,21 @@ async def test_create_subproperty_event_filter_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_subproperty_event_filter( - analytics_admin.CreateSubpropertyEventFilterRequest(), - parent="parent_value", - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + await client.update_event_edit_rule( + analytics_admin.UpdateEventEditRuleRequest(), + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetSubpropertyEventFilterRequest, + analytics_admin.DeleteEventEditRuleRequest, dict, ], ) -def test_get_subproperty_event_filter(request_type, transport: str = "grpc"): +def test_delete_event_edit_rule(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -55854,28 +55260,23 @@ def test_get_subproperty_event_filter(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - response = client.get_subproperty_event_filter(request) + call.return_value = None + response = client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.GetSubpropertyEventFilterRequest() + request = analytics_admin.DeleteEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) - assert response.name == "name_value" - assert response.apply_to_property == "apply_to_property_value" + assert response is None -def test_get_subproperty_event_filter_empty_call(): +def test_delete_event_edit_rule_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -55885,18 +55286,18 @@ def test_get_subproperty_event_filter_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_subproperty_event_filter() + client.delete_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.DeleteEventEditRuleRequest() -def test_get_subproperty_event_filter_non_empty_request_with_auto_populated_field(): +def test_delete_event_edit_rule_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -55907,26 +55308,26 @@ def test_get_subproperty_event_filter_non_empty_request_with_auto_populated_fiel # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.GetSubpropertyEventFilterRequest( + request = analytics_admin.DeleteEventEditRuleRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_subproperty_event_filter(request=request) + client.delete_event_edit_rule(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest( + assert args[0] == analytics_admin.DeleteEventEditRuleRequest( name="name_value", ) -def test_get_subproperty_event_filter_use_cached_wrapped_rpc(): +def test_delete_event_edit_rule_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -55941,7 +55342,7 @@ def test_get_subproperty_event_filter_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_subproperty_event_filter + client._transport.delete_event_edit_rule in client._transport._wrapped_methods ) @@ -55951,15 +55352,15 @@ def test_get_subproperty_event_filter_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_subproperty_event_filter + client._transport.delete_event_edit_rule ] = mock_rpc request = {} - client.get_subproperty_event_filter(request) + client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_subproperty_event_filter(request) + client.delete_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -55967,7 +55368,7 @@ def test_get_subproperty_event_filter_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_subproperty_event_filter_empty_call_async(): +async def test_delete_event_edit_rule_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -55977,23 +55378,18 @@ async def test_get_subproperty_event_filter_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - ) - response = await client.get_subproperty_event_filter() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_edit_rule() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.DeleteEventEditRuleRequest() @pytest.mark.asyncio -async def test_get_subproperty_event_filter_async_use_cached_wrapped_rpc( +async def test_delete_event_edit_rule_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -56010,23 +55406,23 @@ async def test_get_subproperty_event_filter_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_subproperty_event_filter + client._client._transport.delete_event_edit_rule in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.get_subproperty_event_filter + client._client._transport.delete_event_edit_rule ] = mock_object request = {} - await client.get_subproperty_event_filter(request) + await client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.get_subproperty_event_filter(request) + await client.delete_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -56034,9 +55430,9 @@ async def test_get_subproperty_event_filter_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_subproperty_event_filter_async( +async def test_delete_event_edit_rule_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.GetSubpropertyEventFilterRequest, + request_type=analytics_admin.DeleteEventEditRuleRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -56049,51 +55445,44 @@ async def test_get_subproperty_event_filter_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - ) - response = await client.get_subproperty_event_filter(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.GetSubpropertyEventFilterRequest() + request = analytics_admin.DeleteEventEditRuleRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) - assert response.name == "name_value" - assert response.apply_to_property == "apply_to_property_value" + assert response is None @pytest.mark.asyncio -async def test_get_subproperty_event_filter_async_from_dict(): - await test_get_subproperty_event_filter_async(request_type=dict) +async def test_delete_event_edit_rule_async_from_dict(): + await test_delete_event_edit_rule_async(request_type=dict) -def test_get_subproperty_event_filter_field_headers(): +def test_delete_event_edit_rule_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetSubpropertyEventFilterRequest() + request = analytics_admin.DeleteEventEditRuleRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: - call.return_value = subproperty_event_filter.SubpropertyEventFilter() - client.get_subproperty_event_filter(request) + call.return_value = None + client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -56109,25 +55498,23 @@ def test_get_subproperty_event_filter_field_headers(): @pytest.mark.asyncio -async def test_get_subproperty_event_filter_field_headers_async(): +async def test_delete_event_edit_rule_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.GetSubpropertyEventFilterRequest() + request = analytics_admin.DeleteEventEditRuleRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - subproperty_event_filter.SubpropertyEventFilter() - ) - await client.get_subproperty_event_filter(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -56142,20 +55529,20 @@ async def test_get_subproperty_event_filter_field_headers_async(): ) in kw["metadata"] -def test_get_subproperty_event_filter_flattened(): +def test_delete_event_edit_rule_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = subproperty_event_filter.SubpropertyEventFilter() + call.return_value = None # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_subproperty_event_filter( + client.delete_event_edit_rule( name="name_value", ) @@ -56168,7 +55555,7 @@ def test_get_subproperty_event_filter_flattened(): assert arg == mock_val -def test_get_subproperty_event_filter_flattened_error(): +def test_delete_event_edit_rule_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -56176,31 +55563,29 @@ def test_get_subproperty_event_filter_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_subproperty_event_filter( - analytics_admin.GetSubpropertyEventFilterRequest(), + client.delete_event_edit_rule( + analytics_admin.DeleteEventEditRuleRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_subproperty_event_filter_flattened_async(): +async def test_delete_event_edit_rule_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_subproperty_event_filter), "__call__" + type(client.transport.delete_event_edit_rule), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = subproperty_event_filter.SubpropertyEventFilter() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - subproperty_event_filter.SubpropertyEventFilter() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_subproperty_event_filter( + response = await client.delete_event_edit_rule( name="name_value", ) @@ -56214,7 +55599,7 @@ async def test_get_subproperty_event_filter_flattened_async(): @pytest.mark.asyncio -async def test_get_subproperty_event_filter_flattened_error_async(): +async def test_delete_event_edit_rule_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -56222,8 +55607,8 @@ async def test_get_subproperty_event_filter_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_subproperty_event_filter( - analytics_admin.GetSubpropertyEventFilterRequest(), + await client.delete_event_edit_rule( + analytics_admin.DeleteEventEditRuleRequest(), name="name_value", ) @@ -56231,11 +55616,11 @@ async def test_get_subproperty_event_filter_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListSubpropertyEventFiltersRequest, + analytics_admin.ReorderEventEditRulesRequest, dict, ], ) -def test_list_subproperty_event_filters(request_type, transport: str = "grpc"): +def test_reorder_event_edit_rules(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -56247,26 +55632,23 @@ def test_list_subproperty_event_filters(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse( - next_page_token="next_page_token_value", - ) - response = client.list_subproperty_event_filters(request) + call.return_value = None + response = client.reorder_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.ListSubpropertyEventFiltersRequest() + request = analytics_admin.ReorderEventEditRulesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubpropertyEventFiltersPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_subproperty_event_filters_empty_call(): +def test_reorder_event_edit_rules_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -56276,18 +55658,18 @@ def test_list_subproperty_event_filters_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_subproperty_event_filters() + client.reorder_event_edit_rules() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest() + assert args[0] == analytics_admin.ReorderEventEditRulesRequest() -def test_list_subproperty_event_filters_non_empty_request_with_auto_populated_field(): +def test_reorder_event_edit_rules_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -56298,28 +55680,26 @@ def test_list_subproperty_event_filters_non_empty_request_with_auto_populated_fi # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.ListSubpropertyEventFiltersRequest( + request = analytics_admin.ReorderEventEditRulesRequest( parent="parent_value", - page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_subproperty_event_filters(request=request) + client.reorder_event_edit_rules(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest( + assert args[0] == analytics_admin.ReorderEventEditRulesRequest( parent="parent_value", - page_token="page_token_value", ) -def test_list_subproperty_event_filters_use_cached_wrapped_rpc(): +def test_reorder_event_edit_rules_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -56334,7 +55714,7 @@ def test_list_subproperty_event_filters_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_subproperty_event_filters + client._transport.reorder_event_edit_rules in client._transport._wrapped_methods ) @@ -56344,15 +55724,15 @@ def test_list_subproperty_event_filters_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_subproperty_event_filters + client._transport.reorder_event_edit_rules ] = mock_rpc request = {} - client.list_subproperty_event_filters(request) + client.reorder_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_subproperty_event_filters(request) + client.reorder_event_edit_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -56360,7 +55740,7 @@ def test_list_subproperty_event_filters_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_subproperty_event_filters_empty_call_async(): +async def test_reorder_event_edit_rules_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -56370,22 +55750,18 @@ async def test_list_subproperty_event_filters_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSubpropertyEventFiltersResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_subproperty_event_filters() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.reorder_event_edit_rules() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest() + assert args[0] == analytics_admin.ReorderEventEditRulesRequest() @pytest.mark.asyncio -async def test_list_subproperty_event_filters_async_use_cached_wrapped_rpc( +async def test_reorder_event_edit_rules_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -56402,23 +55778,23 @@ async def test_list_subproperty_event_filters_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_subproperty_event_filters + client._client._transport.reorder_event_edit_rules in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.list_subproperty_event_filters + client._client._transport.reorder_event_edit_rules ] = mock_object request = {} - await client.list_subproperty_event_filters(request) + await client.reorder_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.list_subproperty_event_filters(request) + await client.reorder_event_edit_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -56426,9 +55802,9 @@ async def test_list_subproperty_event_filters_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_subproperty_event_filters_async( +async def test_reorder_event_edit_rules_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.ListSubpropertyEventFiltersRequest, + request_type=analytics_admin.ReorderEventEditRulesRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -56441,49 +55817,44 @@ async def test_list_subproperty_event_filters_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSubpropertyEventFiltersResponse( - next_page_token="next_page_token_value", - ) - ) - response = await client.list_subproperty_event_filters(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.reorder_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.ListSubpropertyEventFiltersRequest() + request = analytics_admin.ReorderEventEditRulesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubpropertyEventFiltersAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert response is None @pytest.mark.asyncio -async def test_list_subproperty_event_filters_async_from_dict(): - await test_list_subproperty_event_filters_async(request_type=dict) +async def test_reorder_event_edit_rules_async_from_dict(): + await test_reorder_event_edit_rules_async(request_type=dict) -def test_list_subproperty_event_filters_field_headers(): +def test_reorder_event_edit_rules_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListSubpropertyEventFiltersRequest() + request = analytics_admin.ReorderEventEditRulesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: - call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() - client.list_subproperty_event_filters(request) + call.return_value = None + client.reorder_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -56499,25 +55870,23 @@ def test_list_subproperty_event_filters_field_headers(): @pytest.mark.asyncio -async def test_list_subproperty_event_filters_field_headers_async(): +async def test_reorder_event_edit_rules_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.ListSubpropertyEventFiltersRequest() + request = analytics_admin.ReorderEventEditRulesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.reorder_event_edit_rules), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSubpropertyEventFiltersResponse() - ) - await client.list_subproperty_event_filters(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.reorder_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -56532,343 +55901,51 @@ async def test_list_subproperty_event_filters_field_headers_async(): ) in kw["metadata"] -def test_list_subproperty_event_filters_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateDataRedactionSettingsRequest, + dict, + ], +) +def test_update_data_redaction_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_subproperty_event_filters( - parent="parent_value", + call.return_value = resources.DataRedactionSettings( + name="name_value", + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=["query_parameter_keys_value"], ) + response = client.update_data_redaction_settings(request) - # Establish that the underlying call was made with the expected - # request object values. + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val + request = analytics_admin.UpdateDataRedactionSettingsRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == "name_value" + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ["query_parameter_keys_value"] -def test_list_subproperty_event_filters_flattened_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_subproperty_event_filters( - analytics_admin.ListSubpropertyEventFiltersRequest(), - parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_subproperty_event_filters_flattened_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - analytics_admin.ListSubpropertyEventFiltersResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_subproperty_event_filters( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_subproperty_event_filters_flattened_error_async(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_subproperty_event_filters( - analytics_admin.ListSubpropertyEventFiltersRequest(), - parent="parent_value", - ) - - -def test_list_subproperty_event_filters_pager(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="abc", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[], - next_page_token="def", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="ghi", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_subproperty_event_filters( - request={}, retry=retry, timeout=timeout - ) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, subproperty_event_filter.SubpropertyEventFilter) - for i in results - ) - - -def test_list_subproperty_event_filters_pages(transport_name: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subproperty_event_filters), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="abc", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[], - next_page_token="def", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="ghi", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - ), - RuntimeError, - ) - pages = list(client.list_subproperty_event_filters(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_subproperty_event_filters_async_pager(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subproperty_event_filters), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="abc", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[], - next_page_token="def", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="ghi", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_subproperty_event_filters( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all( - isinstance(i, subproperty_event_filter.SubpropertyEventFilter) - for i in responses - ) - - -@pytest.mark.asyncio -async def test_list_subproperty_event_filters_async_pages(): - client = AnalyticsAdminServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_subproperty_event_filters), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="abc", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[], - next_page_token="def", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - ], - next_page_token="ghi", - ), - analytics_admin.ListSubpropertyEventFiltersResponse( - subproperty_event_filters=[ - subproperty_event_filter.SubpropertyEventFilter(), - subproperty_event_filter.SubpropertyEventFilter(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_subproperty_event_filters(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.UpdateSubpropertyEventFilterRequest, - dict, - ], -) -def test_update_subproperty_event_filter(request_type, transport: str = "grpc"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value", - apply_to_property="apply_to_property_value", - ) - response = client.update_subproperty_event_filter(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateSubpropertyEventFilterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) - assert response.name == "name_value" - assert response.apply_to_property == "apply_to_property_value" - - -def test_update_subproperty_event_filter_empty_call(): +def test_update_data_redaction_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -56878,18 +55955,18 @@ def test_update_subproperty_event_filter_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_subproperty_event_filter() + client.update_data_redaction_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() -def test_update_subproperty_event_filter_non_empty_request_with_auto_populated_field(): +def test_update_data_redaction_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -56900,22 +55977,22 @@ def test_update_subproperty_event_filter_non_empty_request_with_auto_populated_f # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.UpdateSubpropertyEventFilterRequest() + request = analytics_admin.UpdateDataRedactionSettingsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_subproperty_event_filter(request=request) + client.update_data_redaction_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() -def test_update_subproperty_event_filter_use_cached_wrapped_rpc(): +def test_update_data_redaction_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -56930,7 +56007,7 @@ def test_update_subproperty_event_filter_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_subproperty_event_filter + client._transport.update_data_redaction_settings in client._transport._wrapped_methods ) @@ -56940,15 +56017,15 @@ def test_update_subproperty_event_filter_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_subproperty_event_filter + client._transport.update_data_redaction_settings ] = mock_rpc request = {} - client.update_subproperty_event_filter(request) + client.update_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_subproperty_event_filter(request) + client.update_data_redaction_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -56956,7 +56033,7 @@ def test_update_subproperty_event_filter_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_subproperty_event_filter_empty_call_async(): +async def test_update_data_redaction_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -56966,23 +56043,25 @@ async def test_update_subproperty_event_filter_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter( + resources.DataRedactionSettings( name="name_value", - apply_to_property="apply_to_property_value", + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=["query_parameter_keys_value"], ) ) - response = await client.update_subproperty_event_filter() + response = await client.update_data_redaction_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() @pytest.mark.asyncio -async def test_update_subproperty_event_filter_async_use_cached_wrapped_rpc( +async def test_update_data_redaction_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -56999,23 +56078,23 @@ async def test_update_subproperty_event_filter_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_subproperty_event_filter + client._client._transport.update_data_redaction_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.update_subproperty_event_filter + client._client._transport.update_data_redaction_settings ] = mock_object request = {} - await client.update_subproperty_event_filter(request) + await client.update_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.update_subproperty_event_filter(request) + await client.update_data_redaction_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -57023,9 +56102,9 @@ async def test_update_subproperty_event_filter_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_subproperty_event_filter_async( +async def test_update_data_redaction_settings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.UpdateSubpropertyEventFilterRequest, + request_type=analytics_admin.UpdateDataRedactionSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -57038,51 +56117,55 @@ async def test_update_subproperty_event_filter_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter( + resources.DataRedactionSettings( name="name_value", - apply_to_property="apply_to_property_value", + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=["query_parameter_keys_value"], ) ) - response = await client.update_subproperty_event_filter(request) + response = await client.update_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.UpdateSubpropertyEventFilterRequest() + request = analytics_admin.UpdateDataRedactionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert isinstance(response, resources.DataRedactionSettings) assert response.name == "name_value" - assert response.apply_to_property == "apply_to_property_value" + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ["query_parameter_keys_value"] @pytest.mark.asyncio -async def test_update_subproperty_event_filter_async_from_dict(): - await test_update_subproperty_event_filter_async(request_type=dict) +async def test_update_data_redaction_settings_async_from_dict(): + await test_update_data_redaction_settings_async(request_type=dict) -def test_update_subproperty_event_filter_field_headers(): +def test_update_data_redaction_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateSubpropertyEventFilterRequest() + request = analytics_admin.UpdateDataRedactionSettingsRequest() - request.subproperty_event_filter.name = "name_value" + request.data_redaction_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() - client.update_subproperty_event_filter(request) + call.return_value = resources.DataRedactionSettings() + client.update_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -57093,30 +56176,30 @@ def test_update_subproperty_event_filter_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "subproperty_event_filter.name=name_value", + "data_redaction_settings.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_subproperty_event_filter_field_headers_async(): +async def test_update_data_redaction_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.UpdateSubpropertyEventFilterRequest() + request = analytics_admin.UpdateDataRedactionSettingsRequest() - request.subproperty_event_filter.name = "name_value" + request.data_redaction_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter() + resources.DataRedactionSettings() ) - await client.update_subproperty_event_filter(request) + await client.update_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -57127,27 +56210,25 @@ async def test_update_subproperty_event_filter_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "subproperty_event_filter.name=name_value", + "data_redaction_settings.name=name_value", ) in kw["metadata"] -def test_update_subproperty_event_filter_flattened(): +def test_update_data_redaction_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + call.return_value = resources.DataRedactionSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_subproperty_event_filter( - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + client.update_data_redaction_settings( + data_redaction_settings=resources.DataRedactionSettings(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -57155,17 +56236,15 @@ def test_update_subproperty_event_filter_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].subproperty_event_filter - mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ) + arg = args[0].data_redaction_settings + mock_val = resources.DataRedactionSettings(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_update_subproperty_event_filter_flattened_error(): +def test_update_data_redaction_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -57173,37 +56252,33 @@ def test_update_subproperty_event_filter_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_subproperty_event_filter( - analytics_admin.UpdateSubpropertyEventFilterRequest(), - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + client.update_data_redaction_settings( + analytics_admin.UpdateDataRedactionSettingsRequest(), + data_redaction_settings=resources.DataRedactionSettings(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_subproperty_event_filter_flattened_async(): +async def test_update_data_redaction_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_subproperty_event_filter), "__call__" + type(client.transport.update_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + call.return_value = resources.DataRedactionSettings() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - gaa_subproperty_event_filter.SubpropertyEventFilter() + resources.DataRedactionSettings() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_subproperty_event_filter( - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + response = await client.update_data_redaction_settings( + data_redaction_settings=resources.DataRedactionSettings(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -57211,10 +56286,8 @@ async def test_update_subproperty_event_filter_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].subproperty_event_filter - mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ) + arg = args[0].data_redaction_settings + mock_val = resources.DataRedactionSettings(name="name_value") assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -57222,7 +56295,7 @@ async def test_update_subproperty_event_filter_flattened_async(): @pytest.mark.asyncio -async def test_update_subproperty_event_filter_flattened_error_async(): +async def test_update_data_redaction_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -57230,11 +56303,9 @@ async def test_update_subproperty_event_filter_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_subproperty_event_filter( - analytics_admin.UpdateSubpropertyEventFilterRequest(), - subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( - name="name_value" - ), + await client.update_data_redaction_settings( + analytics_admin.UpdateDataRedactionSettingsRequest(), + data_redaction_settings=resources.DataRedactionSettings(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -57242,11 +56313,11 @@ async def test_update_subproperty_event_filter_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteSubpropertyEventFilterRequest, + analytics_admin.GetDataRedactionSettingsRequest, dict, ], ) -def test_delete_subproperty_event_filter(request_type, transport: str = "grpc"): +def test_get_data_redaction_settings(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -57258,23 +56329,32 @@ def test_delete_subproperty_event_filter(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_subproperty_event_filter(request) + call.return_value = resources.DataRedactionSettings( + name="name_value", + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=["query_parameter_keys_value"], + ) + response = client.get_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteSubpropertyEventFilterRequest() + request = analytics_admin.GetDataRedactionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == "name_value" + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ["query_parameter_keys_value"] -def test_delete_subproperty_event_filter_empty_call(): +def test_get_data_redaction_settings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceClient( @@ -57284,18 +56364,18 @@ def test_delete_subproperty_event_filter_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_subproperty_event_filter() + client.get_data_redaction_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.GetDataRedactionSettingsRequest() -def test_delete_subproperty_event_filter_non_empty_request_with_auto_populated_field(): +def test_get_data_redaction_settings_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AnalyticsAdminServiceClient( @@ -57306,26 +56386,26 @@ def test_delete_subproperty_event_filter_non_empty_request_with_auto_populated_f # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = analytics_admin.DeleteSubpropertyEventFilterRequest( + request = analytics_admin.GetDataRedactionSettingsRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_subproperty_event_filter(request=request) + client.get_data_redaction_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest( + assert args[0] == analytics_admin.GetDataRedactionSettingsRequest( name="name_value", ) -def test_delete_subproperty_event_filter_use_cached_wrapped_rpc(): +def test_get_data_redaction_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -57340,7 +56420,7 @@ def test_delete_subproperty_event_filter_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_subproperty_event_filter + client._transport.get_data_redaction_settings in client._transport._wrapped_methods ) @@ -57350,15 +56430,15 @@ def test_delete_subproperty_event_filter_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_subproperty_event_filter + client._transport.get_data_redaction_settings ] = mock_rpc request = {} - client.delete_subproperty_event_filter(request) + client.get_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_subproperty_event_filter(request) + client.get_data_redaction_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -57366,7 +56446,7 @@ def test_delete_subproperty_event_filter_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_empty_call_async(): +async def test_get_data_redaction_settings_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AnalyticsAdminServiceAsyncClient( @@ -57376,18 +56456,25 @@ async def test_delete_subproperty_event_filter_empty_call_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_subproperty_event_filter() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataRedactionSettings( + name="name_value", + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=["query_parameter_keys_value"], + ) + ) + response = await client.get_data_redaction_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest() + assert args[0] == analytics_admin.GetDataRedactionSettingsRequest() @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_async_use_cached_wrapped_rpc( +async def test_get_data_redaction_settings_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -57404,23 +56491,23 @@ async def test_delete_subproperty_event_filter_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_subproperty_event_filter + client._client._transport.get_data_redaction_settings in client._client._transport._wrapped_methods ) # Replace cached wrapped function with mock mock_object = mock.AsyncMock() client._client._transport._wrapped_methods[ - client._client._transport.delete_subproperty_event_filter + client._client._transport.get_data_redaction_settings ] = mock_object request = {} - await client.delete_subproperty_event_filter(request) + await client.get_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_object.call_count == 1 - await client.delete_subproperty_event_filter(request) + await client.get_data_redaction_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -57428,9 +56515,9 @@ async def test_delete_subproperty_event_filter_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_async( +async def test_get_data_redaction_settings_async( transport: str = "grpc_asyncio", - request_type=analytics_admin.DeleteSubpropertyEventFilterRequest, + request_type=analytics_admin.GetDataRedactionSettingsRequest, ): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -57443,44 +56530,55 @@ async def test_delete_subproperty_event_filter_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_subproperty_event_filter(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataRedactionSettings( + name="name_value", + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=["query_parameter_keys_value"], + ) + ) + response = await client.get_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = analytics_admin.DeleteSubpropertyEventFilterRequest() + request = analytics_admin.GetDataRedactionSettingsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == "name_value" + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ["query_parameter_keys_value"] @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_async_from_dict(): - await test_delete_subproperty_event_filter_async(request_type=dict) +async def test_get_data_redaction_settings_async_from_dict(): + await test_get_data_redaction_settings_async(request_type=dict) -def test_delete_subproperty_event_filter_field_headers(): +def test_get_data_redaction_settings_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteSubpropertyEventFilterRequest() + request = analytics_admin.GetDataRedactionSettingsRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: - call.return_value = None - client.delete_subproperty_event_filter(request) + call.return_value = resources.DataRedactionSettings() + client.get_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -57496,23 +56594,25 @@ def test_delete_subproperty_event_filter_field_headers(): @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_field_headers_async(): +async def test_get_data_redaction_settings_field_headers_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = analytics_admin.DeleteSubpropertyEventFilterRequest() + request = analytics_admin.GetDataRedactionSettingsRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_subproperty_event_filter(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataRedactionSettings() + ) + await client.get_data_redaction_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -57527,20 +56627,20 @@ async def test_delete_subproperty_event_filter_field_headers_async(): ) in kw["metadata"] -def test_delete_subproperty_event_filter_flattened(): +def test_get_data_redaction_settings_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.DataRedactionSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_subproperty_event_filter( + client.get_data_redaction_settings( name="name_value", ) @@ -57553,7 +56653,7 @@ def test_delete_subproperty_event_filter_flattened(): assert arg == mock_val -def test_delete_subproperty_event_filter_flattened_error(): +def test_get_data_redaction_settings_flattened_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -57561,29 +56661,31 @@ def test_delete_subproperty_event_filter_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_subproperty_event_filter( - analytics_admin.DeleteSubpropertyEventFilterRequest(), + client.get_data_redaction_settings( + analytics_admin.GetDataRedactionSettingsRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_flattened_async(): +async def test_get_data_redaction_settings_flattened_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_subproperty_event_filter), "__call__" + type(client.transport.get_data_redaction_settings), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.DataRedactionSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.DataRedactionSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_subproperty_event_filter( + response = await client.get_data_redaction_settings( name="name_value", ) @@ -57597,7 +56699,7 @@ async def test_delete_subproperty_event_filter_flattened_async(): @pytest.mark.asyncio -async def test_delete_subproperty_event_filter_flattened_error_async(): +async def test_get_data_redaction_settings_flattened_error_async(): client = AnalyticsAdminServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -57605,8 +56707,8 @@ async def test_delete_subproperty_event_filter_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_subproperty_event_filter( - analytics_admin.DeleteSubpropertyEventFilterRequest(), + await client.get_data_redaction_settings( + analytics_admin.GetDataRedactionSettingsRequest(), name="name_value", ) @@ -57614,56 +56716,117 @@ async def test_delete_subproperty_event_filter_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAccountRequest, + analytics_admin.GetCalculatedMetricRequest, dict, ], ) -def test_get_account_rest(request_type): +def test_get_calculated_metric(request_type, transport: str = "grpc"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1"} - request = request_type(**request_init) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.Account( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric( name="name_value", + description="description_value", display_name="display_name_value", - region_code="region_code_value", - deleted=True, + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, ) + response = client.get_calculated_metric(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Account.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.get_account(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCalculatedMetricRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.Account) + assert isinstance(response, resources.CalculatedMetric) assert response.name == "name_value" + assert response.description == "description_value" assert response.display_name == "display_name_value" - assert response.region_code == "region_code_value" - assert response.deleted is True + assert response.calculated_metric_id == "calculated_metric_id_value" + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ] + assert response.formula == "formula_value" + assert response.invalid_metric_reference is True -def test_get_account_rest_use_cached_wrapped_rpc(): +def test_get_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCalculatedMetricRequest() + + +def test_get_calculated_metric_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.GetCalculatedMetricRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCalculatedMetricRequest( + name="name_value", + ) + + +def test_get_calculated_metric_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -57671,207 +56834,10899 @@ def test_get_account_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_account in client._transport._wrapped_methods + assert ( + client._transport.get_calculated_metric + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_account] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.get_calculated_metric + ] = mock_rpc request = {} - client.get_account(request) + client.get_calculated_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_account(request) + client.get_calculated_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_account_rest_required_fields( - request_type=analytics_admin.GetAccountRequest, -): - transport_class = transports.AnalyticsAdminServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +async def test_get_calculated_metric_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_account._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + ) + response = await client.get_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCalculatedMetricRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_account._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.asyncio +async def test_get_calculated_metric_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Designate an appropriate value for the returned response. - return_value = resources.Account() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Ensure method has been cached + assert ( + client._client._transport.get_calculated_metric + in client._client._transport._wrapped_methods + ) - response_value = Response() - response_value.status_code = 200 + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_calculated_metric + ] = mock_object - # Convert return value to protobuf type - return_value = resources.Account.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request = {} + await client.get_calculated_metric(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 - response = client.get_account(request) + await client.get_calculated_metric(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 -def test_get_account_rest_unset_required_fields(): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_calculated_metric_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.GetCalculatedMetricRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - unset_fields = transport.get_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_account_rest_interceptors(null_interceptor): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.AnalyticsAdminServiceRestInterceptor(), - ) - client = AnalyticsAdminServiceClient(transport=transport) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_account" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_account" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.GetAccountRequest.pb( - analytics_admin.GetAccountRequest() + type(client.transport.get_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + response = await client.get_calculated_metric(request) - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = resources.Account.to_json(resources.Account()) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCalculatedMetricRequest() + assert args[0] == request - request = analytics_admin.GetAccountRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Account() + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.display_name == "display_name_value" + assert response.calculated_metric_id == "calculated_metric_id_value" + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ] + assert response.formula == "formula_value" + assert response.invalid_metric_reference is True - client.get_account( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() +@pytest.mark.asyncio +async def test_get_calculated_metric_async_from_dict(): + await test_get_calculated_metric_async(request_type=dict) -def test_get_account_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetAccountRequest -): +def test_get_calculated_metric_field_headers(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1"} - request = request_type(**request_init) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCalculatedMetricRequest() - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_account(request) + request.name = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + call.return_value = resources.CalculatedMetric() + client.get_calculated_metric(request) -def test_get_account_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCalculatedMetricRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric() + ) + await client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_calculated_metric( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_calculated_metric( + analytics_admin.GetCalculatedMetricRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_calculated_metric( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_calculated_metric( + analytics_admin.GetCalculatedMetricRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateCalculatedMetricRequest, + dict, + ], +) +def test_create_calculated_metric(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + response = client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.display_name == "display_name_value" + assert response.calculated_metric_id == "calculated_metric_id_value" + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ] + assert response.formula == "formula_value" + assert response.invalid_metric_reference is True + + +def test_create_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCalculatedMetricRequest() + + +def test_create_calculated_metric_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.CreateCalculatedMetricRequest( + parent="parent_value", + calculated_metric_id="calculated_metric_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCalculatedMetricRequest( + parent="parent_value", + calculated_metric_id="calculated_metric_id_value", + ) + + +def test_create_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_calculated_metric + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_calculated_metric + ] = mock_rpc + request = {} + client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_calculated_metric_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + ) + response = await client.create_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCalculatedMetricRequest() + + +@pytest.mark.asyncio +async def test_create_calculated_metric_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_calculated_metric + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_calculated_metric + ] = mock_object + + request = {} + await client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_calculated_metric_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.CreateCalculatedMetricRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + ) + response = await client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.display_name == "display_name_value" + assert response.calculated_metric_id == "calculated_metric_id_value" + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ] + assert response.formula == "formula_value" + assert response.invalid_metric_reference is True + + +@pytest.mark.asyncio +async def test_create_calculated_metric_async_from_dict(): + await test_create_calculated_metric_async(request_type=dict) + + +def test_create_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCalculatedMetricRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + call.return_value = resources.CalculatedMetric() + client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCalculatedMetricRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric() + ) + await client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_calculated_metric( + parent="parent_value", + calculated_metric=resources.CalculatedMetric(name="name_value"), + calculated_metric_id="calculated_metric_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].calculated_metric + mock_val = resources.CalculatedMetric(name="name_value") + assert arg == mock_val + arg = args[0].calculated_metric_id + mock_val = "calculated_metric_id_value" + assert arg == mock_val + + +def test_create_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_calculated_metric( + analytics_admin.CreateCalculatedMetricRequest(), + parent="parent_value", + calculated_metric=resources.CalculatedMetric(name="name_value"), + calculated_metric_id="calculated_metric_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_calculated_metric( + parent="parent_value", + calculated_metric=resources.CalculatedMetric(name="name_value"), + calculated_metric_id="calculated_metric_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].calculated_metric + mock_val = resources.CalculatedMetric(name="name_value") + assert arg == mock_val + arg = args[0].calculated_metric_id + mock_val = "calculated_metric_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_calculated_metric( + analytics_admin.CreateCalculatedMetricRequest(), + parent="parent_value", + calculated_metric=resources.CalculatedMetric(name="name_value"), + calculated_metric_id="calculated_metric_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListCalculatedMetricsRequest, + dict, + ], +) +def test_list_calculated_metrics(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCalculatedMetricsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCalculatedMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCalculatedMetricsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_calculated_metrics_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_calculated_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCalculatedMetricsRequest() + + +def test_list_calculated_metrics_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ListCalculatedMetricsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_calculated_metrics(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCalculatedMetricsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_calculated_metrics_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_calculated_metrics + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_calculated_metrics + ] = mock_rpc + request = {} + client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_calculated_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListCalculatedMetricsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_calculated_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCalculatedMetricsRequest() + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_calculated_metrics + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_calculated_metrics + ] = mock_object + + request = {} + await client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_calculated_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.ListCalculatedMetricsRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListCalculatedMetricsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCalculatedMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCalculatedMetricsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_from_dict(): + await test_list_calculated_metrics_async(request_type=dict) + + +def test_list_calculated_metrics_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCalculatedMetricsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + call.return_value = analytics_admin.ListCalculatedMetricsResponse() + client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCalculatedMetricsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListCalculatedMetricsResponse() + ) + await client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_calculated_metrics_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCalculatedMetricsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_calculated_metrics( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_calculated_metrics_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_calculated_metrics( + analytics_admin.ListCalculatedMetricsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCalculatedMetricsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListCalculatedMetricsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_calculated_metrics( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_calculated_metrics( + analytics_admin.ListCalculatedMetricsRequest(), + parent="parent_value", + ) + + +def test_list_calculated_metrics_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_calculated_metrics(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CalculatedMetric) for i in results) + + +def test_list_calculated_metrics_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + pages = list(client.list_calculated_metrics(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_calculated_metrics( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.CalculatedMetric) for i in responses) + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_calculated_metrics(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateCalculatedMetricRequest, + dict, + ], +) +def test_update_calculated_metric(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + response = client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.display_name == "display_name_value" + assert response.calculated_metric_id == "calculated_metric_id_value" + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ] + assert response.formula == "formula_value" + assert response.invalid_metric_reference is True + + +def test_update_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() + + +def test_update_calculated_metric_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.UpdateCalculatedMetricRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() + + +def test_update_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_calculated_metric + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_calculated_metric + ] = mock_rpc + request = {} + client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_calculated_metric_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + ) + response = await client.update_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() + + +@pytest.mark.asyncio +async def test_update_calculated_metric_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_calculated_metric + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_calculated_metric + ] = mock_object + + request = {} + await client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_calculated_metric_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.UpdateCalculatedMetricRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric( + name="name_value", + description="description_value", + display_name="display_name_value", + calculated_metric_id="calculated_metric_id_value", + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ], + formula="formula_value", + invalid_metric_reference=True, + ) + ) + response = await client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.display_name == "display_name_value" + assert response.calculated_metric_id == "calculated_metric_id_value" + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [ + resources.CalculatedMetric.RestrictedMetricType.COST_DATA + ] + assert response.formula == "formula_value" + assert response.invalid_metric_reference is True + + +@pytest.mark.asyncio +async def test_update_calculated_metric_async_from_dict(): + await test_update_calculated_metric_async(request_type=dict) + + +def test_update_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCalculatedMetricRequest() + + request.calculated_metric.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + call.return_value = resources.CalculatedMetric() + client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "calculated_metric.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCalculatedMetricRequest() + + request.calculated_metric.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric() + ) + await client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "calculated_metric.name=name_value", + ) in kw["metadata"] + + +def test_update_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_calculated_metric( + calculated_metric=resources.CalculatedMetric(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].calculated_metric + mock_val = resources.CalculatedMetric(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_calculated_metric( + analytics_admin.UpdateCalculatedMetricRequest(), + calculated_metric=resources.CalculatedMetric(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CalculatedMetric() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_calculated_metric( + calculated_metric=resources.CalculatedMetric(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].calculated_metric + mock_val = resources.CalculatedMetric(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_calculated_metric( + analytics_admin.UpdateCalculatedMetricRequest(), + calculated_metric=resources.CalculatedMetric(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteCalculatedMetricRequest, + dict, + ], +) +def test_delete_calculated_metric(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteCalculatedMetricRequest() + + +def test_delete_calculated_metric_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.DeleteCalculatedMetricRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteCalculatedMetricRequest( + name="name_value", + ) + + +def test_delete_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_calculated_metric + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_calculated_metric + ] = mock_rpc + request = {} + client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteCalculatedMetricRequest() + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_calculated_metric + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_calculated_metric + ] = mock_object + + request = {} + await client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.DeleteCalculatedMetricRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_async_from_dict(): + await test_delete_calculated_metric_async(request_type=dict) + + +def test_delete_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteCalculatedMetricRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + call.return_value = None + client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteCalculatedMetricRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_calculated_metric( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_calculated_metric( + analytics_admin.DeleteCalculatedMetricRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_calculated_metric( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_calculated_metric( + analytics_admin.DeleteCalculatedMetricRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateRollupPropertyRequest, + dict, + ], +) +def test_create_rollup_property(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.CreateRollupPropertyResponse() + response = client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + + +def test_create_rollup_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_rollup_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertyRequest() + + +def test_create_rollup_property_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.CreateRollupPropertyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_rollup_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertyRequest() + + +def test_create_rollup_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_rollup_property + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_rollup_property + ] = mock_rpc + request = {} + client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_rollup_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_rollup_property_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.CreateRollupPropertyResponse() + ) + response = await client.create_rollup_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertyRequest() + + +@pytest.mark.asyncio +async def test_create_rollup_property_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_rollup_property + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_rollup_property + ] = mock_object + + request = {} + await client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_rollup_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_rollup_property_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.CreateRollupPropertyRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.CreateRollupPropertyResponse() + ) + response = await client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + + +@pytest.mark.asyncio +async def test_create_rollup_property_async_from_dict(): + await test_create_rollup_property_async(request_type=dict) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetRollupPropertySourceLinkRequest, + dict, + ], +) +def test_get_rollup_property_source_link(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink( + name="name_value", + source_property="source_property_value", + ) + response = client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == "name_value" + assert response.source_property == "source_property_value" + + +def test_get_rollup_property_source_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest() + + +def test_get_rollup_property_source_link_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.GetRollupPropertySourceLinkRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_rollup_property_source_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest( + name="name_value", + ) + + +def test_get_rollup_property_source_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_rollup_property_source_link + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_rollup_property_source_link + ] = mock_rpc + request = {} + client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink( + name="name_value", + source_property="source_property_value", + ) + ) + response = await client.get_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest() + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_rollup_property_source_link + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_rollup_property_source_link + ] = mock_object + + request = {} + await client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.GetRollupPropertySourceLinkRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink( + name="name_value", + source_property="source_property_value", + ) + ) + response = await client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == "name_value" + assert response.source_property == "source_property_value" + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_async_from_dict(): + await test_get_rollup_property_source_link_async(request_type=dict) + + +def test_get_rollup_property_source_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetRollupPropertySourceLinkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + call.return_value = resources.RollupPropertySourceLink() + client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetRollupPropertySourceLinkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink() + ) + await client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_rollup_property_source_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_rollup_property_source_link( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_rollup_property_source_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_rollup_property_source_link( + analytics_admin.GetRollupPropertySourceLinkRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_rollup_property_source_link( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_rollup_property_source_link( + analytics_admin.GetRollupPropertySourceLinkRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListRollupPropertySourceLinksRequest, + dict, + ], +) +def test_list_rollup_property_source_links(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse( + next_page_token="next_page_token_value", + ) + response = client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListRollupPropertySourceLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRollupPropertySourceLinksPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_rollup_property_source_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_rollup_property_source_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest() + + +def test_list_rollup_property_source_links_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ListRollupPropertySourceLinksRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_rollup_property_source_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_rollup_property_source_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_rollup_property_source_links + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_rollup_property_source_links + ] = mock_rpc + request = {} + client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_rollup_property_source_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListRollupPropertySourceLinksResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_rollup_property_source_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest() + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_rollup_property_source_links + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_rollup_property_source_links + ] = mock_object + + request = {} + await client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_rollup_property_source_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.ListRollupPropertySourceLinksRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListRollupPropertySourceLinksResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListRollupPropertySourceLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRollupPropertySourceLinksAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_from_dict(): + await test_list_rollup_property_source_links_async(request_type=dict) + + +def test_list_rollup_property_source_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListRollupPropertySourceLinksRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListRollupPropertySourceLinksRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListRollupPropertySourceLinksResponse() + ) + await client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_rollup_property_source_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_rollup_property_source_links( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_rollup_property_source_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_rollup_property_source_links( + analytics_admin.ListRollupPropertySourceLinksRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListRollupPropertySourceLinksResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_rollup_property_source_links( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_rollup_property_source_links( + analytics_admin.ListRollupPropertySourceLinksRequest(), + parent="parent_value", + ) + + +def test_list_rollup_property_source_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token="def", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_rollup_property_source_links( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.RollupPropertySourceLink) for i in results) + + +def test_list_rollup_property_source_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token="def", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_rollup_property_source_links(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token="def", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_rollup_property_source_links( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.RollupPropertySourceLink) for i in responses) + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token="def", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_rollup_property_source_links(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateRollupPropertySourceLinkRequest, + dict, + ], +) +def test_create_rollup_property_source_link(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink( + name="name_value", + source_property="source_property_value", + ) + response = client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == "name_value" + assert response.source_property == "source_property_value" + + +def test_create_rollup_property_source_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest() + + +def test_create_rollup_property_source_link_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.CreateRollupPropertySourceLinkRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_rollup_property_source_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest( + parent="parent_value", + ) + + +def test_create_rollup_property_source_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_rollup_property_source_link + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_rollup_property_source_link + ] = mock_rpc + request = {} + client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink( + name="name_value", + source_property="source_property_value", + ) + ) + response = await client.create_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest() + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_rollup_property_source_link + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_rollup_property_source_link + ] = mock_object + + request = {} + await client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.CreateRollupPropertySourceLinkRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink( + name="name_value", + source_property="source_property_value", + ) + ) + response = await client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == "name_value" + assert response.source_property == "source_property_value" + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_async_from_dict(): + await test_create_rollup_property_source_link_async(request_type=dict) + + +def test_create_rollup_property_source_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + call.return_value = resources.RollupPropertySourceLink() + client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink() + ) + await client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_rollup_property_source_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_rollup_property_source_link( + parent="parent_value", + rollup_property_source_link=resources.RollupPropertySourceLink( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].rollup_property_source_link + mock_val = resources.RollupPropertySourceLink(name="name_value") + assert arg == mock_val + + +def test_create_rollup_property_source_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_rollup_property_source_link( + analytics_admin.CreateRollupPropertySourceLinkRequest(), + parent="parent_value", + rollup_property_source_link=resources.RollupPropertySourceLink( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.RollupPropertySourceLink() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_rollup_property_source_link( + parent="parent_value", + rollup_property_source_link=resources.RollupPropertySourceLink( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].rollup_property_source_link + mock_val = resources.RollupPropertySourceLink(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_rollup_property_source_link( + analytics_admin.CreateRollupPropertySourceLinkRequest(), + parent="parent_value", + rollup_property_source_link=resources.RollupPropertySourceLink( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteRollupPropertySourceLinkRequest, + dict, + ], +) +def test_delete_rollup_property_source_link(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_rollup_property_source_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest() + + +def test_delete_rollup_property_source_link_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.DeleteRollupPropertySourceLinkRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_rollup_property_source_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest( + name="name_value", + ) + + +def test_delete_rollup_property_source_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_rollup_property_source_link + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_rollup_property_source_link + ] = mock_rpc + request = {} + client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest() + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_rollup_property_source_link + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_rollup_property_source_link + ] = mock_object + + request = {} + await client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.DeleteRollupPropertySourceLinkRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_async_from_dict(): + await test_delete_rollup_property_source_link_async(request_type=dict) + + +def test_delete_rollup_property_source_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + call.return_value = None + client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_rollup_property_source_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_rollup_property_source_link( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_rollup_property_source_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_rollup_property_source_link( + analytics_admin.DeleteRollupPropertySourceLinkRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_rollup_property_source_link( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_rollup_property_source_link( + analytics_admin.DeleteRollupPropertySourceLinkRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ProvisionSubpropertyRequest, + dict, + ], +) +def test_provision_subproperty(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ProvisionSubpropertyResponse() + response = client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionSubpropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionSubpropertyResponse) + + +def test_provision_subproperty_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.provision_subproperty() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionSubpropertyRequest() + + +def test_provision_subproperty_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ProvisionSubpropertyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.provision_subproperty(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionSubpropertyRequest() + + +def test_provision_subproperty_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.provision_subproperty + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.provision_subproperty + ] = mock_rpc + request = {} + client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_subproperty(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_provision_subproperty_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ProvisionSubpropertyResponse() + ) + response = await client.provision_subproperty() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionSubpropertyRequest() + + +@pytest.mark.asyncio +async def test_provision_subproperty_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.provision_subproperty + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.provision_subproperty + ] = mock_object + + request = {} + await client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.provision_subproperty(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_provision_subproperty_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.ProvisionSubpropertyRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ProvisionSubpropertyResponse() + ) + response = await client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionSubpropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionSubpropertyResponse) + + +@pytest.mark.asyncio +async def test_provision_subproperty_async_from_dict(): + await test_provision_subproperty_async(request_type=dict) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateSubpropertyEventFilterRequest, + dict, + ], +) +def test_create_subproperty_event_filter(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + response = client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == "name_value" + assert response.apply_to_property == "apply_to_property_value" + + +def test_create_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest() + + +def test_create_subproperty_event_filter_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.CreateSubpropertyEventFilterRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest( + parent="parent_value", + ) + + +def test_create_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_subproperty_event_filter + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_subproperty_event_filter + ] = mock_rpc + request = {} + client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + ) + response = await client.create_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest() + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_subproperty_event_filter + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_subproperty_event_filter + ] = mock_object + + request = {} + await client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.CreateSubpropertyEventFilterRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + ) + response = await client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == "name_value" + assert response.apply_to_property == "apply_to_property_value" + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_async_from_dict(): + await test_create_subproperty_event_filter_async(request_type=dict) + + +def test_create_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSubpropertyEventFilterRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSubpropertyEventFilterRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter() + ) + await client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_subproperty_event_filter( + parent="parent_value", + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ) + assert arg == mock_val + + +def test_create_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_subproperty_event_filter( + analytics_admin.CreateSubpropertyEventFilterRequest(), + parent="parent_value", + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_subproperty_event_filter( + parent="parent_value", + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_subproperty_event_filter( + analytics_admin.CreateSubpropertyEventFilterRequest(), + parent="parent_value", + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetSubpropertyEventFilterRequest, + dict, + ], +) +def test_get_subproperty_event_filter(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + response = client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) + assert response.name == "name_value" + assert response.apply_to_property == "apply_to_property_value" + + +def test_get_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest() + + +def test_get_subproperty_event_filter_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.GetSubpropertyEventFilterRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest( + name="name_value", + ) + + +def test_get_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_subproperty_event_filter + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_subproperty_event_filter + ] = mock_rpc + request = {} + client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + ) + response = await client.get_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest() + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_subproperty_event_filter + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_subproperty_event_filter + ] = mock_object + + request = {} + await client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.GetSubpropertyEventFilterRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + ) + response = await client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) + assert response.name == "name_value" + assert response.apply_to_property == "apply_to_property_value" + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_async_from_dict(): + await test_get_subproperty_event_filter_async(request_type=dict) + + +def test_get_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSubpropertyEventFilterRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + call.return_value = subproperty_event_filter.SubpropertyEventFilter() + client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSubpropertyEventFilterRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + subproperty_event_filter.SubpropertyEventFilter() + ) + await client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = subproperty_event_filter.SubpropertyEventFilter() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_subproperty_event_filter( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_subproperty_event_filter( + analytics_admin.GetSubpropertyEventFilterRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = subproperty_event_filter.SubpropertyEventFilter() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + subproperty_event_filter.SubpropertyEventFilter() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_subproperty_event_filter( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_subproperty_event_filter( + analytics_admin.GetSubpropertyEventFilterRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListSubpropertyEventFiltersRequest, + dict, + ], +) +def test_list_subproperty_event_filters(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse( + next_page_token="next_page_token_value", + ) + response = client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSubpropertyEventFiltersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubpropertyEventFiltersPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_subproperty_event_filters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_subproperty_event_filters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest() + + +def test_list_subproperty_event_filters_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.ListSubpropertyEventFiltersRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_subproperty_event_filters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_subproperty_event_filters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_subproperty_event_filters + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_subproperty_event_filters + ] = mock_rpc + request = {} + client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_subproperty_event_filters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListSubpropertyEventFiltersResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_subproperty_event_filters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest() + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_subproperty_event_filters + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_subproperty_event_filters + ] = mock_object + + request = {} + await client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_subproperty_event_filters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.ListSubpropertyEventFiltersRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListSubpropertyEventFiltersResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSubpropertyEventFiltersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubpropertyEventFiltersAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_from_dict(): + await test_list_subproperty_event_filters_async(request_type=dict) + + +def test_list_subproperty_event_filters_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSubpropertyEventFiltersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSubpropertyEventFiltersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListSubpropertyEventFiltersResponse() + ) + await client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_subproperty_event_filters_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_subproperty_event_filters( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_subproperty_event_filters_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_subproperty_event_filters( + analytics_admin.ListSubpropertyEventFiltersRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + analytics_admin.ListSubpropertyEventFiltersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_subproperty_event_filters( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_subproperty_event_filters( + analytics_admin.ListSubpropertyEventFiltersRequest(), + parent="parent_value", + ) + + +def test_list_subproperty_event_filters_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="abc", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token="def", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_subproperty_event_filters( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, subproperty_event_filter.SubpropertyEventFilter) + for i in results + ) + + +def test_list_subproperty_event_filters_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="abc", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token="def", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + pages = list(client.list_subproperty_event_filters(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="abc", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token="def", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_subproperty_event_filters( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, subproperty_event_filter.SubpropertyEventFilter) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="abc", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token="def", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_subproperty_event_filters(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateSubpropertyEventFilterRequest, + dict, + ], +) +def test_update_subproperty_event_filter(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + response = client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == "name_value" + assert response.apply_to_property == "apply_to_property_value" + + +def test_update_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + + +def test_update_subproperty_event_filter_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + + +def test_update_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_subproperty_event_filter + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_subproperty_event_filter + ] = mock_rpc + request = {} + client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + ) + response = await client.update_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_subproperty_event_filter + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_subproperty_event_filter + ] = mock_object + + request = {} + await client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.UpdateSubpropertyEventFilterRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value", + apply_to_property="apply_to_property_value", + ) + ) + response = await client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == "name_value" + assert response.apply_to_property == "apply_to_property_value" + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_async_from_dict(): + await test_update_subproperty_event_filter_async(request_type=dict) + + +def test_update_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + + request.subproperty_event_filter.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "subproperty_event_filter.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + + request.subproperty_event_filter.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter() + ) + await client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "subproperty_event_filter.name=name_value", + ) in kw["metadata"] + + +def test_update_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_subproperty_event_filter( + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_subproperty_event_filter( + analytics_admin.UpdateSubpropertyEventFilterRequest(), + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gaa_subproperty_event_filter.SubpropertyEventFilter() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_subproperty_event_filter( + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_subproperty_event_filter( + analytics_admin.UpdateSubpropertyEventFilterRequest(), + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteSubpropertyEventFilterRequest, + dict, + ], +) +def test_delete_subproperty_event_filter(request_type, transport: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest() + + +def test_delete_subproperty_event_filter_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = analytics_admin.DeleteSubpropertyEventFilterRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest( + name="name_value", + ) + + +def test_delete_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_subproperty_event_filter + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_subproperty_event_filter + ] = mock_rpc + request = {} + client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest() + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_subproperty_event_filter + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_subproperty_event_filter + ] = mock_object + + request = {} + await client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_async( + transport: str = "grpc_asyncio", + request_type=analytics_admin.DeleteSubpropertyEventFilterRequest, +): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_async_from_dict(): + await test_delete_subproperty_event_filter_async(request_type=dict) + + +def test_delete_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + call.return_value = None + client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_subproperty_event_filter( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_subproperty_event_filter( + analytics_admin.DeleteSubpropertyEventFilterRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_subproperty_event_filter( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_subproperty_event_filter( + analytics_admin.DeleteSubpropertyEventFilterRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetAccountRequest, + dict, + ], +) +def test_get_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "accounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Account( + name="name_value", + display_name="display_name_value", + region_code="region_code_value", + deleted=True, + gmp_organization="gmp_organization_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Account.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.region_code == "region_code_value" + assert response.deleted is True + assert response.gmp_organization == "gmp_organization_value" + + +def test_get_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_account_rest_required_fields( + request_type=analytics_admin.GetAccountRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Account() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Account.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_account(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_get_account" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_account" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAccountRequest.pb( + analytics_admin.GetAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Account.to_json(resources.Account()) + + request = analytics_admin.GetAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Account() + + client.get_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_account_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetAccountRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "accounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_account(request) + + +def test_get_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "accounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Account.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_account(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=accounts/*}" % client.transport._host, args[1] + ) + + +def test_get_account_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_account( + analytics_admin.GetAccountRequest(), + name="name_value", + ) + + +def test_get_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListAccountsRequest, + dict, + ], +) +def test_list_accounts_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListAccountsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListAccountsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_accounts_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc + + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_accounts_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_list_accounts" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_accounts" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccountsRequest.pb( + analytics_admin.ListAccountsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = analytics_admin.ListAccountsResponse.to_json( + analytics_admin.ListAccountsResponse() + ) + + request = analytics_admin.ListAccountsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccountsResponse() + + client.list_accounts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_accounts_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListAccountsRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_accounts(request) + + +def test_list_accounts_rest_pager(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token="abc", + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token="def", + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListAccountsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Account) for i in results) + + pages = list(client.list_accounts(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteAccountRequest, + dict, + ], +) +def test_delete_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "accounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_account(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc + + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_account_rest_required_fields( + request_type=analytics_admin.DeleteAccountRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_account(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_account" + ) as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteAccountRequest.pb( + analytics_admin.DeleteAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = analytics_admin.DeleteAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_account_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteAccountRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "accounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_account(request) + + +def test_delete_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "accounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_account(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=accounts/*}" % client.transport._host, args[1] + ) + + +def test_delete_account_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_account( + analytics_admin.DeleteAccountRequest(), + name="name_value", + ) + + +def test_delete_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateAccountRequest, + dict, + ], +) +def test_update_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"account": {"name": "accounts/sample1"}} + request_init["account"] = { + "name": "accounts/sample1", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "display_name": "display_name_value", + "region_code": "region_code_value", + "deleted": True, + "gmp_organization": "gmp_organization_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateAccountRequest.meta.fields["account"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["account"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["account"][field])): + del request_init["account"][field][i][subfield] + else: + del request_init["account"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Account( + name="name_value", + display_name="display_name_value", + region_code="region_code_value", + deleted=True, + gmp_organization="gmp_organization_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Account.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.region_code == "region_code_value" + assert response.deleted is True + assert response.gmp_organization == "gmp_organization_value" + + +def test_update_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_account_rest_required_fields( + request_type=analytics_admin.UpdateAccountRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_account._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Account() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Account.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_account(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_account._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "account", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_update_account" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_account" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateAccountRequest.pb( + analytics_admin.UpdateAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Account.to_json(resources.Account()) + + request = analytics_admin.UpdateAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Account() + + client.update_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_account_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateAccountRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"account": {"name": "accounts/sample1"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_account(request) + + +def test_update_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. return_value = resources.Account() # get arguments that satisfy an http rule for this method - sample_request = {"name": "accounts/sample1"} + sample_request = {"account": {"name": "accounts/sample1"}} + + # get truthy value for each flattened field + mock_args = dict( + account=resources.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Account.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_account(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{account.name=accounts/*}" % client.transport._host, args[1] + ) + + +def test_update_account_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ProvisionAccountTicketRequest, + dict, + ], +) +def test_provision_account_ticket_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id="account_ticket_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ProvisionAccountTicketResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.provision_account_ticket(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == "account_ticket_id_value" + + +def test_provision_account_ticket_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.provision_account_ticket + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.provision_account_ticket + ] = mock_rpc + + request = {} + client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_provision_account_ticket_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_provision_account_ticket" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_provision_account_ticket" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ProvisionAccountTicketRequest.pb( + analytics_admin.ProvisionAccountTicketRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + analytics_admin.ProvisionAccountTicketResponse.to_json( + analytics_admin.ProvisionAccountTicketResponse() + ) + ) + + request = analytics_admin.ProvisionAccountTicketRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ProvisionAccountTicketResponse() + + client.provision_account_ticket( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_provision_account_ticket_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ProvisionAccountTicketRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.provision_account_ticket(request) + + +def test_provision_account_ticket_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListAccountSummariesRequest, + dict, + ], +) +def test_list_account_summaries_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListAccountSummariesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListAccountSummariesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_account_summaries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_account_summaries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_account_summaries + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_account_summaries + ] = mock_rpc + + request = {} + client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_summaries_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_list_account_summaries" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_account_summaries" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccountSummariesRequest.pb( + analytics_admin.ListAccountSummariesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + analytics_admin.ListAccountSummariesResponse.to_json( + analytics_admin.ListAccountSummariesResponse() + ) + ) + + request = analytics_admin.ListAccountSummariesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccountSummariesResponse() + + client.list_account_summaries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_account_summaries_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListAccountSummariesRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_account_summaries(request) + + +def test_list_account_summaries_rest_pager(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token="abc", + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token="def", + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListAccountSummariesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_account_summaries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccountSummary) for i in results) + + pages = list(client.list_account_summaries(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetPropertyRequest, + dict, + ], +) +def test_get_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property( + name="name_value", + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent="parent_value", + display_name="display_name_value", + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone="time_zone_value", + currency_code="currency_code_value", + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account="account_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == "name_value" + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == "parent_value" + assert response.display_name == "display_name_value" + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == "account_value" + + +def test_get_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_property] = mock_rpc + + request = {} + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_property_rest_required_fields( + request_type=analytics_admin.GetPropertyRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_property(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_get_property" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_property" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetPropertyRequest.pb( + analytics_admin.GetPropertyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Property.to_json(resources.Property()) + + request = analytics_admin.GetPropertyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.get_property( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_property_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetPropertyRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_property(request) + + +def test_get_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_property(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*}" % client.transport._host, args[1] + ) + + +def test_get_property_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_property( + analytics_admin.GetPropertyRequest(), + name="name_value", + ) + + +def test_get_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListPropertiesRequest, + dict, + ], +) +def test_list_properties_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListPropertiesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListPropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_properties(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_properties_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_properties in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_properties] = mock_rpc + + request = {} + client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_properties_rest_required_fields( + request_type=analytics_admin.ListPropertiesRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "filter" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["filter"] = "filter_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_properties._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "filter" in jsonified_request + assert jsonified_request["filter"] == "filter_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListPropertiesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = analytics_admin.ListPropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_properties(request) + + expected_params = [ + ( + "filter", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_properties_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_properties._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("filter",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_properties_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_list_properties" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_properties" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListPropertiesRequest.pb( + analytics_admin.ListPropertiesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = analytics_admin.ListPropertiesResponse.to_json( + analytics_admin.ListPropertiesResponse() + ) + + request = analytics_admin.ListPropertiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListPropertiesResponse() + + client.list_properties( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_properties_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListPropertiesRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_properties(request) + + +def test_list_properties_rest_pager(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token="abc", + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token="def", + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token="ghi", + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListPropertiesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_properties(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Property) for i in results) + + pages = list(client.list_properties(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreatePropertyRequest, + dict, + ], +) +def test_create_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["property"] = { + "name": "name_value", + "property_type": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "parent": "parent_value", + "display_name": "display_name_value", + "industry_category": 1, + "time_zone": "time_zone_value", + "currency_code": "currency_code_value", + "service_level": 1, + "delete_time": {}, + "expire_time": {}, + "account": "account_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreatePropertyRequest.meta.fields["property"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["property"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["property"][field])): + del request_init["property"][field][i][subfield] + else: + del request_init["property"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property( + name="name_value", + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent="parent_value", + display_name="display_name_value", + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone="time_zone_value", + currency_code="currency_code_value", + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account="account_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == "name_value" + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == "parent_value" + assert response.display_name == "display_name_value" + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == "account_value" + + +def test_create_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_property] = mock_rpc + + request = {} + client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_property_rest_required_fields( + request_type=analytics_admin.CreatePropertyRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_property(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_create_property" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_property" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreatePropertyRequest.pb( + analytics_admin.CreatePropertyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Property.to_json(resources.Property()) + + request = analytics_admin.CreatePropertyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.create_property( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_property_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreatePropertyRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_property(request) + + +def test_create_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + property=resources.Property(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_property(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/properties" % client.transport._host, args[1] + ) + + +def test_create_property_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name="name_value"), + ) + + +def test_create_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeletePropertyRequest, + dict, + ], +) +def test_delete_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property( + name="name_value", + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent="parent_value", + display_name="display_name_value", + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone="time_zone_value", + currency_code="currency_code_value", + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account="account_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == "name_value" + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == "parent_value" + assert response.display_name == "display_name_value" + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == "account_value" + + +def test_delete_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_property] = mock_rpc + + request = {} + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_property_rest_required_fields( + request_type=analytics_admin.DeletePropertyRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_property(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_delete_property" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_property" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.DeletePropertyRequest.pb( + analytics_admin.DeletePropertyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Property.to_json(resources.Property()) + + request = analytics_admin.DeletePropertyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.delete_property( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_property_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeletePropertyRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_property(request) + + +def test_delete_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_property(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*}" % client.transport._host, args[1] + ) + + +def test_delete_property_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_property( + analytics_admin.DeletePropertyRequest(), + name="name_value", + ) + + +def test_delete_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdatePropertyRequest, + dict, + ], +) +def test_update_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"property": {"name": "properties/sample1"}} + request_init["property"] = { + "name": "properties/sample1", + "property_type": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "parent": "parent_value", + "display_name": "display_name_value", + "industry_category": 1, + "time_zone": "time_zone_value", + "currency_code": "currency_code_value", + "service_level": 1, + "delete_time": {}, + "expire_time": {}, + "account": "account_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdatePropertyRequest.meta.fields["property"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["property"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["property"][field])): + del request_init["property"][field][i][subfield] + else: + del request_init["property"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property( + name="name_value", + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent="parent_value", + display_name="display_name_value", + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone="time_zone_value", + currency_code="currency_code_value", + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account="account_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == "name_value" + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == "parent_value" + assert response.display_name == "display_name_value" + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == "time_zone_value" + assert response.currency_code == "currency_code_value" + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == "account_value" + + +def test_update_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_property] = mock_rpc + + request = {} + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_property_rest_required_fields( + request_type=analytics_admin.UpdatePropertyRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_property._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_property(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_property._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "property", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_update_property" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_property" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdatePropertyRequest.pb( + analytics_admin.UpdatePropertyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Property.to_json(resources.Property()) + + request = analytics_admin.UpdatePropertyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.update_property( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_property_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdatePropertyRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"property": {"name": "properties/sample1"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_property(request) + + +def test_update_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {"property": {"name": "properties/sample1"}} + + # get truthy value for each flattened field + mock_args = dict( + property=resources.Property(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.Property.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_property(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{property.name=properties/*}" % client.transport._host, args[1] + ) + + +def test_update_property_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateFirebaseLinkRequest, + dict, + ], +) +def test_create_firebase_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request_init["firebase_link"] = { + "name": "name_value", + "project": "project_value", + "create_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateFirebaseLinkRequest.meta.fields["firebase_link"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["firebase_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["firebase_link"][field])): + del request_init["firebase_link"][field][i][subfield] + else: + del request_init["firebase_link"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.FirebaseLink( + name="name_value", + project="project_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.FirebaseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_firebase_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == "name_value" + assert response.project == "project_value" + + +def test_create_firebase_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_firebase_link in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_firebase_link + ] = mock_rpc + + request = {} + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_firebase_link_rest_required_fields( + request_type=analytics_admin.CreateFirebaseLinkRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_firebase_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_firebase_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.FirebaseLink() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.FirebaseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_firebase_link(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_firebase_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_firebase_link._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "firebaseLink", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_firebase_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_create_firebase_link" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_firebase_link" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateFirebaseLinkRequest.pb( + analytics_admin.CreateFirebaseLinkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.FirebaseLink.to_json( + resources.FirebaseLink() + ) + + request = analytics_admin.CreateFirebaseLinkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.FirebaseLink() + + client.create_firebase_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_firebase_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateFirebaseLinkRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_firebase_link(request) + + +def test_create_firebase_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.FirebaseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + firebase_link=resources.FirebaseLink(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.FirebaseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_firebase_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=properties/*}/firebaseLinks" % client.transport._host, + args[1], + ) + + +def test_create_firebase_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent="parent_value", + firebase_link=resources.FirebaseLink(name="name_value"), + ) + + +def test_create_firebase_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.DeleteFirebaseLinkRequest, + dict, + ], +) +def test_delete_firebase_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1/firebaseLinks/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_firebase_link(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_firebase_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_firebase_link in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_firebase_link + ] = mock_rpc + + request = {} + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_firebase_link_rest_required_fields( + request_type=analytics_admin.DeleteFirebaseLinkRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_firebase_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_firebase_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_firebase_link(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_firebase_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_firebase_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_firebase_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_firebase_link" + ) as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteFirebaseLinkRequest.pb( + analytics_admin.DeleteFirebaseLinkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = analytics_admin.DeleteFirebaseLinkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_firebase_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_firebase_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteFirebaseLinkRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1/firebaseLinks/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_firebase_link(request) + + +def test_delete_firebase_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/firebaseLinks/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_firebase_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/firebaseLinks/*}" % client.transport._host, + args[1], + ) + + +def test_delete_firebase_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name="name_value", + ) + + +def test_delete_firebase_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ListFirebaseLinksRequest, + dict, + ], +) +def test_list_firebase_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListFirebaseLinksResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_firebase_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_firebase_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_firebase_links in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_firebase_links + ] = mock_rpc + + request = {} + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_firebase_links_rest_required_fields( + request_type=analytics_admin.ListFirebaseLinksRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_firebase_links._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_firebase_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListFirebaseLinksResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_firebase_links(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_firebase_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_firebase_links._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_firebase_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_list_firebase_links" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_firebase_links" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListFirebaseLinksRequest.pb( + analytics_admin.ListFirebaseLinksRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = analytics_admin.ListFirebaseLinksResponse.to_json( + analytics_admin.ListFirebaseLinksResponse() + ) + + request = analytics_admin.ListFirebaseLinksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListFirebaseLinksResponse() + + client.list_firebase_links( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_firebase_links_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListFirebaseLinksRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_firebase_links(request) + + +def test_list_firebase_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListFirebaseLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -57879,23 +67734,24 @@ def test_get_account_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Account.pb(return_value) + return_value = analytics_admin.ListFirebaseLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_account(**mock_args) + client.list_firebase_links(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=accounts/*}" % client.transport._host, args[1] + "%s/v1alpha/{parent=properties/*}/firebaseLinks" % client.transport._host, + args[1], ) -def test_get_account_rest_flattened_error(transport: str = "rest"): +def test_list_firebase_links_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -57904,59 +67760,118 @@ def test_get_account_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_account( - analytics_admin.GetAccountRequest(), - name="name_value", + client.list_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent="parent_value", ) -def test_get_account_rest_error(): +def test_list_firebase_links_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token="def", + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListFirebaseLinksResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_firebase_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.FirebaseLink) for i in results) + + pages = list(client.list_firebase_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListAccountsRequest, + analytics_admin.GetGlobalSiteTagRequest, dict, ], ) -def test_list_accounts_rest(request_type): +def test_get_global_site_tag_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/dataStreams/sample2/globalSiteTag"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAccountsResponse( - next_page_token="next_page_token_value", + return_value = resources.GlobalSiteTag( + name="name_value", + snippet="snippet_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAccountsResponse.pb(return_value) + return_value = resources.GlobalSiteTag.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_accounts(request) + response = client.get_global_site_tag(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.GlobalSiteTag) + assert response.name == "name_value" + assert response.snippet == "snippet_value" -def test_list_accounts_rest_use_cached_wrapped_rpc(): +def test_get_global_site_tag_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -57970,30 +67885,117 @@ def test_list_accounts_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_accounts in client._transport._wrapped_methods + assert ( + client._transport.get_global_site_tag in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_global_site_tag + ] = mock_rpc request = {} - client.list_accounts(request) + client.get_global_site_tag(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_accounts(request) + client.get_global_site_tag(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 +def test_get_global_site_tag_rest_required_fields( + request_type=analytics_admin.GetGlobalSiteTagRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_global_site_tag._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_global_site_tag._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GlobalSiteTag() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.GlobalSiteTag.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_global_site_tag(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_global_site_tag_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_global_site_tag._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_accounts_rest_interceptors(null_interceptor): +def test_get_global_site_tag_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -58006,14 +68008,14 @@ def test_list_accounts_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_accounts" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_global_site_tag" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_accounts" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_global_site_tag" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListAccountsRequest.pb( - analytics_admin.ListAccountsRequest() + pb_message = analytics_admin.GetGlobalSiteTagRequest.pb( + analytics_admin.GetGlobalSiteTagRequest() ) transcode.return_value = { "method": "post", @@ -58025,19 +68027,19 @@ def test_list_accounts_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListAccountsResponse.to_json( - analytics_admin.ListAccountsResponse() + req.return_value._content = resources.GlobalSiteTag.to_json( + resources.GlobalSiteTag() ) - request = analytics_admin.ListAccountsRequest() + request = analytics_admin.GetGlobalSiteTagRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListAccountsResponse() + post.return_value = resources.GlobalSiteTag() - client.list_accounts( + client.get_global_site_tag( request, metadata=[ ("key", "val"), @@ -58049,8 +68051,8 @@ def test_list_accounts_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_accounts_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListAccountsRequest +def test_get_global_site_tag_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetGlobalSiteTagRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -58058,7 +68060,7 @@ def test_list_accounts_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/dataStreams/sample2/globalSiteTag"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -58070,108 +68072,199 @@ def test_list_accounts_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_accounts(request) + client.get_global_site_tag(request) -def test_list_accounts_rest_pager(transport: str = "rest"): +def test_get_global_site_tag_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListAccountsResponse( - accounts=[ - resources.Account(), - resources.Account(), - resources.Account(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccountsResponse( - accounts=[], - next_page_token="def", - ), - analytics_admin.ListAccountsResponse( - accounts=[ - resources.Account(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccountsResponse( - accounts=[ - resources.Account(), - resources.Account(), - ], - ), + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.GlobalSiteTag() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "properties/sample1/dataStreams/sample2/globalSiteTag" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - # Two responses for two calls - response = response + response + mock_args.update(sample_request) - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListAccountsResponse.to_json(x) for x in response + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.GlobalSiteTag.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_global_site_tag(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/dataStreams/*/globalSiteTag}" + % client.transport._host, + args[1], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {} - pager = client.list_accounts(request=sample_request) +def test_get_global_site_tag_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Account) for i in results) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_global_site_tag( + analytics_admin.GetGlobalSiteTagRequest(), + name="name_value", + ) - pages = list(client.list_accounts(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + +def test_get_global_site_tag_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteAccountRequest, + analytics_admin.CreateGoogleAdsLinkRequest, dict, ], ) -def test_delete_account_rest(request_type): +def test_create_google_ads_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1"} + request_init = {"parent": "properties/sample1"} + request_init["google_ads_link"] = { + "name": "name_value", + "customer_id": "customer_id_value", + "can_manage_clients": True, + "ads_personalization_enabled": {"value": True}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "creator_email_address": "creator_email_address_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateGoogleAdsLinkRequest.meta.fields[ + "google_ads_link" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["google_ads_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["google_ads_link"][field])): + del request_init["google_ads_link"][field][i][subfield] + else: + del request_init["google_ads_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.GoogleAdsLink( + name="name_value", + customer_id="customer_id_value", + can_manage_clients=True, + creator_email_address="creator_email_address_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.GoogleAdsLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_account(request) + response = client.create_google_ads_link(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == "name_value" + assert response.customer_id == "customer_id_value" + assert response.can_manage_clients is True + assert response.creator_email_address == "creator_email_address_value" -def test_delete_account_rest_use_cached_wrapped_rpc(): +def test_create_google_ads_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -58185,35 +68278,40 @@ def test_delete_account_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_account in client._transport._wrapped_methods + assert ( + client._transport.create_google_ads_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_google_ads_link + ] = mock_rpc request = {} - client.delete_account(request) + client.create_google_ads_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_account(request) + client.create_google_ads_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_account_rest_required_fields( - request_type=analytics_admin.DeleteAccountRequest, +def test_create_google_ads_link_rest_required_fields( + request_type=analytics_admin.CreateGoogleAdsLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -58224,21 +68322,21 @@ def test_delete_account_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_account._get_unset_required_fields(jsonified_request) + ).create_google_ads_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_account._get_unset_required_fields(jsonified_request) + ).create_google_ads_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -58247,7 +68345,7 @@ def test_delete_account_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.GoogleAdsLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -58259,36 +68357,48 @@ def test_delete_account_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.GoogleAdsLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_account(request) + response = client.create_google_ads_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_account_rest_unset_required_fields(): +def test_create_google_ads_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "googleAdsLink", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_account_rest_interceptors(null_interceptor): +def test_create_google_ads_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -58301,11 +68411,14 @@ def test_delete_account_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_account" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_google_ads_link" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_google_ads_link" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteAccountRequest.pb( - analytics_admin.DeleteAccountRequest() + post.assert_not_called() + pb_message = analytics_admin.CreateGoogleAdsLinkRequest.pb( + analytics_admin.CreateGoogleAdsLinkRequest() ) transcode.return_value = { "method": "post", @@ -58317,15 +68430,19 @@ def test_delete_account_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.GoogleAdsLink.to_json( + resources.GoogleAdsLink() + ) - request = analytics_admin.DeleteAccountRequest() + request = analytics_admin.CreateGoogleAdsLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.GoogleAdsLink() - client.delete_account( + client.create_google_ads_link( request, metadata=[ ("key", "val"), @@ -58334,10 +68451,11 @@ def test_delete_account_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_account_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteAccountRequest +def test_create_google_ads_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateGoogleAdsLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -58345,7 +68463,7 @@ def test_delete_account_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -58357,10 +68475,10 @@ def test_delete_account_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_account(request) + client.create_google_ads_link(request) -def test_delete_account_rest_flattened(): +def test_create_google_ads_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -58369,36 +68487,40 @@ def test_delete_account_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.GoogleAdsLink() # get arguments that satisfy an http rule for this method - sample_request = {"name": "accounts/sample1"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + google_ads_link=resources.GoogleAdsLink(name="name_value"), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.GoogleAdsLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_account(**mock_args) + client.create_google_ads_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=accounts/*}" % client.transport._host, args[1] + "%s/v1alpha/{parent=properties/*}/googleAdsLinks" % client.transport._host, + args[1], ) -def test_delete_account_rest_flattened_error(transport: str = "rest"): +def test_create_google_ads_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -58407,13 +68529,14 @@ def test_delete_account_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_account( - analytics_admin.DeleteAccountRequest(), - name="name_value", + client.create_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent="parent_value", + google_ads_link=resources.GoogleAdsLink(name="name_value"), ) -def test_delete_account_rest_error(): +def test_create_google_ads_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -58422,32 +68545,37 @@ def test_delete_account_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAccountRequest, + analytics_admin.UpdateGoogleAdsLinkRequest, dict, ], ) -def test_update_account_rest(request_type): +def test_update_google_ads_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"account": {"name": "accounts/sample1"}} - request_init["account"] = { - "name": "accounts/sample1", + request_init = { + "google_ads_link": {"name": "properties/sample1/googleAdsLinks/sample2"} + } + request_init["google_ads_link"] = { + "name": "properties/sample1/googleAdsLinks/sample2", + "customer_id": "customer_id_value", + "can_manage_clients": True, + "ads_personalization_enabled": {"value": True}, "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, - "display_name": "display_name_value", - "region_code": "region_code_value", - "deleted": True, + "creator_email_address": "creator_email_address_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateAccountRequest.meta.fields["account"] + test_field = analytics_admin.UpdateGoogleAdsLinkRequest.meta.fields[ + "google_ads_link" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -58475,7 +68603,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["account"].items(): # pragma: NO COVER + for field, value in request_init["google_ads_link"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -58505,42 +68633,42 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["account"][field])): - del request_init["account"][field][i][subfield] + for i in range(0, len(request_init["google_ads_link"][field])): + del request_init["google_ads_link"][field][i][subfield] else: - del request_init["account"][field][subfield] + del request_init["google_ads_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Account( + return_value = resources.GoogleAdsLink( name="name_value", - display_name="display_name_value", - region_code="region_code_value", - deleted=True, + customer_id="customer_id_value", + can_manage_clients=True, + creator_email_address="creator_email_address_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Account.pb(return_value) + return_value = resources.GoogleAdsLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_account(request) + response = client.update_google_ads_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Account) + assert isinstance(response, resources.GoogleAdsLink) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.region_code == "region_code_value" - assert response.deleted is True + assert response.customer_id == "customer_id_value" + assert response.can_manage_clients is True + assert response.creator_email_address == "creator_email_address_value" -def test_update_account_rest_use_cached_wrapped_rpc(): +def test_update_google_ads_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -58554,30 +68682,35 @@ def test_update_account_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_account in client._transport._wrapped_methods + assert ( + client._transport.update_google_ads_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_google_ads_link + ] = mock_rpc request = {} - client.update_account(request) + client.update_google_ads_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_account(request) + client.update_google_ads_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_account_rest_required_fields( - request_type=analytics_admin.UpdateAccountRequest, +def test_update_google_ads_link_rest_required_fields( + request_type=analytics_admin.UpdateGoogleAdsLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -58592,14 +68725,14 @@ def test_update_account_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_account._get_unset_required_fields(jsonified_request) + ).update_google_ads_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_account._get_unset_required_fields(jsonified_request) + ).update_google_ads_link._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) @@ -58613,7 +68746,7 @@ def test_update_account_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Account() + return_value = resources.GoogleAdsLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -58635,38 +68768,30 @@ def test_update_account_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Account.pb(return_value) + return_value = resources.GoogleAdsLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_account(request) + response = client.update_google_ads_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_account_rest_unset_required_fields(): +def test_update_google_ads_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_account._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "account", - "updateMask", - ) - ) - ) + unset_fields = transport.update_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_account_rest_interceptors(null_interceptor): +def test_update_google_ads_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -58679,14 +68804,14 @@ def test_update_account_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_account" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_google_ads_link" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_account" + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_google_ads_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateAccountRequest.pb( - analytics_admin.UpdateAccountRequest() + pb_message = analytics_admin.UpdateGoogleAdsLinkRequest.pb( + analytics_admin.UpdateGoogleAdsLinkRequest() ) transcode.return_value = { "method": "post", @@ -58698,17 +68823,19 @@ def test_update_account_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Account.to_json(resources.Account()) + req.return_value._content = resources.GoogleAdsLink.to_json( + resources.GoogleAdsLink() + ) - request = analytics_admin.UpdateAccountRequest() + request = analytics_admin.UpdateGoogleAdsLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Account() + post.return_value = resources.GoogleAdsLink() - client.update_account( + client.update_google_ads_link( request, metadata=[ ("key", "val"), @@ -58720,8 +68847,8 @@ def test_update_account_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_account_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateAccountRequest +def test_update_google_ads_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateGoogleAdsLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -58729,7 +68856,9 @@ def test_update_account_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"account": {"name": "accounts/sample1"}} + request_init = { + "google_ads_link": {"name": "properties/sample1/googleAdsLinks/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -58741,10 +68870,10 @@ def test_update_account_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_account(request) + client.update_google_ads_link(request) -def test_update_account_rest_flattened(): +def test_update_google_ads_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -58753,14 +68882,16 @@ def test_update_account_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Account() + return_value = resources.GoogleAdsLink() # get arguments that satisfy an http rule for this method - sample_request = {"account": {"name": "accounts/sample1"}} + sample_request = { + "google_ads_link": {"name": "properties/sample1/googleAdsLinks/sample2"} + } # get truthy value for each flattened field mock_args = dict( - account=resources.Account(name="name_value"), + google_ads_link=resources.GoogleAdsLink(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -58769,23 +68900,25 @@ def test_update_account_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Account.pb(return_value) + return_value = resources.GoogleAdsLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_account(**mock_args) + client.update_google_ads_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{account.name=accounts/*}" % client.transport._host, args[1] + "%s/v1alpha/{google_ads_link.name=properties/*/googleAdsLinks/*}" + % client.transport._host, + args[1], ) -def test_update_account_rest_flattened_error(transport: str = "rest"): +def test_update_google_ads_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -58794,14 +68927,14 @@ def test_update_account_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_account( - analytics_admin.UpdateAccountRequest(), - account=resources.Account(name="name_value"), + client.update_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_account_rest_error(): +def test_update_google_ads_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -58810,44 +68943,39 @@ def test_update_account_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ProvisionAccountTicketRequest, + analytics_admin.DeleteGoogleAdsLinkRequest, dict, ], ) -def test_provision_account_ticket_rest(request_type): +def test_delete_google_ads_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/googleAdsLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ProvisionAccountTicketResponse( - account_ticket_id="account_ticket_id_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ProvisionAccountTicketResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.provision_account_ticket(request) + response = client.delete_google_ads_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) - assert response.account_ticket_id == "account_ticket_id_value" + assert response is None -def test_provision_account_ticket_rest_use_cached_wrapped_rpc(): +def test_delete_google_ads_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -58862,7 +68990,7 @@ def test_provision_account_ticket_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.provision_account_ticket + client._transport.delete_google_ads_link in client._transport._wrapped_methods ) @@ -58872,194 +69000,104 @@ def test_provision_account_ticket_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.provision_account_ticket + client._transport.delete_google_ads_link ] = mock_rpc request = {} - client.provision_account_ticket(request) + client.delete_google_ads_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.provision_account_ticket(request) + client.delete_google_ads_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_provision_account_ticket_rest_interceptors(null_interceptor): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.AnalyticsAdminServiceRestInterceptor(), - ) - client = AnalyticsAdminServiceClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_provision_account_ticket" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_provision_account_ticket" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ProvisionAccountTicketRequest.pb( - analytics_admin.ProvisionAccountTicketRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ProvisionAccountTicketResponse.to_json( - analytics_admin.ProvisionAccountTicketResponse() - ) - ) - - request = analytics_admin.ProvisionAccountTicketRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = analytics_admin.ProvisionAccountTicketResponse() - - client.provision_account_ticket( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_provision_account_ticket_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ProvisionAccountTicketRequest +def test_delete_google_ads_link_rest_required_fields( + request_type=analytics_admin.DeleteGoogleAdsLinkRequest, ): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + transport_class = transports.AnalyticsAdminServiceRestTransport - # send a request that will satisfy transcoding request_init = {} + request_init["name"] = "" request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.provision_account_ticket(request) + # verify fields with default values are dropped + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_google_ads_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) -def test_provision_account_ticket_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_google_ads_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.ListAccountSummariesRequest, - dict, - ], -) -def test_list_account_summaries_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - - # send a request that will satisfy transcoding - request_init = {} request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAccountSummariesResponse( - next_page_token="next_page_token_value", - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListAccountSummariesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_account_summaries(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountSummariesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_account_summaries_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + response_value = Response() + response_value.status_code = 200 + json_return_value = "" - # Ensure method has been cached - assert ( - client._transport.list_account_summaries - in client._transport._wrapped_methods - ) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.list_account_summaries - ] = mock_rpc + response = client.delete_google_ads_link(request) - request = {} - client.list_account_summaries(request) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.list_account_summaries(request) +def test_delete_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + unset_fields = transport.delete_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_account_summaries_rest_interceptors(null_interceptor): +def test_delete_google_ads_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -59072,14 +69110,11 @@ def test_list_account_summaries_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_account_summaries" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_account_summaries" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_google_ads_link" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ListAccountSummariesRequest.pb( - analytics_admin.ListAccountSummariesRequest() + pb_message = analytics_admin.DeleteGoogleAdsLinkRequest.pb( + analytics_admin.DeleteGoogleAdsLinkRequest() ) transcode.return_value = { "method": "post", @@ -59088,24 +69123,18 @@ def test_list_account_summaries_rest_interceptors(null_interceptor): "query_params": pb_message, } - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListAccountSummariesResponse.to_json( - analytics_admin.ListAccountSummariesResponse() - ) - ) - - request = analytics_admin.ListAccountSummariesRequest() + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = analytics_admin.DeleteGoogleAdsLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListAccountSummariesResponse() - client.list_account_summaries( + client.delete_google_ads_link( request, metadata=[ ("key", "val"), @@ -59114,11 +69143,10 @@ def test_list_account_summaries_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_list_account_summaries_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListAccountSummariesRequest +def test_delete_google_ads_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteGoogleAdsLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -59126,7 +69154,7 @@ def test_list_account_summaries_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/googleAdsLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -59138,129 +69166,110 @@ def test_list_account_summaries_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_account_summaries(request) + client.delete_google_ads_link(request) -def test_list_account_summaries_rest_pager(transport: str = "rest"): +def test_delete_google_ads_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListAccountSummariesResponse( - account_summaries=[ - resources.AccountSummary(), - resources.AccountSummary(), - resources.AccountSummary(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccountSummariesResponse( - account_summaries=[], - next_page_token="def", - ), - analytics_admin.ListAccountSummariesResponse( - account_summaries=[ - resources.AccountSummary(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccountSummariesResponse( - account_summaries=[ - resources.AccountSummary(), - resources.AccountSummary(), - ], - ), + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/googleAdsLinks/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - # Two responses for two calls - response = response + response + mock_args.update(sample_request) - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListAccountSummariesResponse.to_json(x) for x in response + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_google_ads_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/googleAdsLinks/*}" % client.transport._host, + args[1], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {} - pager = client.list_account_summaries(request=sample_request) +def test_delete_google_ads_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.AccountSummary) for i in results) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name="name_value", + ) - pages = list(client.list_account_summaries(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + +def test_delete_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetPropertyRequest, + analytics_admin.ListGoogleAdsLinksRequest, dict, ], ) -def test_get_property_rest(request_type): +def test_list_google_ads_links_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property( - name="name_value", - property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, - parent="parent_value", - display_name="display_name_value", - industry_category=resources.IndustryCategory.AUTOMOTIVE, - time_zone="time_zone_value", - currency_code="currency_code_value", - service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, - account="account_value", + return_value = analytics_admin.ListGoogleAdsLinksResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_property(request) + response = client.list_google_ads_links(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Property) - assert response.name == "name_value" - assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE - assert response.time_zone == "time_zone_value" - assert response.currency_code == "currency_code_value" - assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD - assert response.account == "account_value" + assert isinstance(response, pagers.ListGoogleAdsLinksPager) + assert response.next_page_token == "next_page_token_value" -def test_get_property_rest_use_cached_wrapped_rpc(): +def test_list_google_ads_links_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -59274,35 +69283,40 @@ def test_get_property_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_property in client._transport._wrapped_methods + assert ( + client._transport.list_google_ads_links + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_property] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_google_ads_links + ] = mock_rpc request = {} - client.get_property(request) + client.list_google_ads_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_property(request) + client.list_google_ads_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_property_rest_required_fields( - request_type=analytics_admin.GetPropertyRequest, +def test_list_google_ads_links_rest_required_fields( + request_type=analytics_admin.ListGoogleAdsLinksRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -59313,21 +69327,28 @@ def test_get_property_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_property._get_unset_required_fields(jsonified_request) + ).list_google_ads_links._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_property._get_unset_required_fields(jsonified_request) + ).list_google_ads_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -59336,7 +69357,7 @@ def test_get_property_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = analytics_admin.ListGoogleAdsLinksResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -59357,30 +69378,38 @@ def test_get_property_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_property(request) + response = client.list_google_ads_links(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_property_rest_unset_required_fields(): +def test_list_google_ads_links_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_property._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_google_ads_links._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_property_rest_interceptors(null_interceptor): +def test_list_google_ads_links_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -59393,14 +69422,14 @@ def test_get_property_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_property" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_google_ads_links" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_property" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_google_ads_links" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetPropertyRequest.pb( - analytics_admin.GetPropertyRequest() + pb_message = analytics_admin.ListGoogleAdsLinksRequest.pb( + analytics_admin.ListGoogleAdsLinksRequest() ) transcode.return_value = { "method": "post", @@ -59412,17 +69441,19 @@ def test_get_property_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Property.to_json(resources.Property()) + req.return_value._content = analytics_admin.ListGoogleAdsLinksResponse.to_json( + analytics_admin.ListGoogleAdsLinksResponse() + ) - request = analytics_admin.GetPropertyRequest() + request = analytics_admin.ListGoogleAdsLinksRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Property() + post.return_value = analytics_admin.ListGoogleAdsLinksResponse() - client.get_property( + client.list_google_ads_links( request, metadata=[ ("key", "val"), @@ -59434,8 +69465,8 @@ def test_get_property_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_property_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetPropertyRequest +def test_list_google_ads_links_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListGoogleAdsLinksRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -59443,7 +69474,7 @@ def test_get_property_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -59455,10 +69486,10 @@ def test_get_property_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_property(request) + client.list_google_ads_links(request) -def test_get_property_rest_flattened(): +def test_list_google_ads_links_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -59467,14 +69498,14 @@ def test_get_property_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = analytics_admin.ListGoogleAdsLinksResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -59482,23 +69513,24 @@ def test_get_property_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_property(**mock_args) + client.list_google_ads_links(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*}" % client.transport._host, args[1] + "%s/v1alpha/{parent=properties/*}/googleAdsLinks" % client.transport._host, + args[1], ) -def test_get_property_rest_flattened_error(transport: str = "rest"): +def test_list_google_ads_links_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -59507,59 +69539,126 @@ def test_get_property_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_property( - analytics_admin.GetPropertyRequest(), - name="name_value", + client.list_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent="parent_value", ) -def test_get_property_rest_error(): +def test_list_google_ads_links_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token="def", + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListGoogleAdsLinksResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_google_ads_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.GoogleAdsLink) for i in results) + + pages = list(client.list_google_ads_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListPropertiesRequest, + analytics_admin.GetDataSharingSettingsRequest, dict, ], ) -def test_list_properties_rest(request_type): +def test_get_data_sharing_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "accounts/sample1/dataSharingSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListPropertiesResponse( - next_page_token="next_page_token_value", + return_value = resources.DataSharingSettings( + name="name_value", + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListPropertiesResponse.pb(return_value) + return_value = resources.DataSharingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_properties(request) + response = client.get_data_sharing_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPropertiesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.DataSharingSettings) + assert response.name == "name_value" + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True -def test_list_properties_rest_use_cached_wrapped_rpc(): +def test_get_data_sharing_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -59573,35 +69672,40 @@ def test_list_properties_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_properties in client._transport._wrapped_methods + assert ( + client._transport.get_data_sharing_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_properties] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_data_sharing_settings + ] = mock_rpc request = {} - client.list_properties(request) + client.get_data_sharing_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_properties(request) + client.get_data_sharing_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_properties_rest_required_fields( - request_type=analytics_admin.ListPropertiesRequest, +def test_get_data_sharing_settings_rest_required_fields( + request_type=analytics_admin.GetDataSharingSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["filter"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -59609,36 +69713,24 @@ def test_list_properties_rest_required_fields( ) # verify fields with default values are dropped - assert "filter" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_properties._get_unset_required_fields(jsonified_request) + ).get_data_sharing_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "filter" in jsonified_request - assert jsonified_request["filter"] == request_init["filter"] - jsonified_request["filter"] = "filter_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_properties._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "page_size", - "page_token", - "show_deleted", - ) - ) + ).get_data_sharing_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "filter" in jsonified_request - assert jsonified_request["filter"] == "filter_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -59647,7 +69739,7 @@ def test_list_properties_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListPropertiesResponse() + return_value = resources.DataSharingSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -59668,46 +69760,30 @@ def test_list_properties_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListPropertiesResponse.pb(return_value) + return_value = resources.DataSharingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_properties(request) + response = client.get_data_sharing_settings(request) - expected_params = [ - ( - "filter", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_properties_rest_unset_required_fields(): +def test_get_data_sharing_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_properties._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "pageSize", - "pageToken", - "showDeleted", - ) - ) - & set(("filter",)) - ) + unset_fields = transport.get_data_sharing_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_properties_rest_interceptors(null_interceptor): +def test_get_data_sharing_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -59720,14 +69796,15 @@ def test_list_properties_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_properties" + transports.AnalyticsAdminServiceRestInterceptor, + "post_get_data_sharing_settings", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_properties" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_sharing_settings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListPropertiesRequest.pb( - analytics_admin.ListPropertiesRequest() + pb_message = analytics_admin.GetDataSharingSettingsRequest.pb( + analytics_admin.GetDataSharingSettingsRequest() ) transcode.return_value = { "method": "post", @@ -59739,19 +69816,19 @@ def test_list_properties_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListPropertiesResponse.to_json( - analytics_admin.ListPropertiesResponse() + req.return_value._content = resources.DataSharingSettings.to_json( + resources.DataSharingSettings() ) - request = analytics_admin.ListPropertiesRequest() + request = analytics_admin.GetDataSharingSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListPropertiesResponse() + post.return_value = resources.DataSharingSettings() - client.list_properties( + client.get_data_sharing_settings( request, metadata=[ ("key", "val"), @@ -59763,8 +69840,8 @@ def test_list_properties_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_properties_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListPropertiesRequest +def test_get_data_sharing_settings_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetDataSharingSettingsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -59772,7 +69849,7 @@ def test_list_properties_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "accounts/sample1/dataSharingSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -59784,211 +69861,118 @@ def test_list_properties_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_properties(request) + client.get_data_sharing_settings(request) -def test_list_properties_rest_pager(transport: str = "rest"): +def test_get_data_sharing_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListPropertiesResponse( - properties=[ - resources.Property(), - resources.Property(), - resources.Property(), - ], - next_page_token="abc", - ), - analytics_admin.ListPropertiesResponse( - properties=[], - next_page_token="def", - ), - analytics_admin.ListPropertiesResponse( - properties=[ - resources.Property(), - ], - next_page_token="ghi", - ), - analytics_admin.ListPropertiesResponse( - properties=[ - resources.Property(), - resources.Property(), - ], - ), + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataSharingSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "accounts/sample1/dataSharingSettings"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - # Two responses for two calls - response = response + response + mock_args.update(sample_request) - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListPropertiesResponse.to_json(x) for x in response + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_data_sharing_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=accounts/*/dataSharingSettings}" % client.transport._host, + args[1], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {} - pager = client.list_properties(request=sample_request) +def test_get_data_sharing_settings_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Property) for i in results) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name="name_value", + ) - pages = list(client.list_properties(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + +def test_get_data_sharing_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreatePropertyRequest, + analytics_admin.GetMeasurementProtocolSecretRequest, dict, ], ) -def test_create_property_rest(request_type): +def test_get_measurement_protocol_secret_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} - request_init["property"] = { - "name": "name_value", - "property_type": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "parent": "parent_value", - "display_name": "display_name_value", - "industry_category": 1, - "time_zone": "time_zone_value", - "currency_code": "currency_code_value", - "service_level": 1, - "delete_time": {}, - "expire_time": {}, - "account": "account_value", + request_init = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreatePropertyRequest.meta.fields["property"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["property"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["property"][field])): - del request_init["property"][field][i][subfield] - else: - del request_init["property"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property( + return_value = resources.MeasurementProtocolSecret( name="name_value", - property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, - parent="parent_value", display_name="display_name_value", - industry_category=resources.IndustryCategory.AUTOMOTIVE, - time_zone="time_zone_value", - currency_code="currency_code_value", - service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, - account="account_value", + secret_value="secret_value_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = resources.MeasurementProtocolSecret.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_property(request) + response = client.get_measurement_protocol_secret(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Property) + assert isinstance(response, resources.MeasurementProtocolSecret) assert response.name == "name_value" - assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY - assert response.parent == "parent_value" assert response.display_name == "display_name_value" - assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE - assert response.time_zone == "time_zone_value" - assert response.currency_code == "currency_code_value" - assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD - assert response.account == "account_value" + assert response.secret_value == "secret_value_value" -def test_create_property_rest_use_cached_wrapped_rpc(): +def test_get_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -60002,34 +69986,40 @@ def test_create_property_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_property in client._transport._wrapped_methods + assert ( + client._transport.get_measurement_protocol_secret + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_property] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_measurement_protocol_secret + ] = mock_rpc request = {} - client.create_property(request) + client.get_measurement_protocol_secret(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_property(request) + client.get_measurement_protocol_secret(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_property_rest_required_fields( - request_type=analytics_admin.CreatePropertyRequest, +def test_get_measurement_protocol_secret_rest_required_fields( + request_type=analytics_admin.GetMeasurementProtocolSecretRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -60040,17 +70030,21 @@ def test_create_property_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_property._get_unset_required_fields(jsonified_request) + ).get_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_property._get_unset_required_fields(jsonified_request) + ).get_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -60059,7 +70053,7 @@ def test_create_property_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = resources.MeasurementProtocolSecret() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -60071,40 +70065,41 @@ def test_create_property_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = resources.MeasurementProtocolSecret.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_property(request) + response = client.get_measurement_protocol_secret(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_property_rest_unset_required_fields(): +def test_get_measurement_protocol_secret_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_property._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("property",))) + unset_fields = transport.get_measurement_protocol_secret._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_property_rest_interceptors(null_interceptor): +def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -60117,14 +70112,16 @@ def test_create_property_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_property" + transports.AnalyticsAdminServiceRestInterceptor, + "post_get_measurement_protocol_secret", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_property" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_get_measurement_protocol_secret", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreatePropertyRequest.pb( - analytics_admin.CreatePropertyRequest() + pb_message = analytics_admin.GetMeasurementProtocolSecretRequest.pb( + analytics_admin.GetMeasurementProtocolSecretRequest() ) transcode.return_value = { "method": "post", @@ -60136,17 +70133,19 @@ def test_create_property_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Property.to_json(resources.Property()) + req.return_value._content = resources.MeasurementProtocolSecret.to_json( + resources.MeasurementProtocolSecret() + ) - request = analytics_admin.CreatePropertyRequest() + request = analytics_admin.GetMeasurementProtocolSecretRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Property() + post.return_value = resources.MeasurementProtocolSecret() - client.create_property( + client.get_measurement_protocol_secret( request, metadata=[ ("key", "val"), @@ -60158,8 +70157,9 @@ def test_create_property_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_property_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreatePropertyRequest +def test_get_measurement_protocol_secret_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.GetMeasurementProtocolSecretRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -60167,7 +70167,9 @@ def test_create_property_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -60179,10 +70181,10 @@ def test_create_property_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_property(request) + client.get_measurement_protocol_secret(request) -def test_create_property_rest_flattened(): +def test_get_measurement_protocol_secret_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -60191,14 +70193,16 @@ def test_create_property_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = resources.MeasurementProtocolSecret() # get arguments that satisfy an http rule for this method - sample_request = {} + sample_request = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } # get truthy value for each flattened field mock_args = dict( - property=resources.Property(name="name_value"), + name="name_value", ) mock_args.update(sample_request) @@ -60206,23 +70210,25 @@ def test_create_property_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = resources.MeasurementProtocolSecret.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_property(**mock_args) + client.get_measurement_protocol_secret(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/properties" % client.transport._host, args[1] + "%s/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" + % client.transport._host, + args[1], ) -def test_create_property_rest_flattened_error(transport: str = "rest"): +def test_get_measurement_protocol_secret_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -60231,13 +70237,13 @@ def test_create_property_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_property( - analytics_admin.CreatePropertyRequest(), - property=resources.Property(name="name_value"), + client.get_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name="name_value", ) -def test_create_property_rest_error(): +def test_get_measurement_protocol_secret_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -60246,60 +70252,46 @@ def test_create_property_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeletePropertyRequest, + analytics_admin.ListMeasurementProtocolSecretsRequest, dict, ], ) -def test_delete_property_rest(request_type): +def test_list_measurement_protocol_secrets_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property( - name="name_value", - property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, - parent="parent_value", - display_name="display_name_value", - industry_category=resources.IndustryCategory.AUTOMOTIVE, - time_zone="time_zone_value", - currency_code="currency_code_value", - service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, - account="account_value", + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_property(request) + response = client.list_measurement_protocol_secrets(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Property) - assert response.name == "name_value" - assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY - assert response.parent == "parent_value" - assert response.display_name == "display_name_value" - assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE - assert response.time_zone == "time_zone_value" - assert response.currency_code == "currency_code_value" - assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD - assert response.account == "account_value" + assert isinstance(response, pagers.ListMeasurementProtocolSecretsPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_property_rest_use_cached_wrapped_rpc(): +def test_list_measurement_protocol_secrets_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -60313,35 +70305,40 @@ def test_delete_property_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_property in client._transport._wrapped_methods + assert ( + client._transport.list_measurement_protocol_secrets + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_property] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_measurement_protocol_secrets + ] = mock_rpc request = {} - client.delete_property(request) + client.list_measurement_protocol_secrets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_property(request) + client.list_measurement_protocol_secrets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_property_rest_required_fields( - request_type=analytics_admin.DeletePropertyRequest, +def test_list_measurement_protocol_secrets_rest_required_fields( + request_type=analytics_admin.ListMeasurementProtocolSecretsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -60352,21 +70349,28 @@ def test_delete_property_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_property._get_unset_required_fields(jsonified_request) + ).list_measurement_protocol_secrets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_property._get_unset_required_fields(jsonified_request) + ).list_measurement_protocol_secrets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -60375,7 +70379,7 @@ def test_delete_property_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -60387,7 +70391,7 @@ def test_delete_property_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result @@ -60396,30 +70400,42 @@ def test_delete_property_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_property(request) + response = client.list_measurement_protocol_secrets(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_property_rest_unset_required_fields(): +def test_list_measurement_protocol_secrets_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_property._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = ( + transport.list_measurement_protocol_secrets._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_property_rest_interceptors(null_interceptor): +def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -60432,14 +70448,16 @@ def test_delete_property_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_delete_property" + transports.AnalyticsAdminServiceRestInterceptor, + "post_list_measurement_protocol_secrets", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_property" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_list_measurement_protocol_secrets", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.DeletePropertyRequest.pb( - analytics_admin.DeletePropertyRequest() + pb_message = analytics_admin.ListMeasurementProtocolSecretsRequest.pb( + analytics_admin.ListMeasurementProtocolSecretsRequest() ) transcode.return_value = { "method": "post", @@ -60451,17 +70469,21 @@ def test_delete_property_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Property.to_json(resources.Property()) + req.return_value._content = ( + analytics_admin.ListMeasurementProtocolSecretsResponse.to_json( + analytics_admin.ListMeasurementProtocolSecretsResponse() + ) + ) - request = analytics_admin.DeletePropertyRequest() + request = analytics_admin.ListMeasurementProtocolSecretsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Property() + post.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() - client.delete_property( + client.list_measurement_protocol_secrets( request, metadata=[ ("key", "val"), @@ -60473,8 +70495,9 @@ def test_delete_property_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_property_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeletePropertyRequest +def test_list_measurement_protocol_secrets_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.ListMeasurementProtocolSecretsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -60482,7 +70505,7 @@ def test_delete_property_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -60494,10 +70517,10 @@ def test_delete_property_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_property(request) + client.list_measurement_protocol_secrets(request) -def test_delete_property_rest_flattened(): +def test_list_measurement_protocol_secrets_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -60506,14 +70529,14 @@ def test_delete_property_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1"} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -60521,23 +70544,29 @@ def test_delete_property_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_property(**mock_args) + client.list_measurement_protocol_secrets(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*}" % client.transport._host, args[1] + "%s/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" + % client.transport._host, + args[1], ) -def test_delete_property_rest_flattened_error(transport: str = "rest"): +def test_list_measurement_protocol_secrets_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -60546,54 +70575,106 @@ def test_delete_property_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_property( - analytics_admin.DeletePropertyRequest(), - name="name_value", + client.list_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent="parent_value", ) -def test_delete_property_rest_error(): +def test_list_measurement_protocol_secrets_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token="abc", + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token="def", + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token="ghi", + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListMeasurementProtocolSecretsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} + + pager = client.list_measurement_protocol_secrets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.MeasurementProtocolSecret) for i in results) + + pages = list( + client.list_measurement_protocol_secrets(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdatePropertyRequest, + analytics_admin.CreateMeasurementProtocolSecretRequest, dict, ], ) -def test_update_property_rest(request_type): +def test_create_measurement_protocol_secret_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"property": {"name": "properties/sample1"}} - request_init["property"] = { - "name": "properties/sample1", - "property_type": 1, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "parent": "parent_value", + request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init["measurement_protocol_secret"] = { + "name": "name_value", "display_name": "display_name_value", - "industry_category": 1, - "time_zone": "time_zone_value", - "currency_code": "currency_code_value", - "service_level": 1, - "delete_time": {}, - "expire_time": {}, - "account": "account_value", + "secret_value": "secret_value_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdatePropertyRequest.meta.fields["property"] + test_field = analytics_admin.CreateMeasurementProtocolSecretRequest.meta.fields[ + "measurement_protocol_secret" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -60621,7 +70702,9 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["property"].items(): # pragma: NO COVER + for field, value in request_init[ + "measurement_protocol_secret" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -60651,52 +70734,42 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["property"][field])): - del request_init["property"][field][i][subfield] + for i in range( + 0, len(request_init["measurement_protocol_secret"][field]) + ): + del request_init["measurement_protocol_secret"][field][i][subfield] else: - del request_init["property"][field][subfield] + del request_init["measurement_protocol_secret"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property( + return_value = resources.MeasurementProtocolSecret( name="name_value", - property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, - parent="parent_value", display_name="display_name_value", - industry_category=resources.IndustryCategory.AUTOMOTIVE, - time_zone="time_zone_value", - currency_code="currency_code_value", - service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, - account="account_value", + secret_value="secret_value_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = resources.MeasurementProtocolSecret.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_property(request) + response = client.create_measurement_protocol_secret(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Property) + assert isinstance(response, resources.MeasurementProtocolSecret) assert response.name == "name_value" - assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY - assert response.parent == "parent_value" assert response.display_name == "display_name_value" - assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE - assert response.time_zone == "time_zone_value" - assert response.currency_code == "currency_code_value" - assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD - assert response.account == "account_value" + assert response.secret_value == "secret_value_value" -def test_update_property_rest_use_cached_wrapped_rpc(): +def test_create_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -60710,34 +70783,40 @@ def test_update_property_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_property in client._transport._wrapped_methods + assert ( + client._transport.create_measurement_protocol_secret + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_property] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_measurement_protocol_secret + ] = mock_rpc request = {} - client.update_property(request) + client.create_measurement_protocol_secret(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_property(request) + client.create_measurement_protocol_secret(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_property_rest_required_fields( - request_type=analytics_admin.UpdatePropertyRequest, +def test_create_measurement_protocol_secret_rest_required_fields( + request_type=analytics_admin.CreateMeasurementProtocolSecretRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -60748,19 +70827,21 @@ def test_update_property_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_property._get_unset_required_fields(jsonified_request) + ).create_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_property._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).create_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -60769,7 +70850,7 @@ def test_update_property_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = resources.MeasurementProtocolSecret() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -60781,7 +70862,7 @@ def test_update_property_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -60791,38 +70872,40 @@ def test_update_property_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = resources.MeasurementProtocolSecret.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_property(request) + response = client.create_measurement_protocol_secret(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_property_rest_unset_required_fields(): +def test_create_measurement_protocol_secret_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_property._get_unset_required_fields({}) + unset_fields = ( + transport.create_measurement_protocol_secret._get_unset_required_fields({}) + ) assert set(unset_fields) == ( - set(("updateMask",)) + set(()) & set( ( - "property", - "updateMask", + "parent", + "measurementProtocolSecret", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_property_rest_interceptors(null_interceptor): +def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -60835,14 +70918,16 @@ def test_update_property_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_property" + transports.AnalyticsAdminServiceRestInterceptor, + "post_create_measurement_protocol_secret", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_property" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_create_measurement_protocol_secret", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdatePropertyRequest.pb( - analytics_admin.UpdatePropertyRequest() + pb_message = analytics_admin.CreateMeasurementProtocolSecretRequest.pb( + analytics_admin.CreateMeasurementProtocolSecretRequest() ) transcode.return_value = { "method": "post", @@ -60854,17 +70939,19 @@ def test_update_property_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Property.to_json(resources.Property()) + req.return_value._content = resources.MeasurementProtocolSecret.to_json( + resources.MeasurementProtocolSecret() + ) - request = analytics_admin.UpdatePropertyRequest() + request = analytics_admin.CreateMeasurementProtocolSecretRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Property() + post.return_value = resources.MeasurementProtocolSecret() - client.update_property( + client.create_measurement_protocol_secret( request, metadata=[ ("key", "val"), @@ -60876,8 +70963,9 @@ def test_update_property_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_property_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdatePropertyRequest +def test_create_measurement_protocol_secret_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.CreateMeasurementProtocolSecretRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -60885,7 +70973,7 @@ def test_update_property_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"property": {"name": "properties/sample1"}} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -60897,10 +70985,10 @@ def test_update_property_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_property(request) + client.create_measurement_protocol_secret(request) -def test_update_property_rest_flattened(): +def test_create_measurement_protocol_secret_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -60909,15 +70997,17 @@ def test_update_property_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Property() + return_value = resources.MeasurementProtocolSecret() # get arguments that satisfy an http rule for this method - sample_request = {"property": {"name": "properties/sample1"}} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( - property=resources.Property(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + measurement_protocol_secret=resources.MeasurementProtocolSecret( + name="name_value" + ), ) mock_args.update(sample_request) @@ -60925,23 +71015,27 @@ def test_update_property_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.Property.pb(return_value) + return_value = resources.MeasurementProtocolSecret.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_property(**mock_args) + client.create_measurement_protocol_secret(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{property.name=properties/*}" % client.transport._host, args[1] + "%s/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" + % client.transport._host, + args[1], ) -def test_update_property_rest_flattened_error(transport: str = "rest"): +def test_create_measurement_protocol_secret_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -60950,14 +71044,16 @@ def test_update_property_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_property( - analytics_admin.UpdatePropertyRequest(), - property=resources.Property(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent="parent_value", + measurement_protocol_secret=resources.MeasurementProtocolSecret( + name="name_value" + ), ) -def test_update_property_rest_error(): +def test_create_measurement_protocol_secret_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -60966,118 +71062,41 @@ def test_update_property_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateFirebaseLinkRequest, + analytics_admin.DeleteMeasurementProtocolSecretRequest, dict, ], ) -def test_create_firebase_link_rest(request_type): +def test_delete_measurement_protocol_secret_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["firebase_link"] = { - "name": "name_value", - "project": "project_value", - "create_time": {"seconds": 751, "nanos": 543}, + request_init = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateFirebaseLinkRequest.meta.fields["firebase_link"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["firebase_link"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["firebase_link"][field])): - del request_init["firebase_link"][field][i][subfield] - else: - del request_init["firebase_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.FirebaseLink( - name="name_value", - project="project_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.FirebaseLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_firebase_link(request) + response = client.delete_measurement_protocol_secret(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.FirebaseLink) - assert response.name == "name_value" - assert response.project == "project_value" + assert response is None -def test_create_firebase_link_rest_use_cached_wrapped_rpc(): +def test_delete_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -61092,7 +71111,8 @@ def test_create_firebase_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_firebase_link in client._transport._wrapped_methods + client._transport.delete_measurement_protocol_secret + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -61101,29 +71121,29 @@ def test_create_firebase_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_firebase_link + client._transport.delete_measurement_protocol_secret ] = mock_rpc request = {} - client.create_firebase_link(request) + client.delete_measurement_protocol_secret(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_firebase_link(request) + client.delete_measurement_protocol_secret(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_firebase_link_rest_required_fields( - request_type=analytics_admin.CreateFirebaseLinkRequest, +def test_delete_measurement_protocol_secret_rest_required_fields( + request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -61134,21 +71154,21 @@ def test_create_firebase_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_firebase_link._get_unset_required_fields(jsonified_request) + ).delete_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_firebase_link._get_unset_required_fields(jsonified_request) + ).delete_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -61157,7 +71177,7 @@ def test_create_firebase_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.FirebaseLink() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -61169,48 +71189,38 @@ def test_create_firebase_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.FirebaseLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_firebase_link(request) + response = client.delete_measurement_protocol_secret(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_firebase_link_rest_unset_required_fields(): +def test_delete_measurement_protocol_secret_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_firebase_link._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "firebaseLink", - ) - ) + unset_fields = ( + transport.delete_measurement_protocol_secret._get_unset_required_fields({}) ) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_firebase_link_rest_interceptors(null_interceptor): +def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -61223,14 +71233,12 @@ def test_create_firebase_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_firebase_link" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_firebase_link" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_delete_measurement_protocol_secret", ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.CreateFirebaseLinkRequest.pb( - analytics_admin.CreateFirebaseLinkRequest() + pb_message = analytics_admin.DeleteMeasurementProtocolSecretRequest.pb( + analytics_admin.DeleteMeasurementProtocolSecretRequest() ) transcode.return_value = { "method": "post", @@ -61242,19 +71250,15 @@ def test_create_firebase_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.FirebaseLink.to_json( - resources.FirebaseLink() - ) - request = analytics_admin.CreateFirebaseLinkRequest() + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.FirebaseLink() - client.create_firebase_link( + client.delete_measurement_protocol_secret( request, metadata=[ ("key", "val"), @@ -61263,11 +71267,11 @@ def test_create_firebase_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_create_firebase_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateFirebaseLinkRequest +def test_delete_measurement_protocol_secret_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -61275,7 +71279,9 @@ def test_create_firebase_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -61287,10 +71293,10 @@ def test_create_firebase_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_firebase_link(request) + client.delete_measurement_protocol_secret(request) -def test_create_firebase_link_rest_flattened(): +def test_delete_measurement_protocol_secret_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -61299,40 +71305,42 @@ def test_create_firebase_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.FirebaseLink() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - firebase_link=resources.FirebaseLink(name="name_value"), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.FirebaseLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_firebase_link(**mock_args) + client.delete_measurement_protocol_secret(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/firebaseLinks" % client.transport._host, + "%s/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" + % client.transport._host, args[1], ) -def test_create_firebase_link_rest_flattened_error(transport: str = "rest"): +def test_delete_measurement_protocol_secret_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -61341,14 +71349,13 @@ def test_create_firebase_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_firebase_link( - analytics_admin.CreateFirebaseLinkRequest(), - parent="parent_value", - firebase_link=resources.FirebaseLink(name="name_value"), + client.delete_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name="name_value", ) -def test_create_firebase_link_rest_error(): +def test_delete_measurement_protocol_secret_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -61357,39 +71364,130 @@ def test_create_firebase_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteFirebaseLinkRequest, + analytics_admin.UpdateMeasurementProtocolSecretRequest, dict, ], ) -def test_delete_firebase_link_rest(request_type): +def test_update_measurement_protocol_secret_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/firebaseLinks/sample2"} + request_init = { + "measurement_protocol_secret": { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } + } + request_init["measurement_protocol_secret"] = { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3", + "display_name": "display_name_value", + "secret_value": "secret_value_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateMeasurementProtocolSecretRequest.meta.fields[ + "measurement_protocol_secret" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "measurement_protocol_secret" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["measurement_protocol_secret"][field]) + ): + del request_init["measurement_protocol_secret"][field][i][subfield] + else: + del request_init["measurement_protocol_secret"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.MeasurementProtocolSecret( + name="name_value", + display_name="display_name_value", + secret_value="secret_value_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.MeasurementProtocolSecret.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_firebase_link(request) + response = client.update_measurement_protocol_secret(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.secret_value == "secret_value_value" -def test_delete_firebase_link_rest_use_cached_wrapped_rpc(): +def test_update_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -61404,7 +71502,8 @@ def test_delete_firebase_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_firebase_link in client._transport._wrapped_methods + client._transport.update_measurement_protocol_secret + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -61413,29 +71512,28 @@ def test_delete_firebase_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_firebase_link + client._transport.update_measurement_protocol_secret ] = mock_rpc request = {} - client.delete_firebase_link(request) + client.update_measurement_protocol_secret(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_firebase_link(request) + client.update_measurement_protocol_secret(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_firebase_link_rest_required_fields( - request_type=analytics_admin.DeleteFirebaseLinkRequest, +def test_update_measurement_protocol_secret_rest_required_fields( + request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -61446,21 +71544,19 @@ def test_delete_firebase_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_firebase_link._get_unset_required_fields(jsonified_request) + ).update_measurement_protocol_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_firebase_link._get_unset_required_fields(jsonified_request) + ).update_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -61469,7 +71565,7 @@ def test_delete_firebase_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.MeasurementProtocolSecret() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -61481,36 +71577,50 @@ def test_delete_firebase_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.MeasurementProtocolSecret.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_firebase_link(request) + response = client.update_measurement_protocol_secret(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_firebase_link_rest_unset_required_fields(): +def test_update_measurement_protocol_secret_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_firebase_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = ( + transport.update_measurement_protocol_secret._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "measurementProtocolSecret", + "updateMask", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_firebase_link_rest_interceptors(null_interceptor): +def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -61523,11 +71633,16 @@ def test_delete_firebase_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_firebase_link" + transports.AnalyticsAdminServiceRestInterceptor, + "post_update_measurement_protocol_secret", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_update_measurement_protocol_secret", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteFirebaseLinkRequest.pb( - analytics_admin.DeleteFirebaseLinkRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateMeasurementProtocolSecretRequest.pb( + analytics_admin.UpdateMeasurementProtocolSecretRequest() ) transcode.return_value = { "method": "post", @@ -61539,15 +71654,19 @@ def test_delete_firebase_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.MeasurementProtocolSecret.to_json( + resources.MeasurementProtocolSecret() + ) - request = analytics_admin.DeleteFirebaseLinkRequest() + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() - client.delete_firebase_link( + client.update_measurement_protocol_secret( request, metadata=[ ("key", "val"), @@ -61556,10 +71675,12 @@ def test_delete_firebase_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_firebase_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteFirebaseLinkRequest +def test_update_measurement_protocol_secret_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -61567,7 +71688,11 @@ def test_delete_firebase_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/firebaseLinks/sample2"} + request_init = { + "measurement_protocol_secret": { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -61579,10 +71704,10 @@ def test_delete_firebase_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_firebase_link(request) + client.update_measurement_protocol_secret(request) -def test_delete_firebase_link_rest_flattened(): +def test_update_measurement_protocol_secret_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -61591,37 +71716,49 @@ def test_delete_firebase_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.MeasurementProtocolSecret() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/firebaseLinks/sample2"} + sample_request = { + "measurement_protocol_secret": { + "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + measurement_protocol_secret=resources.MeasurementProtocolSecret( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.MeasurementProtocolSecret.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_firebase_link(**mock_args) + client.update_measurement_protocol_secret(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/firebaseLinks/*}" % client.transport._host, + "%s/v1alpha/{measurement_protocol_secret.name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" + % client.transport._host, args[1], ) -def test_delete_firebase_link_rest_flattened_error(transport: str = "rest"): +def test_update_measurement_protocol_secret_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -61630,13 +71767,16 @@ def test_delete_firebase_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_firebase_link( - analytics_admin.DeleteFirebaseLinkRequest(), - name="name_value", + client.update_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_firebase_link_rest_error(): +def test_update_measurement_protocol_secret_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -61645,44 +71785,43 @@ def test_delete_firebase_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListFirebaseLinksRequest, + analytics_admin.AcknowledgeUserDataCollectionRequest, dict, ], ) -def test_list_firebase_links_rest(request_type): +def test_acknowledge_user_data_collection_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"property": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListFirebaseLinksResponse( - next_page_token="next_page_token_value", - ) + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_firebase_links(request) + response = client.acknowledge_user_data_collection(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFirebaseLinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) -def test_list_firebase_links_rest_use_cached_wrapped_rpc(): +def test_acknowledge_user_data_collection_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -61697,7 +71836,8 @@ def test_list_firebase_links_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_firebase_links in client._transport._wrapped_methods + client._transport.acknowledge_user_data_collection + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -61706,29 +71846,30 @@ def test_list_firebase_links_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_firebase_links + client._transport.acknowledge_user_data_collection ] = mock_rpc request = {} - client.list_firebase_links(request) + client.acknowledge_user_data_collection(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_firebase_links(request) + client.acknowledge_user_data_collection(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_firebase_links_rest_required_fields( - request_type=analytics_admin.ListFirebaseLinksRequest, +def test_acknowledge_user_data_collection_rest_required_fields( + request_type=analytics_admin.AcknowledgeUserDataCollectionRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["property"] = "" + request_init["acknowledgement"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -61739,28 +71880,24 @@ def test_list_firebase_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_firebase_links._get_unset_required_fields(jsonified_request) + ).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["property"] = "property_value" + jsonified_request["acknowledgement"] = "acknowledgement_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_firebase_links._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "property" in jsonified_request + assert jsonified_request["property"] == "property_value" + assert "acknowledgement" in jsonified_request + assert jsonified_request["acknowledgement"] == "acknowledgement_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -61769,7 +71906,7 @@ def test_list_firebase_links_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListFirebaseLinksResponse() + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -61781,47 +71918,52 @@ def test_list_firebase_links_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_firebase_links(request) + response = client.acknowledge_user_data_collection(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_firebase_links_rest_unset_required_fields(): +def test_acknowledge_user_data_collection_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_firebase_links._get_unset_required_fields({}) + unset_fields = ( + transport.acknowledge_user_data_collection._get_unset_required_fields({}) + ) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "property", + "acknowledgement", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_firebase_links_rest_interceptors(null_interceptor): +def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -61834,14 +71976,16 @@ def test_list_firebase_links_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_firebase_links" + transports.AnalyticsAdminServiceRestInterceptor, + "post_acknowledge_user_data_collection", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_firebase_links" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_acknowledge_user_data_collection", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListFirebaseLinksRequest.pb( - analytics_admin.ListFirebaseLinksRequest() + pb_message = analytics_admin.AcknowledgeUserDataCollectionRequest.pb( + analytics_admin.AcknowledgeUserDataCollectionRequest() ) transcode.return_value = { "method": "post", @@ -61853,19 +71997,21 @@ def test_list_firebase_links_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListFirebaseLinksResponse.to_json( - analytics_admin.ListFirebaseLinksResponse() + req.return_value._content = ( + analytics_admin.AcknowledgeUserDataCollectionResponse.to_json( + analytics_admin.AcknowledgeUserDataCollectionResponse() + ) ) - request = analytics_admin.ListFirebaseLinksRequest() + request = analytics_admin.AcknowledgeUserDataCollectionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListFirebaseLinksResponse() + post.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() - client.list_firebase_links( + client.acknowledge_user_data_collection( request, metadata=[ ("key", "val"), @@ -61877,8 +72023,9 @@ def test_list_firebase_links_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_firebase_links_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListFirebaseLinksRequest +def test_acknowledge_user_data_collection_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.AcknowledgeUserDataCollectionRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -61886,7 +72033,7 @@ def test_list_firebase_links_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"property": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -61898,171 +72045,60 @@ def test_list_firebase_links_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_firebase_links(request) - - -def test_list_firebase_links_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListFirebaseLinksResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListFirebaseLinksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.list_firebase_links(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/firebaseLinks" % client.transport._host, - args[1], - ) - - -def test_list_firebase_links_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_firebase_links( - analytics_admin.ListFirebaseLinksRequest(), - parent="parent_value", - ) + client.acknowledge_user_data_collection(request) -def test_list_firebase_links_rest_pager(transport: str = "rest"): +def test_acknowledge_user_data_collection_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListFirebaseLinksResponse( - firebase_links=[ - resources.FirebaseLink(), - resources.FirebaseLink(), - resources.FirebaseLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListFirebaseLinksResponse( - firebase_links=[], - next_page_token="def", - ), - analytics_admin.ListFirebaseLinksResponse( - firebase_links=[ - resources.FirebaseLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListFirebaseLinksResponse( - firebase_links=[ - resources.FirebaseLink(), - resources.FirebaseLink(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListFirebaseLinksResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_firebase_links(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.FirebaseLink) for i in results) - - pages = list(client.list_firebase_links(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetGlobalSiteTagRequest, + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, dict, ], ) -def test_get_global_site_tag_rest(request_type): +def test_get_sk_ad_network_conversion_value_schema_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataStreams/sample2/globalSiteTag"} + request_init = { + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GlobalSiteTag( + return_value = resources.SKAdNetworkConversionValueSchema( name="name_value", - snippet="snippet_value", + apply_conversion_values=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GlobalSiteTag.pb(return_value) + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_global_site_tag(request) + response = client.get_sk_ad_network_conversion_value_schema(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.GlobalSiteTag) + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) assert response.name == "name_value" - assert response.snippet == "snippet_value" + assert response.apply_conversion_values is True -def test_get_global_site_tag_rest_use_cached_wrapped_rpc(): +def test_get_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -62077,7 +72113,8 @@ def test_get_global_site_tag_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_global_site_tag in client._transport._wrapped_methods + client._transport.get_sk_ad_network_conversion_value_schema + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -62086,24 +72123,24 @@ def test_get_global_site_tag_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_global_site_tag + client._transport.get_sk_ad_network_conversion_value_schema ] = mock_rpc request = {} - client.get_global_site_tag(request) + client.get_sk_ad_network_conversion_value_schema(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_global_site_tag(request) + client.get_sk_ad_network_conversion_value_schema(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_global_site_tag_rest_required_fields( - request_type=analytics_admin.GetGlobalSiteTagRequest, +def test_get_sk_ad_network_conversion_value_schema_rest_required_fields( + request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -62119,7 +72156,9 @@ def test_get_global_site_tag_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_global_site_tag._get_unset_required_fields(jsonified_request) + ).get_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -62128,7 +72167,9 @@ def test_get_global_site_tag_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_global_site_tag._get_unset_required_fields(jsonified_request) + ).get_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -62142,7 +72183,7 @@ def test_get_global_site_tag_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.GlobalSiteTag() + return_value = resources.SKAdNetworkConversionValueSchema() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -62163,30 +72204,34 @@ def test_get_global_site_tag_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GlobalSiteTag.pb(return_value) + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_global_site_tag(request) + response = client.get_sk_ad_network_conversion_value_schema(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_global_site_tag_rest_unset_required_fields(): +def test_get_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_global_site_tag._get_unset_required_fields({}) + unset_fields = ( + transport.get_sk_ad_network_conversion_value_schema._get_unset_required_fields( + {} + ) + ) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_global_site_tag_rest_interceptors(null_interceptor): +def test_get_sk_ad_network_conversion_value_schema_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -62199,14 +72244,16 @@ def test_get_global_site_tag_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_global_site_tag" + transports.AnalyticsAdminServiceRestInterceptor, + "post_get_sk_ad_network_conversion_value_schema", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_global_site_tag" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_get_sk_ad_network_conversion_value_schema", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetGlobalSiteTagRequest.pb( - analytics_admin.GetGlobalSiteTagRequest() + pb_message = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest.pb( + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() ) transcode.return_value = { "method": "post", @@ -62218,19 +72265,19 @@ def test_get_global_site_tag_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.GlobalSiteTag.to_json( - resources.GlobalSiteTag() + req.return_value._content = resources.SKAdNetworkConversionValueSchema.to_json( + resources.SKAdNetworkConversionValueSchema() ) - request = analytics_admin.GetGlobalSiteTagRequest() + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.GlobalSiteTag() + post.return_value = resources.SKAdNetworkConversionValueSchema() - client.get_global_site_tag( + client.get_sk_ad_network_conversion_value_schema( request, metadata=[ ("key", "val"), @@ -62242,8 +72289,9 @@ def test_get_global_site_tag_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_global_site_tag_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetGlobalSiteTagRequest +def test_get_sk_ad_network_conversion_value_schema_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -62251,7 +72299,9 @@ def test_get_global_site_tag_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataStreams/sample2/globalSiteTag"} + request_init = { + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -62263,10 +72313,10 @@ def test_get_global_site_tag_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_global_site_tag(request) + client.get_sk_ad_network_conversion_value_schema(request) -def test_get_global_site_tag_rest_flattened(): +def test_get_sk_ad_network_conversion_value_schema_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -62275,11 +72325,11 @@ def test_get_global_site_tag_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GlobalSiteTag() + return_value = resources.SKAdNetworkConversionValueSchema() # get arguments that satisfy an http rule for this method sample_request = { - "name": "properties/sample1/dataStreams/sample2/globalSiteTag" + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" } # get truthy value for each flattened field @@ -62292,25 +72342,27 @@ def test_get_global_site_tag_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GlobalSiteTag.pb(return_value) + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_global_site_tag(**mock_args) + client.get_sk_ad_network_conversion_value_schema(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/globalSiteTag}" + "%s/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" % client.transport._host, args[1], ) -def test_get_global_site_tag_rest_flattened_error(transport: str = "rest"): +def test_get_sk_ad_network_conversion_value_schema_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -62319,13 +72371,13 @@ def test_get_global_site_tag_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_global_site_tag( - analytics_admin.GetGlobalSiteTagRequest(), + client.get_sk_ad_network_conversion_value_schema( + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(), name="name_value", ) -def test_get_global_site_tag_rest_error(): +def test_get_sk_ad_network_conversion_value_schema_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -62334,35 +72386,54 @@ def test_get_global_site_tag_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateGoogleAdsLinkRequest, + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, dict, ], ) -def test_create_google_ads_link_rest(request_type): +def test_create_sk_ad_network_conversion_value_schema_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["google_ads_link"] = { + request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init["skadnetwork_conversion_value_schema"] = { "name": "name_value", - "customer_id": "customer_id_value", - "can_manage_clients": True, - "ads_personalization_enabled": {"value": True}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "creator_email_address": "creator_email_address_value", + "postback_window_one": { + "conversion_values": [ + { + "display_name": "display_name_value", + "fine_value": 1054, + "coarse_value": 1, + "event_mappings": [ + { + "event_name": "event_name_value", + "min_event_count": 1613, + "max_event_count": 1615, + "min_event_value": 0.16010000000000002, + "max_event_value": 0.1603, + } + ], + "lock_enabled": True, + } + ], + "postback_window_settings_enabled": True, + }, + "postback_window_two": {}, + "postback_window_three": {}, + "apply_conversion_values": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateGoogleAdsLinkRequest.meta.fields[ - "google_ads_link" - ] + test_field = ( + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.meta.fields[ + "skadnetwork_conversion_value_schema" + ] + ) def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -62390,7 +72461,9 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["google_ads_link"].items(): # pragma: NO COVER + for field, value in request_init[ + "skadnetwork_conversion_value_schema" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -62420,42 +72493,42 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["google_ads_link"][field])): - del request_init["google_ads_link"][field][i][subfield] + for i in range( + 0, len(request_init["skadnetwork_conversion_value_schema"][field]) + ): + del request_init["skadnetwork_conversion_value_schema"][field][i][ + subfield + ] else: - del request_init["google_ads_link"][field][subfield] + del request_init["skadnetwork_conversion_value_schema"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleAdsLink( + return_value = resources.SKAdNetworkConversionValueSchema( name="name_value", - customer_id="customer_id_value", - can_manage_clients=True, - creator_email_address="creator_email_address_value", + apply_conversion_values=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleAdsLink.pb(return_value) + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_google_ads_link(request) + response = client.create_sk_ad_network_conversion_value_schema(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.GoogleAdsLink) + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) assert response.name == "name_value" - assert response.customer_id == "customer_id_value" - assert response.can_manage_clients is True - assert response.creator_email_address == "creator_email_address_value" + assert response.apply_conversion_values is True -def test_create_google_ads_link_rest_use_cached_wrapped_rpc(): +def test_create_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -62470,7 +72543,7 @@ def test_create_google_ads_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_google_ads_link + client._transport.create_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods ) @@ -62480,24 +72553,24 @@ def test_create_google_ads_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_google_ads_link + client._transport.create_sk_ad_network_conversion_value_schema ] = mock_rpc request = {} - client.create_google_ads_link(request) + client.create_sk_ad_network_conversion_value_schema(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_google_ads_link(request) + client.create_sk_ad_network_conversion_value_schema(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_google_ads_link_rest_required_fields( - request_type=analytics_admin.CreateGoogleAdsLinkRequest, +def test_create_sk_ad_network_conversion_value_schema_rest_required_fields( + request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -62513,7 +72586,9 @@ def test_create_google_ads_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_google_ads_link._get_unset_required_fields(jsonified_request) + ).create_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -62522,7 +72597,9 @@ def test_create_google_ads_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_google_ads_link._get_unset_required_fields(jsonified_request) + ).create_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -62536,7 +72613,7 @@ def test_create_google_ads_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.GoogleAdsLink() + return_value = resources.SKAdNetworkConversionValueSchema() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -62558,38 +72635,42 @@ def test_create_google_ads_link_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleAdsLink.pb(return_value) + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_google_ads_link(request) + response = client.create_sk_ad_network_conversion_value_schema(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_google_ads_link_rest_unset_required_fields(): +def test_create_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_google_ads_link._get_unset_required_fields({}) + unset_fields = transport.create_sk_ad_network_conversion_value_schema._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set(()) & set( ( "parent", - "googleAdsLink", + "skadnetworkConversionValueSchema", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_google_ads_link_rest_interceptors(null_interceptor): +def test_create_sk_ad_network_conversion_value_schema_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -62602,14 +72683,16 @@ def test_create_google_ads_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_google_ads_link" + transports.AnalyticsAdminServiceRestInterceptor, + "post_create_sk_ad_network_conversion_value_schema", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_google_ads_link" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_create_sk_ad_network_conversion_value_schema", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateGoogleAdsLinkRequest.pb( - analytics_admin.CreateGoogleAdsLinkRequest() + pb_message = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.pb( + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() ) transcode.return_value = { "method": "post", @@ -62621,19 +72704,19 @@ def test_create_google_ads_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.GoogleAdsLink.to_json( - resources.GoogleAdsLink() + req.return_value._content = resources.SKAdNetworkConversionValueSchema.to_json( + resources.SKAdNetworkConversionValueSchema() ) - request = analytics_admin.CreateGoogleAdsLinkRequest() + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.GoogleAdsLink() + post.return_value = resources.SKAdNetworkConversionValueSchema() - client.create_google_ads_link( + client.create_sk_ad_network_conversion_value_schema( request, metadata=[ ("key", "val"), @@ -62645,8 +72728,9 @@ def test_create_google_ads_link_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_google_ads_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateGoogleAdsLinkRequest +def test_create_sk_ad_network_conversion_value_schema_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -62654,7 +72738,7 @@ def test_create_google_ads_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -62666,10 +72750,10 @@ def test_create_google_ads_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_google_ads_link(request) + client.create_sk_ad_network_conversion_value_schema(request) -def test_create_google_ads_link_rest_flattened(): +def test_create_sk_ad_network_conversion_value_schema_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -62678,15 +72762,17 @@ def test_create_google_ads_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleAdsLink() + return_value = resources.SKAdNetworkConversionValueSchema() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - google_ads_link=resources.GoogleAdsLink(name="name_value"), + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( + name="name_value" + ), ) mock_args.update(sample_request) @@ -62694,24 +72780,27 @@ def test_create_google_ads_link_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleAdsLink.pb(return_value) + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_google_ads_link(**mock_args) + client.create_sk_ad_network_conversion_value_schema(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/googleAdsLinks" % client.transport._host, + "%s/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema" + % client.transport._host, args[1], ) -def test_create_google_ads_link_rest_flattened_error(transport: str = "rest"): +def test_create_sk_ad_network_conversion_value_schema_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -62720,14 +72809,16 @@ def test_create_google_ads_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_google_ads_link( - analytics_admin.CreateGoogleAdsLinkRequest(), + client.create_sk_ad_network_conversion_value_schema( + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(), parent="parent_value", - google_ads_link=resources.GoogleAdsLink(name="name_value"), + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( + name="name_value" + ), ) -def test_create_google_ads_link_rest_error(): +def test_create_sk_ad_network_conversion_value_schema_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -62736,11 +72827,11 @@ def test_create_google_ads_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateGoogleAdsLinkRequest, + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, dict, ], ) -def test_update_google_ads_link_rest(request_type): +def test_delete_sk_ad_network_conversion_value_schema_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -62748,118 +72839,29 @@ def test_update_google_ads_link_rest(request_type): # send a request that will satisfy transcoding request_init = { - "google_ads_link": {"name": "properties/sample1/googleAdsLinks/sample2"} - } - request_init["google_ads_link"] = { - "name": "properties/sample1/googleAdsLinks/sample2", - "customer_id": "customer_id_value", - "can_manage_clients": True, - "ads_personalization_enabled": {"value": True}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "creator_email_address": "creator_email_address_value", + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateGoogleAdsLinkRequest.meta.fields[ - "google_ads_link" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["google_ads_link"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["google_ads_link"][field])): - del request_init["google_ads_link"][field][i][subfield] - else: - del request_init["google_ads_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleAdsLink( - name="name_value", - customer_id="customer_id_value", - can_manage_clients=True, - creator_email_address="creator_email_address_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.GoogleAdsLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_google_ads_link(request) + response = client.delete_sk_ad_network_conversion_value_schema(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.GoogleAdsLink) - assert response.name == "name_value" - assert response.customer_id == "customer_id_value" - assert response.can_manage_clients is True - assert response.creator_email_address == "creator_email_address_value" + assert response is None -def test_update_google_ads_link_rest_use_cached_wrapped_rpc(): +def test_delete_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -62874,7 +72876,7 @@ def test_update_google_ads_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_google_ads_link + client._transport.delete_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods ) @@ -62884,28 +72886,29 @@ def test_update_google_ads_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_google_ads_link + client._transport.delete_sk_ad_network_conversion_value_schema ] = mock_rpc request = {} - client.update_google_ads_link(request) + client.delete_sk_ad_network_conversion_value_schema(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_google_ads_link(request) + client.delete_sk_ad_network_conversion_value_schema(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_google_ads_link_rest_required_fields( - request_type=analytics_admin.UpdateGoogleAdsLinkRequest, +def test_delete_sk_ad_network_conversion_value_schema_rest_required_fields( + request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -62916,19 +72919,25 @@ def test_update_google_ads_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_google_ads_link._get_unset_required_fields(jsonified_request) + ).delete_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_google_ads_link._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).delete_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -62937,7 +72946,7 @@ def test_update_google_ads_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.GoogleAdsLink() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -62949,40 +72958,40 @@ def test_update_google_ads_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.GoogleAdsLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_google_ads_link(request) + response = client.delete_sk_ad_network_conversion_value_schema(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_google_ads_link_rest_unset_required_fields(): +def test_delete_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_google_ads_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + unset_fields = transport.delete_sk_ad_network_conversion_value_schema._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_google_ads_link_rest_interceptors(null_interceptor): +def test_delete_sk_ad_network_conversion_value_schema_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -62995,14 +73004,12 @@ def test_update_google_ads_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_google_ads_link" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_google_ads_link" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_delete_sk_ad_network_conversion_value_schema", ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateGoogleAdsLinkRequest.pb( - analytics_admin.UpdateGoogleAdsLinkRequest() + pb_message = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest.pb( + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() ) transcode.return_value = { "method": "post", @@ -63014,19 +73021,15 @@ def test_update_google_ads_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.GoogleAdsLink.to_json( - resources.GoogleAdsLink() - ) - request = analytics_admin.UpdateGoogleAdsLinkRequest() + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.GoogleAdsLink() - client.update_google_ads_link( + client.delete_sk_ad_network_conversion_value_schema( request, metadata=[ ("key", "val"), @@ -63035,11 +73038,11 @@ def test_update_google_ads_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_google_ads_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateGoogleAdsLinkRequest +def test_delete_sk_ad_network_conversion_value_schema_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -63048,7 +73051,7 @@ def test_update_google_ads_link_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "google_ads_link": {"name": "properties/sample1/googleAdsLinks/sample2"} + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" } request = request_type(**request_init) @@ -63061,10 +73064,10 @@ def test_update_google_ads_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_google_ads_link(request) + client.delete_sk_ad_network_conversion_value_schema(request) -def test_update_google_ads_link_rest_flattened(): +def test_delete_sk_ad_network_conversion_value_schema_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -63073,43 +73076,42 @@ def test_update_google_ads_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleAdsLink() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "google_ads_link": {"name": "properties/sample1/googleAdsLinks/sample2"} + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" } # get truthy value for each flattened field mock_args = dict( - google_ads_link=resources.GoogleAdsLink(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.GoogleAdsLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_google_ads_link(**mock_args) + client.delete_sk_ad_network_conversion_value_schema(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{google_ads_link.name=properties/*/googleAdsLinks/*}" + "%s/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" % client.transport._host, args[1], ) -def test_update_google_ads_link_rest_flattened_error(transport: str = "rest"): +def test_delete_sk_ad_network_conversion_value_schema_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -63118,14 +73120,13 @@ def test_update_google_ads_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_google_ads_link( - analytics_admin.UpdateGoogleAdsLinkRequest(), - google_ads_link=resources.GoogleAdsLink(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_sk_ad_network_conversion_value_schema( + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(), + name="name_value", ) -def test_update_google_ads_link_rest_error(): +def test_delete_sk_ad_network_conversion_value_schema_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -63134,39 +73135,153 @@ def test_update_google_ads_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteGoogleAdsLinkRequest, + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, dict, ], ) -def test_delete_google_ads_link_rest(request_type): +def test_update_sk_ad_network_conversion_value_schema_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/googleAdsLinks/sample2"} + request_init = { + "skadnetwork_conversion_value_schema": { + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" + } + } + request_init["skadnetwork_conversion_value_schema"] = { + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3", + "postback_window_one": { + "conversion_values": [ + { + "display_name": "display_name_value", + "fine_value": 1054, + "coarse_value": 1, + "event_mappings": [ + { + "event_name": "event_name_value", + "min_event_count": 1613, + "max_event_count": 1615, + "min_event_value": 0.16010000000000002, + "max_event_value": 0.1603, + } + ], + "lock_enabled": True, + } + ], + "postback_window_settings_enabled": True, + }, + "postback_window_two": {}, + "postback_window_three": {}, + "apply_conversion_values": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.meta.fields[ + "skadnetwork_conversion_value_schema" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "skadnetwork_conversion_value_schema" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["skadnetwork_conversion_value_schema"][field]) + ): + del request_init["skadnetwork_conversion_value_schema"][field][i][ + subfield + ] + else: + del request_init["skadnetwork_conversion_value_schema"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.SKAdNetworkConversionValueSchema( + name="name_value", + apply_conversion_values=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_google_ads_link(request) + response = client.update_sk_ad_network_conversion_value_schema(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == "name_value" + assert response.apply_conversion_values is True -def test_delete_google_ads_link_rest_use_cached_wrapped_rpc(): +def test_update_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -63181,7 +73296,7 @@ def test_delete_google_ads_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_google_ads_link + client._transport.update_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods ) @@ -63191,29 +73306,28 @@ def test_delete_google_ads_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_google_ads_link + client._transport.update_sk_ad_network_conversion_value_schema ] = mock_rpc request = {} - client.delete_google_ads_link(request) + client.update_sk_ad_network_conversion_value_schema(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_google_ads_link(request) + client.update_sk_ad_network_conversion_value_schema(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_google_ads_link_rest_required_fields( - request_type=analytics_admin.DeleteGoogleAdsLinkRequest, +def test_update_sk_ad_network_conversion_value_schema_rest_required_fields( + request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -63224,21 +73338,23 @@ def test_delete_google_ads_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_google_ads_link._get_unset_required_fields(jsonified_request) + ).update_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_google_ads_link._get_unset_required_fields(jsonified_request) + ).update_sk_ad_network_conversion_value_schema._get_unset_required_fields( + jsonified_request + ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -63247,7 +73363,7 @@ def test_delete_google_ads_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.SKAdNetworkConversionValueSchema() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -63259,36 +73375,52 @@ def test_delete_google_ads_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_google_ads_link(request) + response = client.update_sk_ad_network_conversion_value_schema(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_google_ads_link_rest_unset_required_fields(): +def test_update_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_google_ads_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_sk_ad_network_conversion_value_schema._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "skadnetworkConversionValueSchema", + "updateMask", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_google_ads_link_rest_interceptors(null_interceptor): +def test_update_sk_ad_network_conversion_value_schema_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -63301,11 +73433,16 @@ def test_delete_google_ads_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_google_ads_link" + transports.AnalyticsAdminServiceRestInterceptor, + "post_update_sk_ad_network_conversion_value_schema", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_update_sk_ad_network_conversion_value_schema", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteGoogleAdsLinkRequest.pb( - analytics_admin.DeleteGoogleAdsLinkRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.pb( + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() ) transcode.return_value = { "method": "post", @@ -63317,15 +73454,19 @@ def test_delete_google_ads_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.SKAdNetworkConversionValueSchema.to_json( + resources.SKAdNetworkConversionValueSchema() + ) - request = analytics_admin.DeleteGoogleAdsLinkRequest() + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.SKAdNetworkConversionValueSchema() - client.delete_google_ads_link( + client.update_sk_ad_network_conversion_value_schema( request, metadata=[ ("key", "val"), @@ -63334,10 +73475,12 @@ def test_delete_google_ads_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_google_ads_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteGoogleAdsLinkRequest +def test_update_sk_ad_network_conversion_value_schema_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -63345,7 +73488,11 @@ def test_delete_google_ads_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/googleAdsLinks/sample2"} + request_init = { + "skadnetwork_conversion_value_schema": { + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -63357,10 +73504,10 @@ def test_delete_google_ads_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_google_ads_link(request) + client.update_sk_ad_network_conversion_value_schema(request) -def test_delete_google_ads_link_rest_flattened(): +def test_update_sk_ad_network_conversion_value_schema_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -63369,37 +73516,49 @@ def test_delete_google_ads_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.SKAdNetworkConversionValueSchema() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/googleAdsLinks/sample2"} + sample_request = { + "skadnetwork_conversion_value_schema": { + "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_google_ads_link(**mock_args) + client.update_sk_ad_network_conversion_value_schema(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/googleAdsLinks/*}" % client.transport._host, + "%s/v1alpha/{skadnetwork_conversion_value_schema.name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" + % client.transport._host, args[1], ) -def test_delete_google_ads_link_rest_flattened_error(transport: str = "rest"): +def test_update_sk_ad_network_conversion_value_schema_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -63408,13 +73567,16 @@ def test_delete_google_ads_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_google_ads_link( - analytics_admin.DeleteGoogleAdsLinkRequest(), - name="name_value", + client.update_sk_ad_network_conversion_value_schema( + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(), + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_google_ads_link_rest_error(): +def test_update_sk_ad_network_conversion_value_schema_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -63423,24 +73585,24 @@ def test_delete_google_ads_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListGoogleAdsLinksRequest, + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, dict, ], ) -def test_list_google_ads_links_rest(request_type): +def test_list_sk_ad_network_conversion_value_schemas_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListGoogleAdsLinksResponse( + return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( next_page_token="next_page_token_value", ) @@ -63448,19 +73610,21 @@ def test_list_google_ads_links_rest(request_type): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_google_ads_links(request) + response = client.list_sk_ad_network_conversion_value_schemas(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGoogleAdsLinksPager) + assert isinstance(response, pagers.ListSKAdNetworkConversionValueSchemasPager) assert response.next_page_token == "next_page_token_value" -def test_list_google_ads_links_rest_use_cached_wrapped_rpc(): +def test_list_sk_ad_network_conversion_value_schemas_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -63475,7 +73639,7 @@ def test_list_google_ads_links_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_google_ads_links + client._transport.list_sk_ad_network_conversion_value_schemas in client._transport._wrapped_methods ) @@ -63485,24 +73649,24 @@ def test_list_google_ads_links_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_google_ads_links + client._transport.list_sk_ad_network_conversion_value_schemas ] = mock_rpc request = {} - client.list_google_ads_links(request) + client.list_sk_ad_network_conversion_value_schemas(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_google_ads_links(request) + client.list_sk_ad_network_conversion_value_schemas(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_google_ads_links_rest_required_fields( - request_type=analytics_admin.ListGoogleAdsLinksRequest, +def test_list_sk_ad_network_conversion_value_schemas_rest_required_fields( + request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -63518,7 +73682,9 @@ def test_list_google_ads_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_google_ads_links._get_unset_required_fields(jsonified_request) + ).list_sk_ad_network_conversion_value_schemas._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -63527,7 +73693,9 @@ def test_list_google_ads_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_google_ads_links._get_unset_required_fields(jsonified_request) + ).list_sk_ad_network_conversion_value_schemas._get_unset_required_fields( + jsonified_request + ) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -63548,7 +73716,7 @@ def test_list_google_ads_links_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListGoogleAdsLinksResponse() + return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -63569,25 +73737,31 @@ def test_list_google_ads_links_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + return_value = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_google_ads_links(request) + response = client.list_sk_ad_network_conversion_value_schemas(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_google_ads_links_rest_unset_required_fields(): +def test_list_sk_ad_network_conversion_value_schemas_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_google_ads_links._get_unset_required_fields({}) + unset_fields = transport.list_sk_ad_network_conversion_value_schemas._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set( ( @@ -63600,7 +73774,9 @@ def test_list_google_ads_links_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_google_ads_links_rest_interceptors(null_interceptor): +def test_list_sk_ad_network_conversion_value_schemas_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -63613,14 +73789,16 @@ def test_list_google_ads_links_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_google_ads_links" + transports.AnalyticsAdminServiceRestInterceptor, + "post_list_sk_ad_network_conversion_value_schemas", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_google_ads_links" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_list_sk_ad_network_conversion_value_schemas", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListGoogleAdsLinksRequest.pb( - analytics_admin.ListGoogleAdsLinksRequest() + pb_message = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest.pb( + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() ) transcode.return_value = { "method": "post", @@ -63632,19 +73810,23 @@ def test_list_google_ads_links_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListGoogleAdsLinksResponse.to_json( - analytics_admin.ListGoogleAdsLinksResponse() + req.return_value._content = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.to_json( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + ) ) - request = analytics_admin.ListGoogleAdsLinksRequest() + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListGoogleAdsLinksResponse() + post.return_value = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + ) - client.list_google_ads_links( + client.list_sk_ad_network_conversion_value_schemas( request, metadata=[ ("key", "val"), @@ -63656,8 +73838,9 @@ def test_list_google_ads_links_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_google_ads_links_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListGoogleAdsLinksRequest +def test_list_sk_ad_network_conversion_value_schemas_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -63665,7 +73848,7 @@ def test_list_google_ads_links_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -63677,10 +73860,10 @@ def test_list_google_ads_links_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_google_ads_links(request) + client.list_sk_ad_network_conversion_value_schemas(request) -def test_list_google_ads_links_rest_flattened(): +def test_list_sk_ad_network_conversion_value_schemas_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -63689,10 +73872,10 @@ def test_list_google_ads_links_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListGoogleAdsLinksResponse() + return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -63704,24 +73887,29 @@ def test_list_google_ads_links_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_google_ads_links(**mock_args) + client.list_sk_ad_network_conversion_value_schemas(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/googleAdsLinks" % client.transport._host, + "%s/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema" + % client.transport._host, args[1], ) -def test_list_google_ads_links_rest_flattened_error(transport: str = "rest"): +def test_list_sk_ad_network_conversion_value_schemas_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -63730,13 +73918,15 @@ def test_list_google_ads_links_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_google_ads_links( - analytics_admin.ListGoogleAdsLinksRequest(), + client.list_sk_ad_network_conversion_value_schemas( + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(), parent="parent_value", ) -def test_list_google_ads_links_rest_pager(transport: str = "rest"): +def test_list_sk_ad_network_conversion_value_schemas_rest_pager( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -63748,28 +73938,28 @@ def test_list_google_ads_links_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - analytics_admin.ListGoogleAdsLinksResponse( - google_ads_links=[ - resources.GoogleAdsLink(), - resources.GoogleAdsLink(), - resources.GoogleAdsLink(), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), ], next_page_token="abc", ), - analytics_admin.ListGoogleAdsLinksResponse( - google_ads_links=[], + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[], next_page_token="def", ), - analytics_admin.ListGoogleAdsLinksResponse( - google_ads_links=[ - resources.GoogleAdsLink(), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), ], next_page_token="ghi", ), - analytics_admin.ListGoogleAdsLinksResponse( - google_ads_links=[ - resources.GoogleAdsLink(), - resources.GoogleAdsLink(), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), ], ), ) @@ -63778,7 +73968,8 @@ def test_list_google_ads_links_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - analytics_admin.ListGoogleAdsLinksResponse.to_json(x) for x in response + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.to_json(x) + for x in response ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): @@ -63786,15 +73977,23 @@ def test_list_google_ads_links_rest_pager(transport: str = "rest"): return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "properties/sample1"} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} - pager = client.list_google_ads_links(request=sample_request) + pager = client.list_sk_ad_network_conversion_value_schemas( + request=sample_request + ) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.GoogleAdsLink) for i in results) + assert all( + isinstance(i, resources.SKAdNetworkConversionValueSchema) for i in results + ) - pages = list(client.list_google_ads_links(request=sample_request).pages) + pages = list( + client.list_sk_ad_network_conversion_value_schemas( + request=sample_request + ).pages + ) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -63802,54 +74001,46 @@ def test_list_google_ads_links_rest_pager(transport: str = "rest"): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDataSharingSettingsRequest, + analytics_admin.SearchChangeHistoryEventsRequest, dict, ], ) -def test_get_data_sharing_settings_rest(request_type): +def test_search_change_history_events_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1/dataSharingSettings"} + request_init = {"account": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataSharingSettings( - name="name_value", - sharing_with_google_support_enabled=True, - sharing_with_google_assigned_sales_enabled=True, - sharing_with_google_any_sales_enabled=True, - sharing_with_google_products_enabled=True, - sharing_with_others_enabled=True, + return_value = analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataSharingSettings.pb(return_value) + return_value = analytics_admin.SearchChangeHistoryEventsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_data_sharing_settings(request) + response = client.search_change_history_events(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataSharingSettings) - assert response.name == "name_value" - assert response.sharing_with_google_support_enabled is True - assert response.sharing_with_google_assigned_sales_enabled is True - assert response.sharing_with_google_any_sales_enabled is True - assert response.sharing_with_google_products_enabled is True - assert response.sharing_with_others_enabled is True + assert isinstance(response, pagers.SearchChangeHistoryEventsPager) + assert response.next_page_token == "next_page_token_value" -def test_get_data_sharing_settings_rest_use_cached_wrapped_rpc(): +def test_search_change_history_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -63864,7 +74055,7 @@ def test_get_data_sharing_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_data_sharing_settings + client._transport.search_change_history_events in client._transport._wrapped_methods ) @@ -63874,29 +74065,29 @@ def test_get_data_sharing_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_data_sharing_settings + client._transport.search_change_history_events ] = mock_rpc request = {} - client.get_data_sharing_settings(request) + client.search_change_history_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_sharing_settings(request) + client.search_change_history_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_data_sharing_settings_rest_required_fields( - request_type=analytics_admin.GetDataSharingSettingsRequest, +def test_search_change_history_events_rest_required_fields( + request_type=analytics_admin.SearchChangeHistoryEventsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["account"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -63907,21 +74098,21 @@ def test_get_data_sharing_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_data_sharing_settings._get_unset_required_fields(jsonified_request) + ).search_change_history_events._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["account"] = "account_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_data_sharing_settings._get_unset_required_fields(jsonified_request) + ).search_change_history_events._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "account" in jsonified_request + assert jsonified_request["account"] == "account_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -63930,7 +74121,7 @@ def test_get_data_sharing_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DataSharingSettings() + return_value = analytics_admin.SearchChangeHistoryEventsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -63942,39 +74133,42 @@ def test_get_data_sharing_settings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataSharingSettings.pb(return_value) + return_value = analytics_admin.SearchChangeHistoryEventsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_data_sharing_settings(request) + response = client.search_change_history_events(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_data_sharing_settings_rest_unset_required_fields(): +def test_search_change_history_events_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_data_sharing_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.search_change_history_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("account",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_sharing_settings_rest_interceptors(null_interceptor): +def test_search_change_history_events_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -63988,14 +74182,15 @@ def test_get_data_sharing_settings_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_get_data_sharing_settings", + "post_search_change_history_events", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_sharing_settings" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_search_change_history_events", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetDataSharingSettingsRequest.pb( - analytics_admin.GetDataSharingSettingsRequest() + pb_message = analytics_admin.SearchChangeHistoryEventsRequest.pb( + analytics_admin.SearchChangeHistoryEventsRequest() ) transcode.return_value = { "method": "post", @@ -64007,19 +74202,21 @@ def test_get_data_sharing_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DataSharingSettings.to_json( - resources.DataSharingSettings() + req.return_value._content = ( + analytics_admin.SearchChangeHistoryEventsResponse.to_json( + analytics_admin.SearchChangeHistoryEventsResponse() + ) ) - request = analytics_admin.GetDataSharingSettingsRequest() + request = analytics_admin.SearchChangeHistoryEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DataSharingSettings() + post.return_value = analytics_admin.SearchChangeHistoryEventsResponse() - client.get_data_sharing_settings( + client.search_change_history_events( request, metadata=[ ("key", "val"), @@ -64031,8 +74228,9 @@ def test_get_data_sharing_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_data_sharing_settings_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetDataSharingSettingsRequest +def test_search_change_history_events_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.SearchChangeHistoryEventsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -64040,7 +74238,7 @@ def test_get_data_sharing_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1/dataSharingSettings"} + request_init = {"account": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -64052,118 +74250,121 @@ def test_get_data_sharing_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_data_sharing_settings(request) + client.search_change_history_events(request) -def test_get_data_sharing_settings_rest_flattened(): +def test_search_change_history_events_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.DataSharingSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "accounts/sample1/dataSharingSettings"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token="abc", + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token="def", + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token="ghi", + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.DataSharingSettings.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_data_sharing_settings(**mock_args) + # Two responses for two calls + response = response + response - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=accounts/*/dataSharingSettings}" % client.transport._host, - args[1], + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.SearchChangeHistoryEventsResponse.to_json(x) + for x in response ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + sample_request = {"account": "accounts/sample1"} -def test_get_data_sharing_settings_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_data_sharing_settings( - analytics_admin.GetDataSharingSettingsRequest(), - name="name_value", - ) + pager = client.search_change_history_events(request=sample_request) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) for i in results) -def test_get_data_sharing_settings_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + pages = list(client.search_change_history_events(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetMeasurementProtocolSecretRequest, + analytics_admin.GetGoogleSignalsSettingsRequest, dict, ], ) -def test_get_measurement_protocol_secret_rest(request_type): +def test_get_google_signals_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } + request_init = {"name": "properties/sample1/googleSignalsSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret( + return_value = resources.GoogleSignalsSettings( name="name_value", - display_name="display_name_value", - secret_value="secret_value_value", + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.GoogleSignalsSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_measurement_protocol_secret(request) + response = client.get_google_signals_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.MeasurementProtocolSecret) + assert isinstance(response, resources.GoogleSignalsSettings) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.secret_value == "secret_value_value" + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert ( + response.consent + == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + ) -def test_get_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): +def test_get_google_signals_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -64178,7 +74379,7 @@ def test_get_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_measurement_protocol_secret + client._transport.get_google_signals_settings in client._transport._wrapped_methods ) @@ -64188,24 +74389,24 @@ def test_get_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_measurement_protocol_secret + client._transport.get_google_signals_settings ] = mock_rpc request = {} - client.get_measurement_protocol_secret(request) + client.get_google_signals_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_measurement_protocol_secret(request) + client.get_google_signals_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_measurement_protocol_secret_rest_required_fields( - request_type=analytics_admin.GetMeasurementProtocolSecretRequest, +def test_get_google_signals_settings_rest_required_fields( + request_type=analytics_admin.GetGoogleSignalsSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -64221,7 +74422,7 @@ def test_get_measurement_protocol_secret_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).get_google_signals_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -64230,7 +74431,7 @@ def test_get_measurement_protocol_secret_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).get_google_signals_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -64244,7 +74445,7 @@ def test_get_measurement_protocol_secret_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret() + return_value = resources.GoogleSignalsSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -64265,32 +74466,30 @@ def test_get_measurement_protocol_secret_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.GoogleSignalsSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_measurement_protocol_secret(request) + response = client.get_google_signals_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_measurement_protocol_secret_rest_unset_required_fields(): +def test_get_google_signals_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_measurement_protocol_secret._get_unset_required_fields( - {} - ) + unset_fields = transport.get_google_signals_settings._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): +def test_get_google_signals_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -64304,15 +74503,15 @@ def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_get_measurement_protocol_secret", + "post_get_google_signals_settings", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_measurement_protocol_secret", + "pre_get_google_signals_settings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetMeasurementProtocolSecretRequest.pb( - analytics_admin.GetMeasurementProtocolSecretRequest() + pb_message = analytics_admin.GetGoogleSignalsSettingsRequest.pb( + analytics_admin.GetGoogleSignalsSettingsRequest() ) transcode.return_value = { "method": "post", @@ -64324,19 +74523,19 @@ def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.MeasurementProtocolSecret.to_json( - resources.MeasurementProtocolSecret() + req.return_value._content = resources.GoogleSignalsSettings.to_json( + resources.GoogleSignalsSettings() ) - request = analytics_admin.GetMeasurementProtocolSecretRequest() + request = analytics_admin.GetGoogleSignalsSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.MeasurementProtocolSecret() + post.return_value = resources.GoogleSignalsSettings() - client.get_measurement_protocol_secret( + client.get_google_signals_settings( request, metadata=[ ("key", "val"), @@ -64348,9 +74547,9 @@ def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_measurement_protocol_secret_rest_bad_request( +def test_get_google_signals_settings_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.GetMeasurementProtocolSecretRequest, + request_type=analytics_admin.GetGoogleSignalsSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -64358,9 +74557,7 @@ def test_get_measurement_protocol_secret_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } + request_init = {"name": "properties/sample1/googleSignalsSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -64372,10 +74569,10 @@ def test_get_measurement_protocol_secret_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_measurement_protocol_secret(request) + client.get_google_signals_settings(request) -def test_get_measurement_protocol_secret_rest_flattened(): +def test_get_google_signals_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -64384,12 +74581,10 @@ def test_get_measurement_protocol_secret_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret() + return_value = resources.GoogleSignalsSettings() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } + sample_request = {"name": "properties/sample1/googleSignalsSettings"} # get truthy value for each flattened field mock_args = dict( @@ -64401,25 +74596,25 @@ def test_get_measurement_protocol_secret_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.GoogleSignalsSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_measurement_protocol_secret(**mock_args) + client.get_google_signals_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" + "%s/v1alpha/{name=properties/*/googleSignalsSettings}" % client.transport._host, args[1], ) -def test_get_measurement_protocol_secret_rest_flattened_error(transport: str = "rest"): +def test_get_google_signals_settings_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -64428,13 +74623,13 @@ def test_get_measurement_protocol_secret_rest_flattened_error(transport: str = " # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_measurement_protocol_secret( - analytics_admin.GetMeasurementProtocolSecretRequest(), + client.get_google_signals_settings( + analytics_admin.GetGoogleSignalsSettingsRequest(), name="name_value", ) -def test_get_measurement_protocol_secret_rest_error(): +def test_get_google_signals_settings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -64443,46 +74638,129 @@ def test_get_measurement_protocol_secret_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListMeasurementProtocolSecretsRequest, + analytics_admin.UpdateGoogleSignalsSettingsRequest, dict, ], ) -def test_list_measurement_protocol_secrets_rest(request_type): +def test_update_google_signals_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init = { + "google_signals_settings": {"name": "properties/sample1/googleSignalsSettings"} + } + request_init["google_signals_settings"] = { + "name": "properties/sample1/googleSignalsSettings", + "state": 1, + "consent": 2, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateGoogleSignalsSettingsRequest.meta.fields[ + "google_signals_settings" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "google_signals_settings" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["google_signals_settings"][field])): + del request_init["google_signals_settings"][field][i][subfield] + else: + del request_init["google_signals_settings"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListMeasurementProtocolSecretsResponse( - next_page_token="next_page_token_value", + return_value = resources.GoogleSignalsSettings( + name="name_value", + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListMeasurementProtocolSecretsResponse.pb( - return_value - ) + return_value = resources.GoogleSignalsSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_measurement_protocol_secrets(request) + response = client.update_google_signals_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMeasurementProtocolSecretsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == "name_value" + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert ( + response.consent + == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + ) -def test_list_measurement_protocol_secrets_rest_use_cached_wrapped_rpc(): +def test_update_google_signals_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -64497,7 +74775,7 @@ def test_list_measurement_protocol_secrets_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_measurement_protocol_secrets + client._transport.update_google_signals_settings in client._transport._wrapped_methods ) @@ -64507,29 +74785,28 @@ def test_list_measurement_protocol_secrets_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_measurement_protocol_secrets + client._transport.update_google_signals_settings ] = mock_rpc request = {} - client.list_measurement_protocol_secrets(request) + client.update_google_signals_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_measurement_protocol_secrets(request) + client.update_google_signals_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_measurement_protocol_secrets_rest_required_fields( - request_type=analytics_admin.ListMeasurementProtocolSecretsRequest, +def test_update_google_signals_settings_rest_required_fields( + request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -64540,28 +74817,19 @@ def test_list_measurement_protocol_secrets_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_measurement_protocol_secrets._get_unset_required_fields(jsonified_request) + ).update_google_signals_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_measurement_protocol_secrets._get_unset_required_fields(jsonified_request) + ).update_google_signals_settings._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -64570,7 +74838,7 @@ def test_list_measurement_protocol_secrets_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + return_value = resources.GoogleSignalsSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -64582,51 +74850,50 @@ def test_list_measurement_protocol_secrets_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListMeasurementProtocolSecretsResponse.pb( - return_value - ) + return_value = resources.GoogleSignalsSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_measurement_protocol_secrets(request) + response = client.update_google_signals_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_measurement_protocol_secrets_rest_unset_required_fields(): +def test_update_google_signals_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.list_measurement_protocol_secrets._get_unset_required_fields({}) + unset_fields = transport.update_google_signals_settings._get_unset_required_fields( + {} ) assert set(unset_fields) == ( - set( + set(("updateMask",)) + & set( ( - "pageSize", - "pageToken", + "googleSignalsSettings", + "updateMask", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): +def test_update_google_signals_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -64640,15 +74907,15 @@ def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_list_measurement_protocol_secrets", + "post_update_google_signals_settings", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_list_measurement_protocol_secrets", + "pre_update_google_signals_settings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListMeasurementProtocolSecretsRequest.pb( - analytics_admin.ListMeasurementProtocolSecretsRequest() + pb_message = analytics_admin.UpdateGoogleSignalsSettingsRequest.pb( + analytics_admin.UpdateGoogleSignalsSettingsRequest() ) transcode.return_value = { "method": "post", @@ -64660,21 +74927,19 @@ def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListMeasurementProtocolSecretsResponse.to_json( - analytics_admin.ListMeasurementProtocolSecretsResponse() - ) + req.return_value._content = resources.GoogleSignalsSettings.to_json( + resources.GoogleSignalsSettings() ) - request = analytics_admin.ListMeasurementProtocolSecretsRequest() + request = analytics_admin.UpdateGoogleSignalsSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + post.return_value = resources.GoogleSignalsSettings() - client.list_measurement_protocol_secrets( + client.update_google_signals_settings( request, metadata=[ ("key", "val"), @@ -64686,9 +74951,9 @@ def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_measurement_protocol_secrets_rest_bad_request( +def test_update_google_signals_settings_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.ListMeasurementProtocolSecretsRequest, + request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -64696,7 +74961,9 @@ def test_list_measurement_protocol_secrets_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init = { + "google_signals_settings": {"name": "properties/sample1/googleSignalsSettings"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -64708,10 +74975,10 @@ def test_list_measurement_protocol_secrets_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_measurement_protocol_secrets(request) + client.update_google_signals_settings(request) -def test_list_measurement_protocol_secrets_rest_flattened(): +def test_update_google_signals_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -64720,14 +74987,19 @@ def test_list_measurement_protocol_secrets_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + return_value = resources.GoogleSignalsSettings() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1/dataStreams/sample2"} + sample_request = { + "google_signals_settings": { + "name": "properties/sample1/googleSignalsSettings" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + google_signals_settings=resources.GoogleSignalsSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -64735,29 +75007,25 @@ def test_list_measurement_protocol_secrets_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListMeasurementProtocolSecretsResponse.pb( - return_value - ) + return_value = resources.GoogleSignalsSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_measurement_protocol_secrets(**mock_args) + client.update_google_signals_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" + "%s/v1alpha/{google_signals_settings.name=properties/*/googleSignalsSettings}" % client.transport._host, args[1], ) -def test_list_measurement_protocol_secrets_rest_flattened_error( - transport: str = "rest", -): +def test_update_google_signals_settings_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -64766,105 +75034,53 @@ def test_list_measurement_protocol_secrets_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_measurement_protocol_secrets( - analytics_admin.ListMeasurementProtocolSecretsRequest(), - parent="parent_value", + client.update_google_signals_settings( + analytics_admin.UpdateGoogleSignalsSettingsRequest(), + google_signals_settings=resources.GoogleSignalsSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_measurement_protocol_secrets_rest_pager(transport: str = "rest"): +def test_update_google_signals_settings_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListMeasurementProtocolSecretsResponse( - measurement_protocol_secrets=[ - resources.MeasurementProtocolSecret(), - resources.MeasurementProtocolSecret(), - resources.MeasurementProtocolSecret(), - ], - next_page_token="abc", - ), - analytics_admin.ListMeasurementProtocolSecretsResponse( - measurement_protocol_secrets=[], - next_page_token="def", - ), - analytics_admin.ListMeasurementProtocolSecretsResponse( - measurement_protocol_secrets=[ - resources.MeasurementProtocolSecret(), - ], - next_page_token="ghi", - ), - analytics_admin.ListMeasurementProtocolSecretsResponse( - measurement_protocol_secrets=[ - resources.MeasurementProtocolSecret(), - resources.MeasurementProtocolSecret(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListMeasurementProtocolSecretsResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1/dataStreams/sample2"} - - pager = client.list_measurement_protocol_secrets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.MeasurementProtocolSecret) for i in results) - - pages = list( - client.list_measurement_protocol_secrets(request=sample_request).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateMeasurementProtocolSecretRequest, + analytics_admin.CreateConversionEventRequest, dict, ], ) -def test_create_measurement_protocol_secret_rest(request_type): +def test_create_conversion_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} - request_init["measurement_protocol_secret"] = { + request_init = {"parent": "properties/sample1"} + request_init["conversion_event"] = { "name": "name_value", - "display_name": "display_name_value", - "secret_value": "secret_value_value", + "event_name": "event_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "deletable": True, + "custom": True, + "counting_method": 1, + "default_conversion_value": { + "value": 0.541, + "currency_code": "currency_code_value", + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateMeasurementProtocolSecretRequest.meta.fields[ - "measurement_protocol_secret" + test_field = analytics_admin.CreateConversionEventRequest.meta.fields[ + "conversion_event" ] def get_message_fields(field): @@ -64893,9 +75109,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "measurement_protocol_secret" - ].items(): # pragma: NO COVER + for field, value in request_init["conversion_event"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -64925,42 +75139,47 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range( - 0, len(request_init["measurement_protocol_secret"][field]) - ): - del request_init["measurement_protocol_secret"][field][i][subfield] + for i in range(0, len(request_init["conversion_event"][field])): + del request_init["conversion_event"][field][i][subfield] else: - del request_init["measurement_protocol_secret"][field][subfield] + del request_init["conversion_event"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret( + return_value = resources.ConversionEvent( name="name_value", - display_name="display_name_value", - secret_value="secret_value_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.ConversionEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_measurement_protocol_secret(request) + response = client.create_conversion_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.MeasurementProtocolSecret) + assert isinstance(response, resources.ConversionEvent) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.secret_value == "secret_value_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert ( + response.counting_method + == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + ) -def test_create_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): +def test_create_conversion_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -64975,7 +75194,7 @@ def test_create_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_measurement_protocol_secret + client._transport.create_conversion_event in client._transport._wrapped_methods ) @@ -64985,24 +75204,24 @@ def test_create_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_measurement_protocol_secret + client._transport.create_conversion_event ] = mock_rpc request = {} - client.create_measurement_protocol_secret(request) + client.create_conversion_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_measurement_protocol_secret(request) + client.create_conversion_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_measurement_protocol_secret_rest_required_fields( - request_type=analytics_admin.CreateMeasurementProtocolSecretRequest, +def test_create_conversion_event_rest_required_fields( + request_type=analytics_admin.CreateConversionEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -65018,7 +75237,7 @@ def test_create_measurement_protocol_secret_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).create_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -65027,7 +75246,7 @@ def test_create_measurement_protocol_secret_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).create_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -65041,7 +75260,7 @@ def test_create_measurement_protocol_secret_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret() + return_value = resources.ConversionEvent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -65063,40 +75282,38 @@ def test_create_measurement_protocol_secret_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.ConversionEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_measurement_protocol_secret(request) + response = client.create_conversion_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_measurement_protocol_secret_rest_unset_required_fields(): +def test_create_conversion_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.create_measurement_protocol_secret._get_unset_required_fields({}) - ) + unset_fields = transport.create_conversion_event._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( + "conversionEvent", "parent", - "measurementProtocolSecret", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): +def test_create_conversion_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -65109,16 +75326,14 @@ def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_create_measurement_protocol_secret", + transports.AnalyticsAdminServiceRestInterceptor, "post_create_conversion_event" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_create_measurement_protocol_secret", + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_conversion_event" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateMeasurementProtocolSecretRequest.pb( - analytics_admin.CreateMeasurementProtocolSecretRequest() + pb_message = analytics_admin.CreateConversionEventRequest.pb( + analytics_admin.CreateConversionEventRequest() ) transcode.return_value = { "method": "post", @@ -65130,19 +75345,19 @@ def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.MeasurementProtocolSecret.to_json( - resources.MeasurementProtocolSecret() + req.return_value._content = resources.ConversionEvent.to_json( + resources.ConversionEvent() ) - request = analytics_admin.CreateMeasurementProtocolSecretRequest() + request = analytics_admin.CreateConversionEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.MeasurementProtocolSecret() + post.return_value = resources.ConversionEvent() - client.create_measurement_protocol_secret( + client.create_conversion_event( request, metadata=[ ("key", "val"), @@ -65154,9 +75369,8 @@ def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_measurement_protocol_secret_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.CreateMeasurementProtocolSecretRequest, +def test_create_conversion_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateConversionEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -65164,7 +75378,7 @@ def test_create_measurement_protocol_secret_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -65176,10 +75390,10 @@ def test_create_measurement_protocol_secret_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_measurement_protocol_secret(request) + client.create_conversion_event(request) -def test_create_measurement_protocol_secret_rest_flattened(): +def test_create_conversion_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -65188,17 +75402,15 @@ def test_create_measurement_protocol_secret_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret() + return_value = resources.ConversionEvent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1/dataStreams/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - measurement_protocol_secret=resources.MeasurementProtocolSecret( - name="name_value" - ), + conversion_event=resources.ConversionEvent(name="name_value"), ) mock_args.update(sample_request) @@ -65206,27 +75418,25 @@ def test_create_measurement_protocol_secret_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.ConversionEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_measurement_protocol_secret(**mock_args) + client.create_conversion_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" + "%s/v1alpha/{parent=properties/*}/conversionEvents" % client.transport._host, args[1], ) -def test_create_measurement_protocol_secret_rest_flattened_error( - transport: str = "rest", -): +def test_create_conversion_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -65235,59 +75445,154 @@ def test_create_measurement_protocol_secret_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_measurement_protocol_secret( - analytics_admin.CreateMeasurementProtocolSecretRequest(), + client.create_conversion_event( + analytics_admin.CreateConversionEventRequest(), parent="parent_value", - measurement_protocol_secret=resources.MeasurementProtocolSecret( - name="name_value" - ), + conversion_event=resources.ConversionEvent(name="name_value"), ) -def test_create_measurement_protocol_secret_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateConversionEventRequest, + dict, + ], +) +def test_update_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "conversion_event": {"name": "properties/sample1/conversionEvents/sample2"} + } + request_init["conversion_event"] = { + "name": "properties/sample1/conversionEvents/sample2", + "event_name": "event_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "deletable": True, + "custom": True, + "counting_method": 1, + "default_conversion_value": { + "value": 0.541, + "currency_code": "currency_code_value", + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateConversionEventRequest.meta.fields[ + "conversion_event" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversion_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.DeleteMeasurementProtocolSecretRequest, - dict, - ], -) -def test_delete_measurement_protocol_secret_rest(request_type): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversion_event"][field])): + del request_init["conversion_event"][field][i][subfield] + else: + del request_init["conversion_event"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.ConversionEvent( + name="name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_measurement_protocol_secret(request) + response = client.update_conversion_event(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.ConversionEvent) + assert response.name == "name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert ( + response.counting_method + == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + ) -def test_delete_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): +def test_update_conversion_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -65302,7 +75607,7 @@ def test_delete_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_measurement_protocol_secret + client._transport.update_conversion_event in client._transport._wrapped_methods ) @@ -65312,29 +75617,28 @@ def test_delete_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_measurement_protocol_secret + client._transport.update_conversion_event ] = mock_rpc request = {} - client.delete_measurement_protocol_secret(request) + client.update_conversion_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_measurement_protocol_secret(request) + client.update_conversion_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_measurement_protocol_secret_rest_required_fields( - request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest, +def test_update_conversion_event_rest_required_fields( + request_type=analytics_admin.UpdateConversionEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -65345,21 +75649,19 @@ def test_delete_measurement_protocol_secret_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).update_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).update_conversion_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -65368,7 +75670,7 @@ def test_delete_measurement_protocol_secret_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.ConversionEvent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -65380,38 +75682,48 @@ def test_delete_measurement_protocol_secret_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_measurement_protocol_secret(request) + response = client.update_conversion_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_measurement_protocol_secret_rest_unset_required_fields(): +def test_update_conversion_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.delete_measurement_protocol_secret._get_unset_required_fields({}) + unset_fields = transport.update_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "conversionEvent", + "updateMask", + ) + ) ) - assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): +def test_update_conversion_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -65424,12 +75736,14 @@ def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_delete_measurement_protocol_secret", + transports.AnalyticsAdminServiceRestInterceptor, "post_update_conversion_event" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_conversion_event" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteMeasurementProtocolSecretRequest.pb( - analytics_admin.DeleteMeasurementProtocolSecretRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateConversionEventRequest.pb( + analytics_admin.UpdateConversionEventRequest() ) transcode.return_value = { "method": "post", @@ -65441,15 +75755,19 @@ def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.ConversionEvent.to_json( + resources.ConversionEvent() + ) - request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + request = analytics_admin.UpdateConversionEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() - client.delete_measurement_protocol_secret( + client.update_conversion_event( request, metadata=[ ("key", "val"), @@ -65458,11 +75776,11 @@ def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_measurement_protocol_secret_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest, +def test_update_conversion_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateConversionEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -65471,7 +75789,7 @@ def test_delete_measurement_protocol_secret_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + "conversion_event": {"name": "properties/sample1/conversionEvents/sample2"} } request = request_type(**request_init) @@ -65484,10 +75802,10 @@ def test_delete_measurement_protocol_secret_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_measurement_protocol_secret(request) + client.update_conversion_event(request) -def test_delete_measurement_protocol_secret_rest_flattened(): +def test_update_conversion_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -65496,42 +75814,43 @@ def test_delete_measurement_protocol_secret_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.ConversionEvent() # get arguments that satisfy an http rule for this method sample_request = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" + "conversion_event": {"name": "properties/sample1/conversionEvents/sample2"} } # get truthy value for each flattened field mock_args = dict( - name="name_value", + conversion_event=resources.ConversionEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_measurement_protocol_secret(**mock_args) + client.update_conversion_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" + "%s/v1alpha/{conversion_event.name=properties/*/conversionEvents/*}" % client.transport._host, args[1], ) -def test_delete_measurement_protocol_secret_rest_flattened_error( - transport: str = "rest", -): +def test_update_conversion_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -65540,13 +75859,14 @@ def test_delete_measurement_protocol_secret_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_measurement_protocol_secret( - analytics_admin.DeleteMeasurementProtocolSecretRequest(), - name="name_value", + client.update_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_measurement_protocol_secret_rest_error(): +def test_update_conversion_event_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -65555,130 +75875,55 @@ def test_delete_measurement_protocol_secret_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateMeasurementProtocolSecretRequest, + analytics_admin.GetConversionEventRequest, dict, ], ) -def test_update_measurement_protocol_secret_rest(request_type): +def test_get_conversion_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "measurement_protocol_secret": { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } - } - request_init["measurement_protocol_secret"] = { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3", - "display_name": "display_name_value", - "secret_value": "secret_value_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateMeasurementProtocolSecretRequest.meta.fields[ - "measurement_protocol_secret" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "measurement_protocol_secret" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["measurement_protocol_secret"][field]) - ): - del request_init["measurement_protocol_secret"][field][i][subfield] - else: - del request_init["measurement_protocol_secret"][field][subfield] + request_init = {"name": "properties/sample1/conversionEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret( + return_value = resources.ConversionEvent( name="name_value", - display_name="display_name_value", - secret_value="secret_value_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.ConversionEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_measurement_protocol_secret(request) + response = client.get_conversion_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.MeasurementProtocolSecret) + assert isinstance(response, resources.ConversionEvent) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.secret_value == "secret_value_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert ( + response.counting_method + == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + ) -def test_update_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): +def test_get_conversion_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -65693,8 +75938,7 @@ def test_update_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_measurement_protocol_secret - in client._transport._wrapped_methods + client._transport.get_conversion_event in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -65703,28 +75947,29 @@ def test_update_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_measurement_protocol_secret + client._transport.get_conversion_event ] = mock_rpc request = {} - client.update_measurement_protocol_secret(request) + client.get_conversion_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_measurement_protocol_secret(request) + client.get_conversion_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_measurement_protocol_secret_rest_required_fields( - request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest, +def test_get_conversion_event_rest_required_fields( + request_type=analytics_admin.GetConversionEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -65735,19 +75980,21 @@ def test_update_measurement_protocol_secret_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_measurement_protocol_secret._get_unset_required_fields(jsonified_request) + ).get_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_measurement_protocol_secret._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).get_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -65756,7 +76003,7 @@ def test_update_measurement_protocol_secret_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret() + return_value = resources.ConversionEvent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -65768,50 +76015,39 @@ def test_update_measurement_protocol_secret_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.ConversionEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_measurement_protocol_secret(request) + response = client.get_conversion_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_measurement_protocol_secret_rest_unset_required_fields(): +def test_get_conversion_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.update_measurement_protocol_secret._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "measurementProtocolSecret", - "updateMask", - ) - ) - ) + unset_fields = transport.get_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): +def test_get_conversion_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -65824,16 +76060,14 @@ def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_update_measurement_protocol_secret", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_conversion_event" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_measurement_protocol_secret", + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_conversion_event" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateMeasurementProtocolSecretRequest.pb( - analytics_admin.UpdateMeasurementProtocolSecretRequest() + pb_message = analytics_admin.GetConversionEventRequest.pb( + analytics_admin.GetConversionEventRequest() ) transcode.return_value = { "method": "post", @@ -65845,19 +76079,19 @@ def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.MeasurementProtocolSecret.to_json( - resources.MeasurementProtocolSecret() + req.return_value._content = resources.ConversionEvent.to_json( + resources.ConversionEvent() ) - request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + request = analytics_admin.GetConversionEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.MeasurementProtocolSecret() + post.return_value = resources.ConversionEvent() - client.update_measurement_protocol_secret( + client.get_conversion_event( request, metadata=[ ("key", "val"), @@ -65869,9 +76103,8 @@ def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_measurement_protocol_secret_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest, +def test_get_conversion_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetConversionEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -65879,11 +76112,7 @@ def test_update_measurement_protocol_secret_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "measurement_protocol_secret": { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } - } + request_init = {"name": "properties/sample1/conversionEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -65895,10 +76124,10 @@ def test_update_measurement_protocol_secret_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_measurement_protocol_secret(request) + client.get_conversion_event(request) -def test_update_measurement_protocol_secret_rest_flattened(): +def test_get_conversion_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -65907,21 +76136,14 @@ def test_update_measurement_protocol_secret_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.MeasurementProtocolSecret() + return_value = resources.ConversionEvent() # get arguments that satisfy an http rule for this method - sample_request = { - "measurement_protocol_secret": { - "name": "properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3" - } - } + sample_request = {"name": "properties/sample1/conversionEvents/sample2"} # get truthy value for each flattened field mock_args = dict( - measurement_protocol_secret=resources.MeasurementProtocolSecret( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -65929,27 +76151,25 @@ def test_update_measurement_protocol_secret_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.MeasurementProtocolSecret.pb(return_value) + return_value = resources.ConversionEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_measurement_protocol_secret(**mock_args) + client.get_conversion_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{measurement_protocol_secret.name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" + "%s/v1alpha/{name=properties/*/conversionEvents/*}" % client.transport._host, args[1], ) -def test_update_measurement_protocol_secret_rest_flattened_error( - transport: str = "rest", -): +def test_get_conversion_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -65958,16 +76178,13 @@ def test_update_measurement_protocol_secret_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_measurement_protocol_secret( - analytics_admin.UpdateMeasurementProtocolSecretRequest(), - measurement_protocol_secret=resources.MeasurementProtocolSecret( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_conversion_event( + analytics_admin.GetConversionEventRequest(), + name="name_value", ) -def test_update_measurement_protocol_secret_rest_error(): +def test_get_conversion_event_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -65976,43 +76193,39 @@ def test_update_measurement_protocol_secret_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.AcknowledgeUserDataCollectionRequest, + analytics_admin.DeleteConversionEventRequest, dict, ], ) -def test_acknowledge_user_data_collection_rest(request_type): +def test_delete_conversion_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"property": "properties/sample1"} + request_init = {"name": "properties/sample1/conversionEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.AcknowledgeUserDataCollectionResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.acknowledge_user_data_collection(request) + response = client.delete_conversion_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + assert response is None -def test_acknowledge_user_data_collection_rest_use_cached_wrapped_rpc(): +def test_delete_conversion_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -66027,7 +76240,7 @@ def test_acknowledge_user_data_collection_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.acknowledge_user_data_collection + client._transport.delete_conversion_event in client._transport._wrapped_methods ) @@ -66037,30 +76250,29 @@ def test_acknowledge_user_data_collection_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.acknowledge_user_data_collection + client._transport.delete_conversion_event ] = mock_rpc request = {} - client.acknowledge_user_data_collection(request) + client.delete_conversion_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.acknowledge_user_data_collection(request) + client.delete_conversion_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_acknowledge_user_data_collection_rest_required_fields( - request_type=analytics_admin.AcknowledgeUserDataCollectionRequest, +def test_delete_conversion_event_rest_required_fields( + request_type=analytics_admin.DeleteConversionEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["property"] = "" - request_init["acknowledgement"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -66071,24 +76283,21 @@ def test_acknowledge_user_data_collection_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) + ).delete_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["property"] = "property_value" - jsonified_request["acknowledgement"] = "acknowledgement_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) + ).delete_conversion_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "property" in jsonified_request - assert jsonified_request["property"] == "property_value" - assert "acknowledgement" in jsonified_request - assert jsonified_request["acknowledgement"] == "acknowledgement_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -66097,7 +76306,7 @@ def test_acknowledge_user_data_collection_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -66109,52 +76318,36 @@ def test_acknowledge_user_data_collection_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = analytics_admin.AcknowledgeUserDataCollectionResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.acknowledge_user_data_collection(request) + response = client.delete_conversion_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_acknowledge_user_data_collection_rest_unset_required_fields(): +def test_delete_conversion_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.acknowledge_user_data_collection._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "property", - "acknowledgement", - ) - ) - ) + unset_fields = transport.delete_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): +def test_delete_conversion_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -66167,16 +76360,11 @@ def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_acknowledge_user_data_collection", - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_acknowledge_user_data_collection", + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_conversion_event" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.AcknowledgeUserDataCollectionRequest.pb( - analytics_admin.AcknowledgeUserDataCollectionRequest() + pb_message = analytics_admin.DeleteConversionEventRequest.pb( + analytics_admin.DeleteConversionEventRequest() ) transcode.return_value = { "method": "post", @@ -66188,21 +76376,15 @@ def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.AcknowledgeUserDataCollectionResponse.to_json( - analytics_admin.AcknowledgeUserDataCollectionResponse() - ) - ) - request = analytics_admin.AcknowledgeUserDataCollectionRequest() + request = analytics_admin.DeleteConversionEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() - client.acknowledge_user_data_collection( + client.delete_conversion_event( request, metadata=[ ("key", "val"), @@ -66211,12 +76393,10 @@ def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_acknowledge_user_data_collection_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.AcknowledgeUserDataCollectionRequest, +def test_delete_conversion_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteConversionEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -66224,7 +76404,7 @@ def test_acknowledge_user_data_collection_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"property": "properties/sample1"} + request_init = {"name": "properties/sample1/conversionEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -66236,10 +76416,65 @@ def test_acknowledge_user_data_collection_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.acknowledge_user_data_collection(request) + client.delete_conversion_event(request) -def test_acknowledge_user_data_collection_rest_error(): +def test_delete_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/conversionEvents/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/conversionEvents/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_conversion_event_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name="name_value", + ) + + +def test_delete_conversion_event_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -66248,48 +76483,44 @@ def test_acknowledge_user_data_collection_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, + analytics_admin.ListConversionEventsRequest, dict, ], ) -def test_get_sk_ad_network_conversion_value_schema_rest(request_type): +def test_list_conversion_events_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema( - name="name_value", - apply_conversion_values=True, + return_value = analytics_admin.ListConversionEventsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = analytics_admin.ListConversionEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_sk_ad_network_conversion_value_schema(request) + response = client.list_conversion_events(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.SKAdNetworkConversionValueSchema) - assert response.name == "name_value" - assert response.apply_conversion_values is True + assert isinstance(response, pagers.ListConversionEventsPager) + assert response.next_page_token == "next_page_token_value" -def test_get_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): +def test_list_conversion_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -66304,7 +76535,7 @@ def test_get_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc() # Ensure method has been cached assert ( - client._transport.get_sk_ad_network_conversion_value_schema + client._transport.list_conversion_events in client._transport._wrapped_methods ) @@ -66314,29 +76545,29 @@ def test_get_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc() "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_sk_ad_network_conversion_value_schema + client._transport.list_conversion_events ] = mock_rpc request = {} - client.get_sk_ad_network_conversion_value_schema(request) + client.list_conversion_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_sk_ad_network_conversion_value_schema(request) + client.list_conversion_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_sk_ad_network_conversion_value_schema_rest_required_fields( - request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, +def test_list_conversion_events_rest_required_fields( + request_type=analytics_admin.ListConversionEventsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -66347,25 +76578,28 @@ def test_get_sk_ad_network_conversion_value_schema_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) + ).list_conversion_events._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request + ).list_conversion_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -66374,7 +76608,7 @@ def test_get_sk_ad_network_conversion_value_schema_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema() + return_value = analytics_admin.ListConversionEventsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -66395,34 +76629,38 @@ def test_get_sk_ad_network_conversion_value_schema_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = analytics_admin.ListConversionEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_sk_ad_network_conversion_value_schema(request) + response = client.list_conversion_events(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): +def test_list_conversion_events_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.get_sk_ad_network_conversion_value_schema._get_unset_required_fields( - {} + unset_fields = transport.list_conversion_events._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) ) + & set(("parent",)) ) - assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_sk_ad_network_conversion_value_schema_rest_interceptors(null_interceptor): +def test_list_conversion_events_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -66435,16 +76673,14 @@ def test_get_sk_ad_network_conversion_value_schema_rest_interceptors(null_interc ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_get_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_conversion_events" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_conversion_events" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest.pb( - analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + pb_message = analytics_admin.ListConversionEventsRequest.pb( + analytics_admin.ListConversionEventsRequest() ) transcode.return_value = { "method": "post", @@ -66456,19 +76692,21 @@ def test_get_sk_ad_network_conversion_value_schema_rest_interceptors(null_interc req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.SKAdNetworkConversionValueSchema.to_json( - resources.SKAdNetworkConversionValueSchema() + req.return_value._content = ( + analytics_admin.ListConversionEventsResponse.to_json( + analytics_admin.ListConversionEventsResponse() + ) ) - request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + request = analytics_admin.ListConversionEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SKAdNetworkConversionValueSchema() + post.return_value = analytics_admin.ListConversionEventsResponse() - client.get_sk_ad_network_conversion_value_schema( + client.list_conversion_events( request, metadata=[ ("key", "val"), @@ -66480,9 +76718,8 @@ def test_get_sk_ad_network_conversion_value_schema_rest_interceptors(null_interc post.assert_called_once() -def test_get_sk_ad_network_conversion_value_schema_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, +def test_list_conversion_events_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListConversionEventsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -66490,9 +76727,7 @@ def test_get_sk_ad_network_conversion_value_schema_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -66504,10 +76739,10 @@ def test_get_sk_ad_network_conversion_value_schema_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_sk_ad_network_conversion_value_schema(request) + client.list_conversion_events(request) -def test_get_sk_ad_network_conversion_value_schema_rest_flattened(): +def test_list_conversion_events_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -66516,16 +76751,14 @@ def test_get_sk_ad_network_conversion_value_schema_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema() + return_value = analytics_admin.ListConversionEventsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -66533,27 +76766,25 @@ def test_get_sk_ad_network_conversion_value_schema_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = analytics_admin.ListConversionEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_sk_ad_network_conversion_value_schema(**mock_args) + client.list_conversion_events(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" + "%s/v1alpha/{parent=properties/*}/conversionEvents" % client.transport._host, args[1], ) -def test_get_sk_ad_network_conversion_value_schema_rest_flattened_error( - transport: str = "rest", -): +def test_list_conversion_events_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -66562,69 +76793,108 @@ def test_get_sk_ad_network_conversion_value_schema_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_sk_ad_network_conversion_value_schema( - analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(), - name="name_value", + client.list_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent="parent_value", ) -def test_get_sk_ad_network_conversion_value_schema_rest_error(): +def test_list_conversion_events_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token="abc", + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token="def", + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token="ghi", + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListConversionEventsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_conversion_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ConversionEvent) for i in results) + + pages = list(client.list_conversion_events(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, + analytics_admin.CreateKeyEventRequest, dict, ], ) -def test_create_sk_ad_network_conversion_value_schema_rest(request_type): +def test_create_key_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} - request_init["skadnetwork_conversion_value_schema"] = { + request_init = {"parent": "properties/sample1"} + request_init["key_event"] = { "name": "name_value", - "postback_window_one": { - "conversion_values": [ - { - "display_name": "display_name_value", - "fine_value": 1054, - "coarse_value": 1, - "event_mappings": [ - { - "event_name": "event_name_value", - "min_event_count": 1613, - "max_event_count": 1615, - "min_event_value": 0.16010000000000002, - "max_event_value": 0.1603, - } - ], - "lock_enabled": True, - } - ], - "postback_window_settings_enabled": True, + "event_name": "event_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "deletable": True, + "custom": True, + "counting_method": 1, + "default_value": { + "numeric_value": 0.1391, + "currency_code": "currency_code_value", }, - "postback_window_two": {}, - "postback_window_three": {}, - "apply_conversion_values": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = ( - analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.meta.fields[ - "skadnetwork_conversion_value_schema" - ] - ) + test_field = analytics_admin.CreateKeyEventRequest.meta.fields["key_event"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -66652,9 +76922,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "skadnetwork_conversion_value_schema" - ].items(): # pragma: NO COVER + for field, value in request_init["key_event"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -66684,42 +76952,44 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range( - 0, len(request_init["skadnetwork_conversion_value_schema"][field]) - ): - del request_init["skadnetwork_conversion_value_schema"][field][i][ - subfield - ] + for i in range(0, len(request_init["key_event"][field])): + del request_init["key_event"][field][i][subfield] else: - del request_init["skadnetwork_conversion_value_schema"][field][subfield] + del request_init["key_event"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema( + return_value = resources.KeyEvent( name="name_value", - apply_conversion_values=True, + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = resources.KeyEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_sk_ad_network_conversion_value_schema(request) + response = client.create_key_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert isinstance(response, resources.KeyEvent) assert response.name == "name_value" - assert response.apply_conversion_values is True + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT -def test_create_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): +def test_create_key_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -66733,10 +77003,7 @@ def test_create_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rp wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_sk_ad_network_conversion_value_schema - in client._transport._wrapped_methods - ) + assert client._transport.create_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -66744,24 +77011,24 @@ def test_create_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rp "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_sk_ad_network_conversion_value_schema + client._transport.create_key_event ] = mock_rpc request = {} - client.create_sk_ad_network_conversion_value_schema(request) + client.create_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_sk_ad_network_conversion_value_schema(request) + client.create_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_sk_ad_network_conversion_value_schema_rest_required_fields( - request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, +def test_create_key_event_rest_required_fields( + request_type=analytics_admin.CreateKeyEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -66777,9 +77044,7 @@ def test_create_sk_ad_network_conversion_value_schema_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) + ).create_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -66788,9 +77053,7 @@ def test_create_sk_ad_network_conversion_value_schema_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) + ).create_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -66804,7 +77067,7 @@ def test_create_sk_ad_network_conversion_value_schema_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema() + return_value = resources.KeyEvent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -66826,42 +77089,38 @@ def test_create_sk_ad_network_conversion_value_schema_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = resources.KeyEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_sk_ad_network_conversion_value_schema(request) + response = client.create_key_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): +def test_create_key_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_sk_ad_network_conversion_value_schema._get_unset_required_fields( - {} - ) + unset_fields = transport.create_key_event._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( + "keyEvent", "parent", - "skadnetworkConversionValueSchema", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_sk_ad_network_conversion_value_schema_rest_interceptors( - null_interceptor, -): +def test_create_key_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -66874,16 +77133,14 @@ def test_create_sk_ad_network_conversion_value_schema_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_create_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "post_create_key_event" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_create_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_key_event" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.pb( - analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + pb_message = analytics_admin.CreateKeyEventRequest.pb( + analytics_admin.CreateKeyEventRequest() ) transcode.return_value = { "method": "post", @@ -66895,19 +77152,17 @@ def test_create_sk_ad_network_conversion_value_schema_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.SKAdNetworkConversionValueSchema.to_json( - resources.SKAdNetworkConversionValueSchema() - ) + req.return_value._content = resources.KeyEvent.to_json(resources.KeyEvent()) - request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + request = analytics_admin.CreateKeyEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SKAdNetworkConversionValueSchema() + post.return_value = resources.KeyEvent() - client.create_sk_ad_network_conversion_value_schema( + client.create_key_event( request, metadata=[ ("key", "val"), @@ -66919,9 +77174,8 @@ def test_create_sk_ad_network_conversion_value_schema_rest_interceptors( post.assert_called_once() -def test_create_sk_ad_network_conversion_value_schema_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, +def test_create_key_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateKeyEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -66929,7 +77183,7 @@ def test_create_sk_ad_network_conversion_value_schema_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -66941,10 +77195,10 @@ def test_create_sk_ad_network_conversion_value_schema_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_sk_ad_network_conversion_value_schema(request) + client.create_key_event(request) -def test_create_sk_ad_network_conversion_value_schema_rest_flattened(): +def test_create_key_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -66953,17 +77207,15 @@ def test_create_sk_ad_network_conversion_value_schema_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema() + return_value = resources.KeyEvent() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1/dataStreams/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( - name="name_value" - ), + key_event=resources.KeyEvent(name="name_value"), ) mock_args.update(sample_request) @@ -66971,27 +77223,24 @@ def test_create_sk_ad_network_conversion_value_schema_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = resources.KeyEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_sk_ad_network_conversion_value_schema(**mock_args) + client.create_key_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema" - % client.transport._host, + "%s/v1alpha/{parent=properties/*}/keyEvents" % client.transport._host, args[1], ) -def test_create_sk_ad_network_conversion_value_schema_rest_flattened_error( - transport: str = "rest", -): +def test_create_key_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -67000,16 +77249,14 @@ def test_create_sk_ad_network_conversion_value_schema_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_sk_ad_network_conversion_value_schema( - analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(), + client.create_key_event( + analytics_admin.CreateKeyEventRequest(), parent="parent_value", - skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( - name="name_value" - ), + key_event=resources.KeyEvent(name="name_value"), ) -def test_create_sk_ad_network_conversion_value_schema_rest_error(): +def test_create_key_event_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -67018,41 +77265,131 @@ def test_create_sk_ad_network_conversion_value_schema_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, + analytics_admin.UpdateKeyEventRequest, dict, ], ) -def test_delete_sk_ad_network_conversion_value_schema_rest(request_type): +def test_update_key_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" + request_init = {"key_event": {"name": "properties/sample1/keyEvents/sample2"}} + request_init["key_event"] = { + "name": "properties/sample1/keyEvents/sample2", + "event_name": "event_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "deletable": True, + "custom": True, + "counting_method": 1, + "default_value": { + "numeric_value": 0.1391, + "currency_code": "currency_code_value", + }, } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateKeyEventRequest.meta.fields["key_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_event"][field])): + del request_init["key_event"][field][i][subfield] + else: + del request_init["key_event"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.KeyEvent( + name="name_value", + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_sk_ad_network_conversion_value_schema(request) + response = client.update_key_event(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.KeyEvent) + assert response.name == "name_value" + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT -def test_delete_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): +def test_update_key_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -67066,10 +77403,7 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rp wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_sk_ad_network_conversion_value_schema - in client._transport._wrapped_methods - ) + assert client._transport.update_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -67077,29 +77411,28 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rp "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_sk_ad_network_conversion_value_schema + client._transport.update_key_event ] = mock_rpc request = {} - client.delete_sk_ad_network_conversion_value_schema(request) + client.update_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_sk_ad_network_conversion_value_schema(request) + client.update_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_sk_ad_network_conversion_value_schema_rest_required_fields( - request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, +def test_update_key_event_rest_required_fields( + request_type=analytics_admin.UpdateKeyEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -67110,25 +77443,19 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) + ).update_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_key_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -67137,7 +77464,7 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.KeyEvent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -67149,40 +77476,48 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_sk_ad_network_conversion_value_schema(request) + response = client.update_key_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): +def test_update_key_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_sk_ad_network_conversion_value_schema._get_unset_required_fields( - {} + unset_fields = transport.update_key_event._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "keyEvent", + "updateMask", + ) + ) ) - assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_sk_ad_network_conversion_value_schema_rest_interceptors( - null_interceptor, -): +def test_update_key_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -67195,12 +77530,14 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_delete_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "post_update_key_event" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_key_event" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest.pb( - analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateKeyEventRequest.pb( + analytics_admin.UpdateKeyEventRequest() ) transcode.return_value = { "method": "post", @@ -67212,15 +77549,17 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.KeyEvent.to_json(resources.KeyEvent()) - request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + request = analytics_admin.UpdateKeyEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.KeyEvent() - client.delete_sk_ad_network_conversion_value_schema( + client.update_key_event( request, metadata=[ ("key", "val"), @@ -67229,11 +77568,11 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_interceptors( ) pre.assert_called_once() + post.assert_called_once() -def test_delete_sk_ad_network_conversion_value_schema_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, +def test_update_key_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateKeyEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -67241,9 +77580,7 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } + request_init = {"key_event": {"name": "properties/sample1/keyEvents/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -67255,10 +77592,10 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_sk_ad_network_conversion_value_schema(request) + client.update_key_event(request) -def test_delete_sk_ad_network_conversion_value_schema_rest_flattened(): +def test_update_key_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -67267,42 +77604,41 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.KeyEvent() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } + sample_request = {"key_event": {"name": "properties/sample1/keyEvents/sample2"}} # get truthy value for each flattened field mock_args = dict( - name="name_value", + key_event=resources.KeyEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_sk_ad_network_conversion_value_schema(**mock_args) + client.update_key_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" + "%s/v1alpha/{key_event.name=properties/*/keyEvents/*}" % client.transport._host, args[1], ) -def test_delete_sk_ad_network_conversion_value_schema_rest_flattened_error( - transport: str = "rest", -): +def test_update_key_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -67311,13 +77647,14 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_sk_ad_network_conversion_value_schema( - analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(), - name="name_value", + client.update_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_sk_ad_network_conversion_value_schema_rest_error(): +def test_update_key_event_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -67326,153 +77663,52 @@ def test_delete_sk_ad_network_conversion_value_schema_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, + analytics_admin.GetKeyEventRequest, dict, ], ) -def test_update_sk_ad_network_conversion_value_schema_rest(request_type): +def test_get_key_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "skadnetwork_conversion_value_schema": { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } - } - request_init["skadnetwork_conversion_value_schema"] = { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3", - "postback_window_one": { - "conversion_values": [ - { - "display_name": "display_name_value", - "fine_value": 1054, - "coarse_value": 1, - "event_mappings": [ - { - "event_name": "event_name_value", - "min_event_count": 1613, - "max_event_count": 1615, - "min_event_value": 0.16010000000000002, - "max_event_value": 0.1603, - } - ], - "lock_enabled": True, - } - ], - "postback_window_settings_enabled": True, - }, - "postback_window_two": {}, - "postback_window_three": {}, - "apply_conversion_values": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ( - analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.meta.fields[ - "skadnetwork_conversion_value_schema" - ] - ) - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "skadnetwork_conversion_value_schema" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["skadnetwork_conversion_value_schema"][field]) - ): - del request_init["skadnetwork_conversion_value_schema"][field][i][ - subfield - ] - else: - del request_init["skadnetwork_conversion_value_schema"][field][subfield] + request_init = {"name": "properties/sample1/keyEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema( + return_value = resources.KeyEvent( name="name_value", - apply_conversion_values=True, + event_name="event_name_value", + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = resources.KeyEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_sk_ad_network_conversion_value_schema(request) + response = client.get_key_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert isinstance(response, resources.KeyEvent) assert response.name == "name_value" - assert response.apply_conversion_values is True + assert response.event_name == "event_name_value" + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT -def test_update_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): +def test_get_key_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -67486,39 +77722,35 @@ def test_update_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rp wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_sk_ad_network_conversion_value_schema - in client._transport._wrapped_methods - ) + assert client._transport.get_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_sk_ad_network_conversion_value_schema - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_key_event] = mock_rpc request = {} - client.update_sk_ad_network_conversion_value_schema(request) + client.get_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_sk_ad_network_conversion_value_schema(request) + client.get_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_sk_ad_network_conversion_value_schema_rest_required_fields( - request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, +def test_get_key_event_rest_required_fields( + request_type=analytics_admin.GetKeyEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -67529,23 +77761,21 @@ def test_update_sk_ad_network_conversion_value_schema_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) + ).get_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_sk_ad_network_conversion_value_schema._get_unset_required_fields( - jsonified_request - ) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).get_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -67554,7 +77784,7 @@ def test_update_sk_ad_network_conversion_value_schema_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema() + return_value = resources.KeyEvent() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -67566,52 +77796,39 @@ def test_update_sk_ad_network_conversion_value_schema_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = resources.KeyEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_sk_ad_network_conversion_value_schema(request) + response = client.get_key_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): +def test_get_key_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_sk_ad_network_conversion_value_schema._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "skadnetworkConversionValueSchema", - "updateMask", - ) - ) - ) + unset_fields = transport.get_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_sk_ad_network_conversion_value_schema_rest_interceptors( - null_interceptor, -): +def test_get_key_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -67624,16 +77841,14 @@ def test_update_sk_ad_network_conversion_value_schema_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_update_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_key_event" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_sk_ad_network_conversion_value_schema", + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_key_event" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.pb( - analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + pb_message = analytics_admin.GetKeyEventRequest.pb( + analytics_admin.GetKeyEventRequest() ) transcode.return_value = { "method": "post", @@ -67645,19 +77860,17 @@ def test_update_sk_ad_network_conversion_value_schema_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.SKAdNetworkConversionValueSchema.to_json( - resources.SKAdNetworkConversionValueSchema() - ) + req.return_value._content = resources.KeyEvent.to_json(resources.KeyEvent()) - request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + request = analytics_admin.GetKeyEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SKAdNetworkConversionValueSchema() + post.return_value = resources.KeyEvent() - client.update_sk_ad_network_conversion_value_schema( + client.get_key_event( request, metadata=[ ("key", "val"), @@ -67669,9 +77882,8 @@ def test_update_sk_ad_network_conversion_value_schema_rest_interceptors( post.assert_called_once() -def test_update_sk_ad_network_conversion_value_schema_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, +def test_get_key_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetKeyEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -67679,11 +77891,7 @@ def test_update_sk_ad_network_conversion_value_schema_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "skadnetwork_conversion_value_schema": { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } - } + request_init = {"name": "properties/sample1/keyEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -67695,10 +77903,10 @@ def test_update_sk_ad_network_conversion_value_schema_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_sk_ad_network_conversion_value_schema(request) + client.get_key_event(request) -def test_update_sk_ad_network_conversion_value_schema_rest_flattened(): +def test_get_key_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -67707,21 +77915,14 @@ def test_update_sk_ad_network_conversion_value_schema_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SKAdNetworkConversionValueSchema() + return_value = resources.KeyEvent() # get arguments that satisfy an http rule for this method - sample_request = { - "skadnetwork_conversion_value_schema": { - "name": "properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3" - } - } + sample_request = {"name": "properties/sample1/keyEvents/sample2"} # get truthy value for each flattened field mock_args = dict( - skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -67729,27 +77930,24 @@ def test_update_sk_ad_network_conversion_value_schema_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SKAdNetworkConversionValueSchema.pb(return_value) + return_value = resources.KeyEvent.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_sk_ad_network_conversion_value_schema(**mock_args) + client.get_key_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{skadnetwork_conversion_value_schema.name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" - % client.transport._host, + "%s/v1alpha/{name=properties/*/keyEvents/*}" % client.transport._host, args[1], ) -def test_update_sk_ad_network_conversion_value_schema_rest_flattened_error( - transport: str = "rest", -): +def test_get_key_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -67758,16 +77956,13 @@ def test_update_sk_ad_network_conversion_value_schema_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_sk_ad_network_conversion_value_schema( - analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(), - skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_key_event( + analytics_admin.GetKeyEventRequest(), + name="name_value", ) -def test_update_sk_ad_network_conversion_value_schema_rest_error(): +def test_get_key_event_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -67776,46 +77971,39 @@ def test_update_sk_ad_network_conversion_value_schema_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, + analytics_admin.DeleteKeyEventRequest, dict, ], ) -def test_list_sk_ad_network_conversion_value_schemas_rest(request_type): +def test_delete_key_event_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init = {"name": "properties/sample1/keyEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_sk_ad_network_conversion_value_schemas(request) + response = client.delete_key_event(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSKAdNetworkConversionValueSchemasPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_sk_ad_network_conversion_value_schemas_rest_use_cached_wrapped_rpc(): +def test_delete_key_event_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -67829,10 +78017,7 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_use_cached_wrapped_rpc wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_sk_ad_network_conversion_value_schemas - in client._transport._wrapped_methods - ) + assert client._transport.delete_key_event in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -67840,29 +78025,29 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_use_cached_wrapped_rpc "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_sk_ad_network_conversion_value_schemas + client._transport.delete_key_event ] = mock_rpc request = {} - client.list_sk_ad_network_conversion_value_schemas(request) + client.delete_key_event(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_sk_ad_network_conversion_value_schemas(request) + client.delete_key_event(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_sk_ad_network_conversion_value_schemas_rest_required_fields( - request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, +def test_delete_key_event_rest_required_fields( + request_type=analytics_admin.DeleteKeyEventRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -67873,32 +78058,21 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_sk_ad_network_conversion_value_schemas._get_unset_required_fields( - jsonified_request - ) + ).delete_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_sk_ad_network_conversion_value_schemas._get_unset_required_fields( - jsonified_request - ) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).delete_key_event._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -67907,7 +78081,7 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -67919,55 +78093,36 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ( - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_sk_ad_network_conversion_value_schemas(request) + response = client.delete_key_event(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_sk_ad_network_conversion_value_schemas_rest_unset_required_fields(): +def test_delete_key_event_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_sk_ad_network_conversion_value_schemas._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.delete_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sk_ad_network_conversion_value_schemas_rest_interceptors( - null_interceptor, -): +def test_delete_key_event_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -67980,16 +78135,11 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_list_sk_ad_network_conversion_value_schemas", - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_list_sk_ad_network_conversion_value_schemas", + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_key_event" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest.pb( - analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + pb_message = analytics_admin.DeleteKeyEventRequest.pb( + analytics_admin.DeleteKeyEventRequest() ) transcode.return_value = { "method": "post", @@ -68001,23 +78151,15 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.to_json( - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() - ) - ) - request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + request = analytics_admin.DeleteKeyEventRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = ( - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() - ) - client.list_sk_ad_network_conversion_value_schemas( + client.delete_key_event( request, metadata=[ ("key", "val"), @@ -68026,12 +78168,10 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_interceptors( ) pre.assert_called_once() - post.assert_called_once() -def test_list_sk_ad_network_conversion_value_schemas_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, +def test_delete_key_event_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteKeyEventRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -68039,7 +78179,7 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init = {"name": "properties/sample1/keyEvents/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -68051,10 +78191,10 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_sk_ad_network_conversion_value_schemas(request) + client.delete_key_event(request) -def test_list_sk_ad_network_conversion_value_schemas_rest_flattened(): +def test_delete_key_event_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -68063,44 +78203,37 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1/dataStreams/sample2"} + sample_request = {"name": "properties/sample1/keyEvents/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_sk_ad_network_conversion_value_schemas(**mock_args) + client.delete_key_event(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema" - % client.transport._host, + "%s/v1alpha/{name=properties/*/keyEvents/*}" % client.transport._host, args[1], ) -def test_list_sk_ad_network_conversion_value_schemas_rest_flattened_error( - transport: str = "rest", -): +def test_delete_key_event_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -68109,107 +78242,39 @@ def test_list_sk_ad_network_conversion_value_schemas_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_sk_ad_network_conversion_value_schemas( - analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(), - parent="parent_value", + client.delete_key_event( + analytics_admin.DeleteKeyEventRequest(), + name="name_value", ) -def test_list_sk_ad_network_conversion_value_schemas_rest_pager( - transport: str = "rest", -): +def test_delete_key_event_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( - skadnetwork_conversion_value_schemas=[ - resources.SKAdNetworkConversionValueSchema(), - resources.SKAdNetworkConversionValueSchema(), - resources.SKAdNetworkConversionValueSchema(), - ], - next_page_token="abc", - ), - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( - skadnetwork_conversion_value_schemas=[], - next_page_token="def", - ), - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( - skadnetwork_conversion_value_schemas=[ - resources.SKAdNetworkConversionValueSchema(), - ], - next_page_token="ghi", - ), - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( - skadnetwork_conversion_value_schemas=[ - resources.SKAdNetworkConversionValueSchema(), - resources.SKAdNetworkConversionValueSchema(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1/dataStreams/sample2"} - - pager = client.list_sk_ad_network_conversion_value_schemas( - request=sample_request - ) - - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, resources.SKAdNetworkConversionValueSchema) for i in results - ) - - pages = list( - client.list_sk_ad_network_conversion_value_schemas( - request=sample_request - ).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.SearchChangeHistoryEventsRequest, + analytics_admin.ListKeyEventsRequest, dict, ], ) -def test_search_change_history_events_rest(request_type): +def test_list_key_events_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"account": "accounts/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.SearchChangeHistoryEventsResponse( + return_value = analytics_admin.ListKeyEventsResponse( next_page_token="next_page_token_value", ) @@ -68217,21 +78282,19 @@ def test_search_change_history_events_rest(request_type): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.SearchChangeHistoryEventsResponse.pb( - return_value - ) + return_value = analytics_admin.ListKeyEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.search_change_history_events(request) + response = client.list_key_events(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchChangeHistoryEventsPager) + assert isinstance(response, pagers.ListKeyEventsPager) assert response.next_page_token == "next_page_token_value" -def test_search_change_history_events_rest_use_cached_wrapped_rpc(): +def test_list_key_events_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -68245,40 +78308,35 @@ def test_search_change_history_events_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.search_change_history_events - in client._transport._wrapped_methods - ) + assert client._transport.list_key_events in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.search_change_history_events - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_key_events] = mock_rpc request = {} - client.search_change_history_events(request) + client.list_key_events(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.search_change_history_events(request) + client.list_key_events(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_search_change_history_events_rest_required_fields( - request_type=analytics_admin.SearchChangeHistoryEventsRequest, +def test_list_key_events_rest_required_fields( + request_type=analytics_admin.ListKeyEventsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["account"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -68289,21 +78347,28 @@ def test_search_change_history_events_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search_change_history_events._get_unset_required_fields(jsonified_request) + ).list_key_events._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["account"] = "account_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search_change_history_events._get_unset_required_fields(jsonified_request) + ).list_key_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "account" in jsonified_request - assert jsonified_request["account"] == "account_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -68312,7 +78377,7 @@ def test_search_change_history_events_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.SearchChangeHistoryEventsResponse() + return_value = analytics_admin.ListKeyEventsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -68324,42 +78389,47 @@ def test_search_change_history_events_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.SearchChangeHistoryEventsResponse.pb( - return_value - ) + return_value = analytics_admin.ListKeyEventsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.search_change_history_events(request) + response = client.list_key_events(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_search_change_history_events_rest_unset_required_fields(): +def test_list_key_events_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.search_change_history_events._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("account",))) + unset_fields = transport.list_key_events._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_change_history_events_rest_interceptors(null_interceptor): +def test_list_key_events_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -68372,16 +78442,14 @@ def test_search_change_history_events_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_search_change_history_events", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_key_events" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_search_change_history_events", + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_key_events" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.SearchChangeHistoryEventsRequest.pb( - analytics_admin.SearchChangeHistoryEventsRequest() + pb_message = analytics_admin.ListKeyEventsRequest.pb( + analytics_admin.ListKeyEventsRequest() ) transcode.return_value = { "method": "post", @@ -68393,21 +78461,19 @@ def test_search_change_history_events_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.SearchChangeHistoryEventsResponse.to_json( - analytics_admin.SearchChangeHistoryEventsResponse() - ) + req.return_value._content = analytics_admin.ListKeyEventsResponse.to_json( + analytics_admin.ListKeyEventsResponse() ) - request = analytics_admin.SearchChangeHistoryEventsRequest() + request = analytics_admin.ListKeyEventsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.SearchChangeHistoryEventsResponse() + post.return_value = analytics_admin.ListKeyEventsResponse() - client.search_change_history_events( + client.list_key_events( request, metadata=[ ("key", "val"), @@ -68419,9 +78485,8 @@ def test_search_change_history_events_rest_interceptors(null_interceptor): post.assert_called_once() -def test_search_change_history_events_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.SearchChangeHistoryEventsRequest, +def test_list_key_events_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListKeyEventsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -68429,7 +78494,7 @@ def test_search_change_history_events_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"account": "accounts/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -68441,10 +78506,66 @@ def test_search_change_history_events_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.search_change_history_events(request) + client.list_key_events(request) -def test_search_change_history_events_rest_pager(transport: str = "rest"): +def test_list_key_events_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListKeyEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListKeyEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_key_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=properties/*}/keyEvents" % client.transport._host, + args[1], + ) + + +def test_list_key_events_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_key_events( + analytics_admin.ListKeyEventsRequest(), + parent="parent_value", + ) + + +def test_list_key_events_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -68456,28 +78577,28 @@ def test_search_change_history_events_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - analytics_admin.SearchChangeHistoryEventsResponse( - change_history_events=[ - resources.ChangeHistoryEvent(), - resources.ChangeHistoryEvent(), - resources.ChangeHistoryEvent(), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), ], next_page_token="abc", ), - analytics_admin.SearchChangeHistoryEventsResponse( - change_history_events=[], + analytics_admin.ListKeyEventsResponse( + key_events=[], next_page_token="def", ), - analytics_admin.SearchChangeHistoryEventsResponse( - change_history_events=[ - resources.ChangeHistoryEvent(), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), ], next_page_token="ghi", ), - analytics_admin.SearchChangeHistoryEventsResponse( - change_history_events=[ - resources.ChangeHistoryEvent(), - resources.ChangeHistoryEvent(), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), ], ), ) @@ -68486,8 +78607,7 @@ def test_search_change_history_events_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - analytics_admin.SearchChangeHistoryEventsResponse.to_json(x) - for x in response + analytics_admin.ListKeyEventsResponse.to_json(x) for x in response ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): @@ -68495,15 +78615,15 @@ def test_search_change_history_events_rest_pager(transport: str = "rest"): return_val.status_code = 200 req.side_effect = return_values - sample_request = {"account": "accounts/sample1"} + sample_request = {"parent": "properties/sample1"} - pager = client.search_change_history_events(request=sample_request) + pager = client.list_key_events(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.ChangeHistoryEvent) for i in results) + assert all(isinstance(i, resources.KeyEvent) for i in results) - pages = list(client.search_change_history_events(request=sample_request).pages) + pages = list(client.list_key_events(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -68511,51 +78631,48 @@ def test_search_change_history_events_rest_pager(transport: str = "rest"): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetGoogleSignalsSettingsRequest, + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_get_google_signals_settings_rest(request_type): +def test_get_display_video360_advertiser_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/googleSignalsSettings"} + request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleSignalsSettings( + return_value = resources.DisplayVideo360AdvertiserLink( name="name_value", - state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, - consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleSignalsSettings.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_google_signals_settings(request) + response = client.get_display_video360_advertiser_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.GoogleSignalsSettings) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) assert response.name == "name_value" - assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED - assert ( - response.consent - == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED - ) + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_get_google_signals_settings_rest_use_cached_wrapped_rpc(): +def test_get_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -68570,7 +78687,7 @@ def test_get_google_signals_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_google_signals_settings + client._transport.get_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -68580,24 +78697,24 @@ def test_get_google_signals_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_google_signals_settings + client._transport.get_display_video360_advertiser_link ] = mock_rpc request = {} - client.get_google_signals_settings(request) + client.get_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_google_signals_settings(request) + client.get_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_google_signals_settings_rest_required_fields( - request_type=analytics_admin.GetGoogleSignalsSettingsRequest, +def test_get_display_video360_advertiser_link_rest_required_fields( + request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -68613,7 +78730,7 @@ def test_get_google_signals_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_google_signals_settings._get_unset_required_fields(jsonified_request) + ).get_display_video360_advertiser_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -68622,7 +78739,7 @@ def test_get_google_signals_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_google_signals_settings._get_unset_required_fields(jsonified_request) + ).get_display_video360_advertiser_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -68636,7 +78753,7 @@ def test_get_google_signals_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.GoogleSignalsSettings() + return_value = resources.DisplayVideo360AdvertiserLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -68657,30 +78774,32 @@ def test_get_google_signals_settings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleSignalsSettings.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_google_signals_settings(request) + response = client.get_display_video360_advertiser_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_google_signals_settings_rest_unset_required_fields(): +def test_get_display_video360_advertiser_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_google_signals_settings._get_unset_required_fields({}) + unset_fields = ( + transport.get_display_video360_advertiser_link._get_unset_required_fields({}) + ) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_google_signals_settings_rest_interceptors(null_interceptor): +def test_get_display_video360_advertiser_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -68694,15 +78813,15 @@ def test_get_google_signals_settings_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_get_google_signals_settings", + "post_get_display_video360_advertiser_link", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_google_signals_settings", + "pre_get_display_video360_advertiser_link", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetGoogleSignalsSettingsRequest.pb( - analytics_admin.GetGoogleSignalsSettingsRequest() + pb_message = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest.pb( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() ) transcode.return_value = { "method": "post", @@ -68714,19 +78833,19 @@ def test_get_google_signals_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.GoogleSignalsSettings.to_json( - resources.GoogleSignalsSettings() + req.return_value._content = resources.DisplayVideo360AdvertiserLink.to_json( + resources.DisplayVideo360AdvertiserLink() ) - request = analytics_admin.GetGoogleSignalsSettingsRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.GoogleSignalsSettings() + post.return_value = resources.DisplayVideo360AdvertiserLink() - client.get_google_signals_settings( + client.get_display_video360_advertiser_link( request, metadata=[ ("key", "val"), @@ -68738,9 +78857,9 @@ def test_get_google_signals_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_google_signals_settings_rest_bad_request( +def test_get_display_video360_advertiser_link_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.GetGoogleSignalsSettingsRequest, + request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -68748,7 +78867,7 @@ def test_get_google_signals_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/googleSignalsSettings"} + request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -68760,10 +78879,10 @@ def test_get_google_signals_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_google_signals_settings(request) + client.get_display_video360_advertiser_link(request) -def test_get_google_signals_settings_rest_flattened(): +def test_get_display_video360_advertiser_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -68772,10 +78891,12 @@ def test_get_google_signals_settings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleSignalsSettings() + return_value = resources.DisplayVideo360AdvertiserLink() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/googleSignalsSettings"} + sample_request = { + "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" + } # get truthy value for each flattened field mock_args = dict( @@ -68787,25 +78908,27 @@ def test_get_google_signals_settings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleSignalsSettings.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_google_signals_settings(**mock_args) + client.get_display_video360_advertiser_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/googleSignalsSettings}" + "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}" % client.transport._host, args[1], ) -def test_get_google_signals_settings_rest_flattened_error(transport: str = "rest"): +def test_get_display_video360_advertiser_link_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -68814,13 +78937,13 @@ def test_get_google_signals_settings_rest_flattened_error(transport: str = "rest # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_google_signals_settings( - analytics_admin.GetGoogleSignalsSettingsRequest(), + client.get_display_video360_advertiser_link( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), name="name_value", ) -def test_get_google_signals_settings_rest_error(): +def test_get_display_video360_advertiser_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -68829,129 +78952,46 @@ def test_get_google_signals_settings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateGoogleSignalsSettingsRequest, + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, dict, ], ) -def test_update_google_signals_settings_rest(request_type): +def test_list_display_video360_advertiser_links_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "google_signals_settings": {"name": "properties/sample1/googleSignalsSettings"} - } - request_init["google_signals_settings"] = { - "name": "properties/sample1/googleSignalsSettings", - "state": 1, - "consent": 2, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateGoogleSignalsSettingsRequest.meta.fields[ - "google_signals_settings" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "google_signals_settings" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["google_signals_settings"][field])): - del request_init["google_signals_settings"][field][i][subfield] - else: - del request_init["google_signals_settings"][field][subfield] + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleSignalsSettings( - name="name_value", - state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, - consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleSignalsSettings.pb(return_value) + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_google_signals_settings(request) + response = client.list_display_video360_advertiser_links(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.GoogleSignalsSettings) - assert response.name == "name_value" - assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED - assert ( - response.consent - == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED - ) + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksPager) + assert response.next_page_token == "next_page_token_value" -def test_update_google_signals_settings_rest_use_cached_wrapped_rpc(): +def test_list_display_video360_advertiser_links_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -68966,7 +79006,7 @@ def test_update_google_signals_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_google_signals_settings + client._transport.list_display_video360_advertiser_links in client._transport._wrapped_methods ) @@ -68976,28 +79016,29 @@ def test_update_google_signals_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_google_signals_settings + client._transport.list_display_video360_advertiser_links ] = mock_rpc request = {} - client.update_google_signals_settings(request) + client.list_display_video360_advertiser_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_google_signals_settings(request) + client.list_display_video360_advertiser_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_google_signals_settings_rest_required_fields( - request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest, +def test_list_display_video360_advertiser_links_rest_required_fields( + request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -69008,19 +79049,32 @@ def test_update_google_signals_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_google_signals_settings._get_unset_required_fields(jsonified_request) + ).list_display_video360_advertiser_links._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_google_signals_settings._get_unset_required_fields(jsonified_request) + ).list_display_video360_advertiser_links._get_unset_required_fields( + jsonified_request + ) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -69029,7 +79083,7 @@ def test_update_google_signals_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.GoogleSignalsSettings() + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -69041,50 +79095,53 @@ def test_update_google_signals_settings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleSignalsSettings.pb(return_value) + return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_google_signals_settings(request) + response = client.list_display_video360_advertiser_links(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_google_signals_settings_rest_unset_required_fields(): +def test_list_display_video360_advertiser_links_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_google_signals_settings._get_unset_required_fields( - {} + unset_fields = ( + transport.list_display_video360_advertiser_links._get_unset_required_fields({}) ) assert set(unset_fields) == ( - set(("updateMask",)) - & set( + set( ( - "googleSignalsSettings", - "updateMask", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_google_signals_settings_rest_interceptors(null_interceptor): +def test_list_display_video360_advertiser_links_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -69098,15 +79155,15 @@ def test_update_google_signals_settings_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_update_google_signals_settings", + "post_list_display_video360_advertiser_links", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_google_signals_settings", + "pre_list_display_video360_advertiser_links", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateGoogleSignalsSettingsRequest.pb( - analytics_admin.UpdateGoogleSignalsSettingsRequest() + pb_message = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest.pb( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() ) transcode.return_value = { "method": "post", @@ -69118,19 +79175,21 @@ def test_update_google_signals_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.GoogleSignalsSettings.to_json( - resources.GoogleSignalsSettings() + req.return_value._content = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.to_json( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + ) ) - request = analytics_admin.UpdateGoogleSignalsSettingsRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.GoogleSignalsSettings() + post.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() - client.update_google_signals_settings( + client.list_display_video360_advertiser_links( request, metadata=[ ("key", "val"), @@ -69142,9 +79201,9 @@ def test_update_google_signals_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_google_signals_settings_rest_bad_request( +def test_list_display_video360_advertiser_links_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest, + request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -69152,9 +79211,7 @@ def test_update_google_signals_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "google_signals_settings": {"name": "properties/sample1/googleSignalsSettings"} - } + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -69166,10 +79223,10 @@ def test_update_google_signals_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_google_signals_settings(request) + client.list_display_video360_advertiser_links(request) -def test_update_google_signals_settings_rest_flattened(): +def test_list_display_video360_advertiser_links_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -69178,19 +79235,14 @@ def test_update_google_signals_settings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.GoogleSignalsSettings() + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "google_signals_settings": { - "name": "properties/sample1/googleSignalsSettings" - } - } + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - google_signals_settings=resources.GoogleSignalsSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) @@ -69198,25 +79250,29 @@ def test_update_google_signals_settings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.GoogleSignalsSettings.pb(return_value) + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_google_signals_settings(**mock_args) + client.list_display_video360_advertiser_links(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{google_signals_settings.name=properties/*/googleSignalsSettings}" + "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks" % client.transport._host, args[1], ) -def test_update_google_signals_settings_rest_flattened_error(transport: str = "rest"): +def test_list_display_video360_advertiser_links_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -69225,27 +79281,88 @@ def test_update_google_signals_settings_rest_flattened_error(transport: str = "r # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_google_signals_settings( - analytics_admin.UpdateGoogleSignalsSettingsRequest(), - google_signals_settings=resources.GoogleSignalsSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_display_video360_advertiser_links( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), + parent="parent_value", + ) + + +def test_list_display_video360_advertiser_links_rest_pager(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], + next_page_token="def", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_display_video360_advertiser_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, resources.DisplayVideo360AdvertiserLink) for i in results ) - -def test_update_google_signals_settings_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + pages = list( + client.list_display_video360_advertiser_links(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateConversionEventRequest, + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_create_conversion_event_rest(request_type): +def test_create_display_video360_advertiser_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -69253,25 +79370,21 @@ def test_create_conversion_event_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "properties/sample1"} - request_init["conversion_event"] = { + request_init["display_video_360_advertiser_link"] = { "name": "name_value", - "event_name": "event_name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "deletable": True, - "custom": True, - "counting_method": 1, - "default_conversion_value": { - "value": 0.541, - "currency_code": "currency_code_value", - }, + "advertiser_id": "advertiser_id_value", + "advertiser_display_name": "advertiser_display_name_value", + "ads_personalization_enabled": {"value": True}, + "campaign_data_sharing_enabled": {}, + "cost_data_sharing_enabled": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateConversionEventRequest.meta.fields[ - "conversion_event" + test_field = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.meta.fields[ + "display_video_360_advertiser_link" ] def get_message_fields(field): @@ -69300,7 +79413,9 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["conversion_event"].items(): # pragma: NO COVER + for field, value in request_init[ + "display_video_360_advertiser_link" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -69330,47 +79445,44 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["conversion_event"][field])): - del request_init["conversion_event"][field][i][subfield] + for i in range( + 0, len(request_init["display_video_360_advertiser_link"][field]) + ): + del request_init["display_video_360_advertiser_link"][field][i][ + subfield + ] else: - del request_init["conversion_event"][field][subfield] + del request_init["display_video_360_advertiser_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent( + return_value = resources.DisplayVideo360AdvertiserLink( name="name_value", - event_name="event_name_value", - deletable=True, - custom=True, - counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_conversion_event(request) + response = client.create_display_video360_advertiser_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.ConversionEvent) + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) assert response.name == "name_value" - assert response.event_name == "event_name_value" - assert response.deletable is True - assert response.custom is True - assert ( - response.counting_method - == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT - ) + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_create_conversion_event_rest_use_cached_wrapped_rpc(): +def test_create_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -69385,7 +79497,7 @@ def test_create_conversion_event_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_conversion_event + client._transport.create_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -69395,24 +79507,24 @@ def test_create_conversion_event_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_conversion_event + client._transport.create_display_video360_advertiser_link ] = mock_rpc request = {} - client.create_conversion_event(request) + client.create_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_conversion_event(request) + client.create_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_conversion_event_rest_required_fields( - request_type=analytics_admin.CreateConversionEventRequest, +def test_create_display_video360_advertiser_link_rest_required_fields( + request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -69428,7 +79540,9 @@ def test_create_conversion_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_conversion_event._get_unset_required_fields(jsonified_request) + ).create_display_video360_advertiser_link._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -69437,7 +79551,9 @@ def test_create_conversion_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_conversion_event._get_unset_required_fields(jsonified_request) + ).create_display_video360_advertiser_link._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -69451,7 +79567,7 @@ def test_create_conversion_event_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent() + return_value = resources.DisplayVideo360AdvertiserLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -69473,38 +79589,40 @@ def test_create_conversion_event_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_conversion_event(request) + response = client.create_display_video360_advertiser_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_conversion_event_rest_unset_required_fields(): +def test_create_display_video360_advertiser_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_conversion_event._get_unset_required_fields({}) + unset_fields = ( + transport.create_display_video360_advertiser_link._get_unset_required_fields({}) + ) assert set(unset_fields) == ( set(()) & set( ( - "conversionEvent", "parent", + "displayVideo360AdvertiserLink", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversion_event_rest_interceptors(null_interceptor): +def test_create_display_video360_advertiser_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -69517,14 +79635,16 @@ def test_create_conversion_event_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_conversion_event" + transports.AnalyticsAdminServiceRestInterceptor, + "post_create_display_video360_advertiser_link", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_conversion_event" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_create_display_video360_advertiser_link", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateConversionEventRequest.pb( - analytics_admin.CreateConversionEventRequest() + pb_message = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.pb( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() ) transcode.return_value = { "method": "post", @@ -69536,19 +79656,19 @@ def test_create_conversion_event_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.ConversionEvent.to_json( - resources.ConversionEvent() + req.return_value._content = resources.DisplayVideo360AdvertiserLink.to_json( + resources.DisplayVideo360AdvertiserLink() ) - request = analytics_admin.CreateConversionEventRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.ConversionEvent() + post.return_value = resources.DisplayVideo360AdvertiserLink() - client.create_conversion_event( + client.create_display_video360_advertiser_link( request, metadata=[ ("key", "val"), @@ -69560,8 +79680,9 @@ def test_create_conversion_event_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_conversion_event_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateConversionEventRequest +def test_create_display_video360_advertiser_link_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -69581,10 +79702,10 @@ def test_create_conversion_event_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_conversion_event(request) + client.create_display_video360_advertiser_link(request) -def test_create_conversion_event_rest_flattened(): +def test_create_display_video360_advertiser_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -69593,7 +79714,7 @@ def test_create_conversion_event_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent() + return_value = resources.DisplayVideo360AdvertiserLink() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -69601,7 +79722,9 @@ def test_create_conversion_event_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - conversion_event=resources.ConversionEvent(name="name_value"), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), ) mock_args.update(sample_request) @@ -69609,25 +79732,27 @@ def test_create_conversion_event_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_conversion_event(**mock_args) + client.create_display_video360_advertiser_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/conversionEvents" + "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks" % client.transport._host, args[1], ) -def test_create_conversion_event_rest_flattened_error(transport: str = "rest"): +def test_create_display_video360_advertiser_link_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -69636,14 +79761,16 @@ def test_create_conversion_event_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_conversion_event( - analytics_admin.CreateConversionEventRequest(), + client.create_display_video360_advertiser_link( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), parent="parent_value", - conversion_event=resources.ConversionEvent(name="name_value"), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), ) -def test_create_conversion_event_rest_error(): +def test_create_display_video360_advertiser_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -69652,138 +79779,39 @@ def test_create_conversion_event_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateConversionEventRequest, + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_update_conversion_event_rest(request_type): +def test_delete_display_video360_advertiser_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "conversion_event": {"name": "properties/sample1/conversionEvents/sample2"} - } - request_init["conversion_event"] = { - "name": "properties/sample1/conversionEvents/sample2", - "event_name": "event_name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "deletable": True, - "custom": True, - "counting_method": 1, - "default_conversion_value": { - "value": 0.541, - "currency_code": "currency_code_value", - }, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateConversionEventRequest.meta.fields[ - "conversion_event" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["conversion_event"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["conversion_event"][field])): - del request_init["conversion_event"][field][i][subfield] - else: - del request_init["conversion_event"][field][subfield] + request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent( - name="name_value", - event_name="event_name_value", - deletable=True, - custom=True, - counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_conversion_event(request) + response = client.delete_display_video360_advertiser_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.ConversionEvent) - assert response.name == "name_value" - assert response.event_name == "event_name_value" - assert response.deletable is True - assert response.custom is True - assert ( - response.counting_method - == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT - ) + assert response is None -def test_update_conversion_event_rest_use_cached_wrapped_rpc(): +def test_delete_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -69798,7 +79826,7 @@ def test_update_conversion_event_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_conversion_event + client._transport.delete_display_video360_advertiser_link in client._transport._wrapped_methods ) @@ -69808,28 +79836,29 @@ def test_update_conversion_event_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_conversion_event + client._transport.delete_display_video360_advertiser_link ] = mock_rpc request = {} - client.update_conversion_event(request) + client.delete_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_conversion_event(request) + client.delete_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_conversion_event_rest_required_fields( - request_type=analytics_admin.UpdateConversionEventRequest, +def test_delete_display_video360_advertiser_link_rest_required_fields( + request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -69840,19 +79869,25 @@ def test_update_conversion_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_conversion_event._get_unset_required_fields(jsonified_request) + ).delete_display_video360_advertiser_link._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_conversion_event._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).delete_display_video360_advertiser_link._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -69861,7 +79896,7 @@ def test_update_conversion_event_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -69873,48 +79908,38 @@ def test_update_conversion_event_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_conversion_event(request) + response = client.delete_display_video360_advertiser_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_conversion_event_rest_unset_required_fields(): +def test_delete_display_video360_advertiser_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_conversion_event._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "conversionEvent", - "updateMask", - ) - ) + unset_fields = ( + transport.delete_display_video360_advertiser_link._get_unset_required_fields({}) ) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversion_event_rest_interceptors(null_interceptor): +def test_delete_display_video360_advertiser_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -69927,14 +79952,12 @@ def test_update_conversion_event_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_conversion_event" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_conversion_event" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_delete_display_video360_advertiser_link", ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateConversionEventRequest.pb( - analytics_admin.UpdateConversionEventRequest() + pb_message = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest.pb( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() ) transcode.return_value = { "method": "post", @@ -69946,19 +79969,15 @@ def test_update_conversion_event_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.ConversionEvent.to_json( - resources.ConversionEvent() - ) - request = analytics_admin.UpdateConversionEventRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.ConversionEvent() - client.update_conversion_event( + client.delete_display_video360_advertiser_link( request, metadata=[ ("key", "val"), @@ -69967,11 +79986,11 @@ def test_update_conversion_event_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_conversion_event_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateConversionEventRequest +def test_delete_display_video360_advertiser_link_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -69979,9 +79998,7 @@ def test_update_conversion_event_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "conversion_event": {"name": "properties/sample1/conversionEvents/sample2"} - } + request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -69993,10 +80010,10 @@ def test_update_conversion_event_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_conversion_event(request) + client.delete_display_video360_advertiser_link(request) -def test_update_conversion_event_rest_flattened(): +def test_delete_display_video360_advertiser_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -70005,43 +80022,42 @@ def test_update_conversion_event_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "conversion_event": {"name": "properties/sample1/conversionEvents/sample2"} + "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" } # get truthy value for each flattened field mock_args = dict( - conversion_event=resources.ConversionEvent(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_conversion_event(**mock_args) + client.delete_display_video360_advertiser_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{conversion_event.name=properties/*/conversionEvents/*}" + "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}" % client.transport._host, args[1], ) -def test_update_conversion_event_rest_flattened_error(transport: str = "rest"): +def test_delete_display_video360_advertiser_link_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -70050,14 +80066,13 @@ def test_update_conversion_event_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_conversion_event( - analytics_admin.UpdateConversionEventRequest(), - conversion_event=resources.ConversionEvent(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_display_video360_advertiser_link( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), + name="name_value", ) -def test_update_conversion_event_rest_error(): +def test_delete_display_video360_advertiser_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -70066,55 +80081,135 @@ def test_update_conversion_event_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetConversionEventRequest, + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict, ], ) -def test_get_conversion_event_rest(request_type): +def test_update_display_video360_advertiser_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/conversionEvents/sample2"} + request_init = { + "display_video_360_advertiser_link": { + "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" + } + } + request_init["display_video_360_advertiser_link"] = { + "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2", + "advertiser_id": "advertiser_id_value", + "advertiser_display_name": "advertiser_display_name_value", + "ads_personalization_enabled": {"value": True}, + "campaign_data_sharing_enabled": {}, + "cost_data_sharing_enabled": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.meta.fields[ + "display_video_360_advertiser_link" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "display_video_360_advertiser_link" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["display_video_360_advertiser_link"][field]) + ): + del request_init["display_video_360_advertiser_link"][field][i][ + subfield + ] + else: + del request_init["display_video_360_advertiser_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent( + return_value = resources.DisplayVideo360AdvertiserLink( name="name_value", - event_name="event_name_value", - deletable=True, - custom=True, - counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_conversion_event(request) + response = client.update_display_video360_advertiser_link(request) - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ConversionEvent) - assert response.name == "name_value" - assert response.event_name == "event_name_value" - assert response.deletable is True - assert response.custom is True - assert ( - response.counting_method - == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT - ) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_get_conversion_event_rest_use_cached_wrapped_rpc(): +def test_update_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -70129,7 +80224,8 @@ def test_get_conversion_event_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_conversion_event in client._transport._wrapped_methods + client._transport.update_display_video360_advertiser_link + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -70138,29 +80234,28 @@ def test_get_conversion_event_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_conversion_event + client._transport.update_display_video360_advertiser_link ] = mock_rpc request = {} - client.get_conversion_event(request) + client.update_display_video360_advertiser_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_conversion_event(request) + client.update_display_video360_advertiser_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_conversion_event_rest_required_fields( - request_type=analytics_admin.GetConversionEventRequest, +def test_update_display_video360_advertiser_link_rest_required_fields( + request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -70171,21 +80266,23 @@ def test_get_conversion_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_conversion_event._get_unset_required_fields(jsonified_request) + ).update_display_video360_advertiser_link._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_conversion_event._get_unset_required_fields(jsonified_request) + ).update_display_video360_advertiser_link._get_unset_required_fields( + jsonified_request + ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -70194,7 +80291,7 @@ def test_get_conversion_event_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent() + return_value = resources.DisplayVideo360AdvertiserLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -70206,39 +80303,42 @@ def test_get_conversion_event_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_conversion_event(request) + response = client.update_display_video360_advertiser_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_conversion_event_rest_unset_required_fields(): +def test_update_display_video360_advertiser_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_conversion_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = ( + transport.update_display_video360_advertiser_link._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversion_event_rest_interceptors(null_interceptor): +def test_update_display_video360_advertiser_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -70251,14 +80351,16 @@ def test_get_conversion_event_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_conversion_event" + transports.AnalyticsAdminServiceRestInterceptor, + "post_update_display_video360_advertiser_link", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_conversion_event" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_update_display_video360_advertiser_link", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetConversionEventRequest.pb( - analytics_admin.GetConversionEventRequest() + pb_message = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.pb( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() ) transcode.return_value = { "method": "post", @@ -70270,19 +80372,19 @@ def test_get_conversion_event_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.ConversionEvent.to_json( - resources.ConversionEvent() + req.return_value._content = resources.DisplayVideo360AdvertiserLink.to_json( + resources.DisplayVideo360AdvertiserLink() ) - request = analytics_admin.GetConversionEventRequest() + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.ConversionEvent() + post.return_value = resources.DisplayVideo360AdvertiserLink() - client.get_conversion_event( + client.update_display_video360_advertiser_link( request, metadata=[ ("key", "val"), @@ -70294,8 +80396,9 @@ def test_get_conversion_event_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_conversion_event_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetConversionEventRequest +def test_update_display_video360_advertiser_link_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -70303,7 +80406,11 @@ def test_get_conversion_event_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/conversionEvents/sample2"} + request_init = { + "display_video_360_advertiser_link": { + "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -70315,10 +80422,10 @@ def test_get_conversion_event_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_conversion_event(request) + client.update_display_video360_advertiser_link(request) -def test_get_conversion_event_rest_flattened(): +def test_update_display_video360_advertiser_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -70327,14 +80434,21 @@ def test_get_conversion_event_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ConversionEvent() + return_value = resources.DisplayVideo360AdvertiserLink() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/conversionEvents/sample2"} + sample_request = { + "display_video_360_advertiser_link": { + "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" + } + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -70342,25 +80456,27 @@ def test_get_conversion_event_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ConversionEvent.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_conversion_event(**mock_args) + client.update_display_video360_advertiser_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/conversionEvents/*}" + "%s/v1alpha/{display_video_360_advertiser_link.name=properties/*/displayVideo360AdvertiserLinks/*}" % client.transport._host, args[1], ) -def test_get_conversion_event_rest_flattened_error(transport: str = "rest"): +def test_update_display_video360_advertiser_link_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -70369,13 +80485,16 @@ def test_get_conversion_event_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_conversion_event( - analytics_admin.GetConversionEventRequest(), - name="name_value", + client.update_display_video360_advertiser_link( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_conversion_event_rest_error(): +def test_update_display_video360_advertiser_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -70384,39 +80503,52 @@ def test_get_conversion_event_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteConversionEventRequest, + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_delete_conversion_event_rest(request_type): +def test_get_display_video360_advertiser_link_proposal_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/conversionEvents/sample2"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_conversion_event(request) + response = client.get_display_video360_advertiser_link_proposal(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" -def test_delete_conversion_event_rest_use_cached_wrapped_rpc(): +def test_get_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -70431,7 +80563,7 @@ def test_delete_conversion_event_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_conversion_event + client._transport.get_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -70441,24 +80573,24 @@ def test_delete_conversion_event_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_conversion_event + client._transport.get_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.delete_conversion_event(request) + client.get_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_conversion_event(request) + client.get_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_conversion_event_rest_required_fields( - request_type=analytics_admin.DeleteConversionEventRequest, +def test_get_display_video360_advertiser_link_proposal_rest_required_fields( + request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -70474,7 +80606,9 @@ def test_delete_conversion_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_conversion_event._get_unset_required_fields(jsonified_request) + ).get_display_video360_advertiser_link_proposal._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -70483,7 +80617,9 @@ def test_delete_conversion_event_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_conversion_event._get_unset_required_fields(jsonified_request) + ).get_display_video360_advertiser_link_proposal._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -70497,7 +80633,7 @@ def test_delete_conversion_event_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DisplayVideo360AdvertiserLinkProposal() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -70509,36 +80645,45 @@ def test_delete_conversion_event_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_conversion_event(request) + response = client.get_display_video360_advertiser_link_proposal(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_conversion_event_rest_unset_required_fields(): +def test_get_display_video360_advertiser_link_proposal_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_conversion_event._get_unset_required_fields({}) + unset_fields = transport.get_display_video360_advertiser_link_proposal._get_unset_required_fields( + {} + ) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversion_event_rest_interceptors(null_interceptor): +def test_get_display_video360_advertiser_link_proposal_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -70551,11 +80696,16 @@ def test_delete_conversion_event_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_conversion_event" + transports.AnalyticsAdminServiceRestInterceptor, + "post_get_display_video360_advertiser_link_proposal", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_get_display_video360_advertiser_link_proposal", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteConversionEventRequest.pb( - analytics_admin.DeleteConversionEventRequest() + post.assert_not_called() + pb_message = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest.pb( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() ) transcode.return_value = { "method": "post", @@ -70567,15 +80717,21 @@ def test_delete_conversion_event_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = ( + resources.DisplayVideo360AdvertiserLinkProposal.to_json( + resources.DisplayVideo360AdvertiserLinkProposal() + ) + ) - request = analytics_admin.DeleteConversionEventRequest() + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.delete_conversion_event( + client.get_display_video360_advertiser_link_proposal( request, metadata=[ ("key", "val"), @@ -70584,10 +80740,12 @@ def test_delete_conversion_event_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_conversion_event_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteConversionEventRequest +def test_get_display_video360_advertiser_link_proposal_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -70595,7 +80753,9 @@ def test_delete_conversion_event_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/conversionEvents/sample2"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -70607,10 +80767,10 @@ def test_delete_conversion_event_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_conversion_event(request) + client.get_display_video360_advertiser_link_proposal(request) -def test_delete_conversion_event_rest_flattened(): +def test_get_display_video360_advertiser_link_proposal_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -70619,10 +80779,12 @@ def test_delete_conversion_event_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DisplayVideo360AdvertiserLinkProposal() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/conversionEvents/sample2"} + sample_request = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } # get truthy value for each flattened field mock_args = dict( @@ -70633,24 +80795,28 @@ def test_delete_conversion_event_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_conversion_event(**mock_args) + client.get_display_video360_advertiser_link_proposal(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/conversionEvents/*}" + "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}" % client.transport._host, args[1], ) -def test_delete_conversion_event_rest_flattened_error(transport: str = "rest"): +def test_get_display_video360_advertiser_link_proposal_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -70659,13 +80825,13 @@ def test_delete_conversion_event_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_conversion_event( - analytics_admin.DeleteConversionEventRequest(), + client.get_display_video360_advertiser_link_proposal( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), name="name_value", ) -def test_delete_conversion_event_rest_error(): +def test_get_display_video360_advertiser_link_proposal_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -70674,11 +80840,11 @@ def test_delete_conversion_event_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListConversionEventsRequest, + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict, ], ) -def test_list_conversion_events_rest(request_type): +def test_list_display_video360_advertiser_link_proposals_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -70691,27 +80857,33 @@ def test_list_conversion_events_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListConversionEventsResponse( - next_page_token="next_page_token_value", + return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token="next_page_token_value", + ) ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListConversionEventsResponse.pb(return_value) + return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_conversion_events(request) + response = client.list_display_video360_advertiser_link_proposals(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversionEventsPager) + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsPager) assert response.next_page_token == "next_page_token_value" -def test_list_conversion_events_rest_use_cached_wrapped_rpc(): +def test_list_display_video360_advertiser_link_proposals_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -70726,7 +80898,7 @@ def test_list_conversion_events_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_conversion_events + client._transport.list_display_video360_advertiser_link_proposals in client._transport._wrapped_methods ) @@ -70736,24 +80908,24 @@ def test_list_conversion_events_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_conversion_events + client._transport.list_display_video360_advertiser_link_proposals ] = mock_rpc request = {} - client.list_conversion_events(request) + client.list_display_video360_advertiser_link_proposals(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_conversion_events(request) + client.list_display_video360_advertiser_link_proposals(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_conversion_events_rest_required_fields( - request_type=analytics_admin.ListConversionEventsRequest, +def test_list_display_video360_advertiser_link_proposals_rest_required_fields( + request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -70769,7 +80941,9 @@ def test_list_conversion_events_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_conversion_events._get_unset_required_fields(jsonified_request) + ).list_display_video360_advertiser_link_proposals._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -70778,7 +80952,9 @@ def test_list_conversion_events_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_conversion_events._get_unset_required_fields(jsonified_request) + ).list_display_video360_advertiser_link_proposals._get_unset_required_fields( + jsonified_request + ) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -70799,7 +80975,7 @@ def test_list_conversion_events_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListConversionEventsResponse() + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -70820,25 +80996,31 @@ def test_list_conversion_events_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListConversionEventsResponse.pb(return_value) + return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_conversion_events(request) + response = client.list_display_video360_advertiser_link_proposals(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_conversion_events_rest_unset_required_fields(): +def test_list_display_video360_advertiser_link_proposals_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_conversion_events._get_unset_required_fields({}) + unset_fields = transport.list_display_video360_advertiser_link_proposals._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set( ( @@ -70851,7 +81033,9 @@ def test_list_conversion_events_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversion_events_rest_interceptors(null_interceptor): +def test_list_display_video360_advertiser_link_proposals_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -70864,14 +81048,18 @@ def test_list_conversion_events_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_conversion_events" + transports.AnalyticsAdminServiceRestInterceptor, + "post_list_display_video360_advertiser_link_proposals", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_conversion_events" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_list_display_video360_advertiser_link_proposals", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListConversionEventsRequest.pb( - analytics_admin.ListConversionEventsRequest() + pb_message = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest.pb( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + ) ) transcode.return_value = { "method": "post", @@ -70884,20 +81072,22 @@ def test_list_conversion_events_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = ( - analytics_admin.ListConversionEventsResponse.to_json( - analytics_admin.ListConversionEventsResponse() + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.to_json( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() ) ) - request = analytics_admin.ListConversionEventsRequest() + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListConversionEventsResponse() + post.return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + ) - client.list_conversion_events( + client.list_display_video360_advertiser_link_proposals( request, metadata=[ ("key", "val"), @@ -70909,8 +81099,9 @@ def test_list_conversion_events_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_conversion_events_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListConversionEventsRequest +def test_list_display_video360_advertiser_link_proposals_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -70930,10 +81121,10 @@ def test_list_conversion_events_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_conversion_events(request) + client.list_display_video360_advertiser_link_proposals(request) -def test_list_conversion_events_rest_flattened(): +def test_list_display_video360_advertiser_link_proposals_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -70942,7 +81133,9 @@ def test_list_conversion_events_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListConversionEventsResponse() + return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + ) # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -70957,25 +81150,31 @@ def test_list_conversion_events_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListConversionEventsResponse.pb(return_value) + return_value = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_conversion_events(**mock_args) + client.list_display_video360_advertiser_link_proposals(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/conversionEvents" + "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals" % client.transport._host, args[1], ) -def test_list_conversion_events_rest_flattened_error(transport: str = "rest"): +def test_list_display_video360_advertiser_link_proposals_rest_flattened_error( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -70984,13 +81183,15 @@ def test_list_conversion_events_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_conversion_events( - analytics_admin.ListConversionEventsRequest(), + client.list_display_video360_advertiser_link_proposals( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), parent="parent_value", ) -def test_list_conversion_events_rest_pager(transport: str = "rest"): +def test_list_display_video360_advertiser_link_proposals_rest_pager( + transport: str = "rest", +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -71002,28 +81203,28 @@ def test_list_conversion_events_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - analytics_admin.ListConversionEventsResponse( - conversion_events=[ - resources.ConversionEvent(), - resources.ConversionEvent(), - resources.ConversionEvent(), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), ], next_page_token="abc", ), - analytics_admin.ListConversionEventsResponse( - conversion_events=[], + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], next_page_token="def", ), - analytics_admin.ListConversionEventsResponse( - conversion_events=[ - resources.ConversionEvent(), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), ], next_page_token="ghi", ), - analytics_admin.ListConversionEventsResponse( - conversion_events=[ - resources.ConversionEvent(), - resources.ConversionEvent(), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), ], ), ) @@ -71032,7 +81233,10 @@ def test_list_conversion_events_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - analytics_admin.ListConversionEventsResponse.to_json(x) for x in response + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.to_json( + x + ) + for x in response ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): @@ -71042,13 +81246,22 @@ def test_list_conversion_events_rest_pager(transport: str = "rest"): sample_request = {"parent": "properties/sample1"} - pager = client.list_conversion_events(request=sample_request) + pager = client.list_display_video360_advertiser_link_proposals( + request=sample_request + ) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.ConversionEvent) for i in results) + assert all( + isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) + for i in results + ) - pages = list(client.list_conversion_events(request=sample_request).pages) + pages = list( + client.list_display_video360_advertiser_link_proposals( + request=sample_request + ).pages + ) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -71056,48 +81269,148 @@ def test_list_conversion_events_rest_pager(transport: str = "rest"): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_get_display_video360_advertiser_link_rest(request_type): +def test_create_display_video360_advertiser_link_proposal_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} + request_init = {"parent": "properties/sample1"} + request_init["display_video_360_advertiser_link_proposal"] = { + "name": "name_value", + "advertiser_id": "advertiser_id_value", + "link_proposal_status_details": { + "link_proposal_initiating_product": 1, + "requestor_email": "requestor_email_value", + "link_proposal_state": 1, + }, + "advertiser_display_name": "advertiser_display_name_value", + "validation_email": "validation_email_value", + "ads_personalization_enabled": {"value": True}, + "campaign_data_sharing_enabled": {}, + "cost_data_sharing_enabled": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.meta.fields[ + "display_video_360_advertiser_link_proposal" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "display_video_360_advertiser_link_proposal" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init["display_video_360_advertiser_link_proposal"][ + field + ] + ), + ): + del request_init["display_video_360_advertiser_link_proposal"][ + field + ][i][subfield] + else: + del request_init["display_video_360_advertiser_link_proposal"][field][ + subfield + ] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink( + return_value = resources.DisplayVideo360AdvertiserLinkProposal( name="name_value", advertiser_id="advertiser_id_value", advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_display_video360_advertiser_link(request) + response = client.create_display_video360_advertiser_link_proposal(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) assert response.name == "name_value" assert response.advertiser_id == "advertiser_id_value" assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" -def test_get_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): +def test_create_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -71112,7 +81425,7 @@ def test_get_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_display_video360_advertiser_link + client._transport.create_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -71122,29 +81435,29 @@ def test_get_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_display_video360_advertiser_link + client._transport.create_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.get_display_video360_advertiser_link(request) + client.create_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_display_video360_advertiser_link(request) + client.create_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_display_video360_advertiser_link_rest_required_fields( - request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, +def test_create_display_video360_advertiser_link_proposal_rest_required_fields( + request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -71155,21 +81468,25 @@ def test_get_display_video360_advertiser_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_display_video360_advertiser_link._get_unset_required_fields(jsonified_request) + ).create_display_video360_advertiser_link_proposal._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_display_video360_advertiser_link._get_unset_required_fields(jsonified_request) + ).create_display_video360_advertiser_link_proposal._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -71178,7 +81495,7 @@ def test_get_display_video360_advertiser_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink() + return_value = resources.DisplayVideo360AdvertiserLinkProposal() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -71190,41 +81507,54 @@ def test_get_display_video360_advertiser_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_display_video360_advertiser_link(request) + response = client.create_display_video360_advertiser_link_proposal(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_display_video360_advertiser_link_rest_unset_required_fields(): +def test_create_display_video360_advertiser_link_proposal_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.get_display_video360_advertiser_link._get_unset_required_fields({}) + unset_fields = transport.create_display_video360_advertiser_link_proposal._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "displayVideo360AdvertiserLinkProposal", + ) + ) ) - assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_display_video360_advertiser_link_rest_interceptors(null_interceptor): +def test_create_display_video360_advertiser_link_proposal_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -71238,15 +81568,17 @@ def test_get_display_video360_advertiser_link_rest_interceptors(null_interceptor path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_get_display_video360_advertiser_link", + "post_create_display_video360_advertiser_link_proposal", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_display_video360_advertiser_link", + "pre_create_display_video360_advertiser_link_proposal", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest.pb( - analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + pb_message = ( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.pb( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + ) ) transcode.return_value = { "method": "post", @@ -71258,19 +81590,21 @@ def test_get_display_video360_advertiser_link_rest_interceptors(null_interceptor req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DisplayVideo360AdvertiserLink.to_json( - resources.DisplayVideo360AdvertiserLink() + req.return_value._content = ( + resources.DisplayVideo360AdvertiserLinkProposal.to_json( + resources.DisplayVideo360AdvertiserLinkProposal() + ) ) - request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DisplayVideo360AdvertiserLink() + post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.get_display_video360_advertiser_link( + client.create_display_video360_advertiser_link_proposal( request, metadata=[ ("key", "val"), @@ -71282,9 +81616,9 @@ def test_get_display_video360_advertiser_link_rest_interceptors(null_interceptor post.assert_called_once() -def test_get_display_video360_advertiser_link_rest_bad_request( +def test_create_display_video360_advertiser_link_proposal_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, + request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -71292,7 +81626,7 @@ def test_get_display_video360_advertiser_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -71304,10 +81638,10 @@ def test_get_display_video360_advertiser_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_display_video360_advertiser_link(request) + client.create_display_video360_advertiser_link_proposal(request) -def test_get_display_video360_advertiser_link_rest_flattened(): +def test_create_display_video360_advertiser_link_proposal_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -71316,16 +81650,17 @@ def test_get_display_video360_advertiser_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink() + return_value = resources.DisplayVideo360AdvertiserLinkProposal() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" - } + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value" + ), ) mock_args.update(sample_request) @@ -71333,25 +81668,25 @@ def test_get_display_video360_advertiser_link_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_display_video360_advertiser_link(**mock_args) + client.create_display_video360_advertiser_link_proposal(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}" + "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals" % client.transport._host, args[1], ) -def test_get_display_video360_advertiser_link_rest_flattened_error( +def test_create_display_video360_advertiser_link_proposal_rest_flattened_error( transport: str = "rest", ): client = AnalyticsAdminServiceClient( @@ -71362,13 +81697,16 @@ def test_get_display_video360_advertiser_link_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_display_video360_advertiser_link( - analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), - name="name_value", + client.create_display_video360_advertiser_link_proposal( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + parent="parent_value", + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value" + ), ) -def test_get_display_video360_advertiser_link_rest_error(): +def test_create_display_video360_advertiser_link_proposal_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -71377,46 +81715,41 @@ def test_get_display_video360_advertiser_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_list_display_video360_advertiser_links_rest(request_type): +def test_delete_display_video360_advertiser_link_proposal_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_display_video360_advertiser_links(request) + response = client.delete_display_video360_advertiser_link_proposal(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_display_video360_advertiser_links_rest_use_cached_wrapped_rpc(): +def test_delete_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -71431,7 +81764,7 @@ def test_list_display_video360_advertiser_links_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_display_video360_advertiser_links + client._transport.delete_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -71441,29 +81774,29 @@ def test_list_display_video360_advertiser_links_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_display_video360_advertiser_links + client._transport.delete_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.list_display_video360_advertiser_links(request) + client.delete_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_display_video360_advertiser_links(request) + client.delete_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_display_video360_advertiser_links_rest_required_fields( - request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, +def test_delete_display_video360_advertiser_link_proposal_rest_required_fields( + request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -71474,32 +81807,25 @@ def test_list_display_video360_advertiser_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_display_video360_advertiser_links._get_unset_required_fields( + ).delete_display_video360_advertiser_link_proposal._get_unset_required_fields( jsonified_request ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_display_video360_advertiser_links._get_unset_required_fields( + ).delete_display_video360_advertiser_link_proposal._get_unset_required_fields( jsonified_request ) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -71508,7 +81834,7 @@ def test_list_display_video360_advertiser_links_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -71520,53 +81846,40 @@ def test_list_display_video360_advertiser_links_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_display_video360_advertiser_links(request) + response = client.delete_display_video360_advertiser_link_proposal(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_display_video360_advertiser_links_rest_unset_required_fields(): +def test_delete_display_video360_advertiser_link_proposal_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.list_display_video360_advertiser_links._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) + unset_fields = transport.delete_display_video360_advertiser_link_proposal._get_unset_required_fields( + {} ) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_display_video360_advertiser_links_rest_interceptors(null_interceptor): +def test_delete_display_video360_advertiser_link_proposal_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -71580,15 +81893,13 @@ def test_list_display_video360_advertiser_links_rest_interceptors(null_intercept path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_list_display_video360_advertiser_links", - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_list_display_video360_advertiser_links", + "pre_delete_display_video360_advertiser_link_proposal", ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest.pb( - analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + pb_message = ( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest.pb( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + ) ) transcode.return_value = { "method": "post", @@ -71600,21 +81911,15 @@ def test_list_display_video360_advertiser_links_rest_interceptors(null_intercept req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.to_json( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() - ) - ) - request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() - client.list_display_video360_advertiser_links( + client.delete_display_video360_advertiser_link_proposal( request, metadata=[ ("key", "val"), @@ -71623,12 +81928,11 @@ def test_list_display_video360_advertiser_links_rest_interceptors(null_intercept ) pre.assert_called_once() - post.assert_called_once() -def test_list_display_video360_advertiser_links_rest_bad_request( +def test_delete_display_video360_advertiser_link_proposal_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -71636,7 +81940,9 @@ def test_list_display_video360_advertiser_links_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -71648,10 +81954,10 @@ def test_list_display_video360_advertiser_links_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_display_video360_advertiser_links(request) + client.delete_display_video360_advertiser_link_proposal(request) -def test_list_display_video360_advertiser_links_rest_flattened(): +def test_delete_display_video360_advertiser_link_proposal_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -71660,42 +81966,40 @@ def test_list_display_video360_advertiser_links_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_display_video360_advertiser_links(**mock_args) + client.delete_display_video360_advertiser_link_proposal(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks" + "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}" % client.transport._host, args[1], ) -def test_list_display_video360_advertiser_links_rest_flattened_error( +def test_delete_display_video360_advertiser_link_proposal_rest_flattened_error( transport: str = "rest", ): client = AnalyticsAdminServiceClient( @@ -71706,208 +82010,66 @@ def test_list_display_video360_advertiser_links_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_display_video360_advertiser_links( - analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), - parent="parent_value", + client.delete_display_video360_advertiser_link_proposal( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + name="name_value", ) -def test_list_display_video360_advertiser_links_rest_pager(transport: str = "rest"): +def test_delete_display_video360_advertiser_link_proposal_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[], - next_page_token="def", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( - display_video_360_advertiser_links=[ - resources.DisplayVideo360AdvertiserLink(), - resources.DisplayVideo360AdvertiserLink(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_display_video360_advertiser_links(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, resources.DisplayVideo360AdvertiserLink) for i in results - ) - - pages = list( - client.list_display_video360_advertiser_links(request=sample_request).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_create_display_video360_advertiser_link_rest(request_type): +def test_approve_display_video360_advertiser_link_proposal_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["display_video_360_advertiser_link"] = { - "name": "name_value", - "advertiser_id": "advertiser_id_value", - "advertiser_display_name": "advertiser_display_name_value", - "ads_personalization_enabled": {"value": True}, - "campaign_data_sharing_enabled": {}, - "cost_data_sharing_enabled": {}, + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.meta.fields[ - "display_video_360_advertiser_link" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "display_video_360_advertiser_link" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["display_video_360_advertiser_link"][field]) - ): - del request_init["display_video_360_advertiser_link"][field][i][ - subfield - ] - else: - del request_init["display_video_360_advertiser_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_display_video360_advertiser_link(request) + response = client.approve_display_video360_advertiser_link_proposal(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert isinstance( + response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse + ) -def test_create_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): +def test_approve_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -71922,7 +82084,7 @@ def test_create_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_display_video360_advertiser_link + client._transport.approve_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -71932,29 +82094,29 @@ def test_create_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_display_video360_advertiser_link + client._transport.approve_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.create_display_video360_advertiser_link(request) + client.approve_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_display_video360_advertiser_link(request) + client.approve_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_display_video360_advertiser_link_rest_required_fields( - request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, +def test_approve_display_video360_advertiser_link_proposal_rest_required_fields( + request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -71965,25 +82127,25 @@ def test_create_display_video360_advertiser_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_display_video360_advertiser_link._get_unset_required_fields( + ).approve_display_video360_advertiser_link_proposal._get_unset_required_fields( jsonified_request ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_display_video360_advertiser_link._get_unset_required_fields( + ).approve_display_video360_advertiser_link_proposal._get_unset_required_fields( jsonified_request ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -71992,7 +82154,9 @@ def test_create_display_video360_advertiser_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink() + return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -72014,40 +82178,38 @@ def test_create_display_video360_advertiser_link_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_display_video360_advertiser_link(request) + response = client.approve_display_video360_advertiser_link_proposal(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_display_video360_advertiser_link_rest_unset_required_fields(): +def test_approve_display_video360_advertiser_link_proposal_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.create_display_video360_advertiser_link._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "displayVideo360AdvertiserLink", - ) - ) + unset_fields = transport.approve_display_video360_advertiser_link_proposal._get_unset_required_fields( + {} ) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_display_video360_advertiser_link_rest_interceptors(null_interceptor): +def test_approve_display_video360_advertiser_link_proposal_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -72061,15 +82223,17 @@ def test_create_display_video360_advertiser_link_rest_interceptors(null_intercep path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_create_display_video360_advertiser_link", + "post_approve_display_video360_advertiser_link_proposal", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_create_display_video360_advertiser_link", + "pre_approve_display_video360_advertiser_link_proposal", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.pb( - analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + pb_message = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest.pb( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + ) ) transcode.return_value = { "method": "post", @@ -72081,19 +82245,21 @@ def test_create_display_video360_advertiser_link_rest_interceptors(null_intercep req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DisplayVideo360AdvertiserLink.to_json( - resources.DisplayVideo360AdvertiserLink() + req.return_value._content = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.to_json( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() ) - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DisplayVideo360AdvertiserLink() + post.return_value = ( + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + ) - client.create_display_video360_advertiser_link( + client.approve_display_video360_advertiser_link_proposal( request, metadata=[ ("key", "val"), @@ -72105,9 +82271,9 @@ def test_create_display_video360_advertiser_link_rest_interceptors(null_intercep post.assert_called_once() -def test_create_display_video360_advertiser_link_rest_bad_request( +def test_approve_display_video360_advertiser_link_proposal_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, + request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -72115,7 +82281,9 @@ def test_create_display_video360_advertiser_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -72127,75 +82295,10 @@ def test_create_display_video360_advertiser_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_display_video360_advertiser_link(request) - - -def test_create_display_video360_advertiser_link_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_display_video360_advertiser_link(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks" - % client.transport._host, - args[1], - ) - - -def test_create_display_video360_advertiser_link_rest_flattened_error( - transport: str = "rest", -): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_display_video360_advertiser_link( - analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), - parent="parent_value", - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - ) + client.approve_display_video360_advertiser_link_proposal(request) -def test_create_display_video360_advertiser_link_rest_error(): +def test_approve_display_video360_advertiser_link_proposal_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -72204,39 +82307,52 @@ def test_create_display_video360_advertiser_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict, ], ) -def test_delete_display_video360_advertiser_link_rest(request_type): +def test_cancel_display_video360_advertiser_link_proposal_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DisplayVideo360AdvertiserLinkProposal( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", + validation_email="validation_email_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_display_video360_advertiser_link(request) + response = client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.validation_email == "validation_email_value" -def test_delete_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): +def test_cancel_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -72251,7 +82367,7 @@ def test_delete_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_display_video360_advertiser_link + client._transport.cancel_display_video360_advertiser_link_proposal in client._transport._wrapped_methods ) @@ -72261,24 +82377,24 @@ def test_delete_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_display_video360_advertiser_link + client._transport.cancel_display_video360_advertiser_link_proposal ] = mock_rpc request = {} - client.delete_display_video360_advertiser_link(request) + client.cancel_display_video360_advertiser_link_proposal(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_display_video360_advertiser_link(request) + client.cancel_display_video360_advertiser_link_proposal(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_display_video360_advertiser_link_rest_required_fields( - request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, +def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields( + request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -72294,7 +82410,7 @@ def test_delete_display_video360_advertiser_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_display_video360_advertiser_link._get_unset_required_fields( + ).cancel_display_video360_advertiser_link_proposal._get_unset_required_fields( jsonified_request ) jsonified_request.update(unset_fields) @@ -72305,7 +82421,7 @@ def test_delete_display_video360_advertiser_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_display_video360_advertiser_link._get_unset_required_fields( + ).cancel_display_video360_advertiser_link_proposal._get_unset_required_fields( jsonified_request ) jsonified_request.update(unset_fields) @@ -72321,7 +82437,7 @@ def test_delete_display_video360_advertiser_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DisplayVideo360AdvertiserLinkProposal() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -72333,38 +82449,46 @@ def test_delete_display_video360_advertiser_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_display_video360_advertiser_link(request) + response = client.cancel_display_video360_advertiser_link_proposal(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_display_video360_advertiser_link_rest_unset_required_fields(): +def test_cancel_display_video360_advertiser_link_proposal_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.delete_display_video360_advertiser_link._get_unset_required_fields({}) + unset_fields = transport.cancel_display_video360_advertiser_link_proposal._get_unset_required_fields( + {} ) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_display_video360_advertiser_link_rest_interceptors(null_interceptor): +def test_cancel_display_video360_advertiser_link_proposal_rest_interceptors( + null_interceptor, +): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -72378,11 +82502,17 @@ def test_delete_display_video360_advertiser_link_rest_interceptors(null_intercep path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_delete_display_video360_advertiser_link", + "post_cancel_display_video360_advertiser_link_proposal", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_cancel_display_video360_advertiser_link_proposal", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest.pb( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + post.assert_not_called() + pb_message = ( + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest.pb( + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + ) ) transcode.return_value = { "method": "post", @@ -72394,15 +82524,21 @@ def test_delete_display_video360_advertiser_link_rest_interceptors(null_intercep req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = ( + resources.DisplayVideo360AdvertiserLinkProposal.to_json( + resources.DisplayVideo360AdvertiserLinkProposal() + ) + ) - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.delete_display_video360_advertiser_link( + client.cancel_display_video360_advertiser_link_proposal( request, metadata=[ ("key", "val"), @@ -72411,11 +82547,12 @@ def test_delete_display_video360_advertiser_link_rest_interceptors(null_intercep ) pre.assert_called_once() + post.assert_called_once() -def test_delete_display_video360_advertiser_link_rest_bad_request( +def test_cancel_display_video360_advertiser_link_proposal_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, + request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -72423,7 +82560,9 @@ def test_delete_display_video360_advertiser_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/displayVideo360AdvertiserLinks/sample2"} + request_init = { + "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -72435,69 +82574,10 @@ def test_delete_display_video360_advertiser_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_display_video360_advertiser_link(request) - - -def test_delete_display_video360_advertiser_link_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_display_video360_advertiser_link(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_display_video360_advertiser_link_rest_flattened_error( - transport: str = "rest", -): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_display_video360_advertiser_link( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), - name="name_value", - ) + client.cancel_display_video360_advertiser_link_proposal(request) -def test_delete_display_video360_advertiser_link_rest_error(): +def test_cancel_display_video360_advertiser_link_proposal_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -72506,37 +82586,33 @@ def test_delete_display_video360_advertiser_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, + analytics_admin.CreateCustomDimensionRequest, dict, ], ) -def test_update_display_video360_advertiser_link_rest(request_type): +def test_create_custom_dimension_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "display_video_360_advertiser_link": { - "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" - } - } - request_init["display_video_360_advertiser_link"] = { - "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2", - "advertiser_id": "advertiser_id_value", - "advertiser_display_name": "advertiser_display_name_value", - "ads_personalization_enabled": {"value": True}, - "campaign_data_sharing_enabled": {}, - "cost_data_sharing_enabled": {}, + request_init = {"parent": "properties/sample1"} + request_init["custom_dimension"] = { + "name": "name_value", + "parameter_name": "parameter_name_value", + "display_name": "display_name_value", + "description": "description_value", + "scope": 1, + "disallow_ads_personalization": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.meta.fields[ - "display_video_360_advertiser_link" + test_field = analytics_admin.CreateCustomDimensionRequest.meta.fields[ + "custom_dimension" ] def get_message_fields(field): @@ -72565,9 +82641,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "display_video_360_advertiser_link" - ].items(): # pragma: NO COVER + for field, value in request_init["custom_dimension"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -72597,44 +82671,46 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range( - 0, len(request_init["display_video_360_advertiser_link"][field]) - ): - del request_init["display_video_360_advertiser_link"][field][i][ - subfield - ] + for i in range(0, len(request_init["custom_dimension"][field])): + del request_init["custom_dimension"][field][i][subfield] else: - del request_init["display_video_360_advertiser_link"][field][subfield] + del request_init["custom_dimension"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink( + return_value = resources.CustomDimension( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = resources.CustomDimension.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_display_video360_advertiser_link(request) + response = client.create_custom_dimension(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True -def test_update_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): +def test_create_custom_dimension_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -72649,7 +82725,7 @@ def test_update_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_display_video360_advertiser_link + client._transport.create_custom_dimension in client._transport._wrapped_methods ) @@ -72659,28 +82735,29 @@ def test_update_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_display_video360_advertiser_link + client._transport.create_custom_dimension ] = mock_rpc request = {} - client.update_display_video360_advertiser_link(request) + client.create_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_display_video360_advertiser_link(request) + client.create_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_display_video360_advertiser_link_rest_required_fields( - request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, +def test_create_custom_dimension_rest_required_fields( + request_type=analytics_admin.CreateCustomDimensionRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -72691,23 +82768,21 @@ def test_update_display_video360_advertiser_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_display_video360_advertiser_link._get_unset_required_fields( - jsonified_request - ) + ).create_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_display_video360_advertiser_link._get_unset_required_fields( - jsonified_request - ) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).create_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -72716,7 +82791,7 @@ def test_update_display_video360_advertiser_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink() + return_value = resources.CustomDimension() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -72728,7 +82803,7 @@ def test_update_display_video360_advertiser_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -72738,32 +82813,38 @@ def test_update_display_video360_advertiser_link_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = resources.CustomDimension.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_display_video360_advertiser_link(request) + response = client.create_custom_dimension(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_display_video360_advertiser_link_rest_unset_required_fields(): +def test_create_custom_dimension_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.update_display_video360_advertiser_link._get_unset_required_fields({}) + unset_fields = transport.create_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "customDimension", + ) + ) ) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_display_video360_advertiser_link_rest_interceptors(null_interceptor): +def test_create_custom_dimension_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -72776,16 +82857,14 @@ def test_update_display_video360_advertiser_link_rest_interceptors(null_intercep ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_update_display_video360_advertiser_link", + transports.AnalyticsAdminServiceRestInterceptor, "post_create_custom_dimension" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_display_video360_advertiser_link", + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_dimension" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.pb( - analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + pb_message = analytics_admin.CreateCustomDimensionRequest.pb( + analytics_admin.CreateCustomDimensionRequest() ) transcode.return_value = { "method": "post", @@ -72797,19 +82876,19 @@ def test_update_display_video360_advertiser_link_rest_interceptors(null_intercep req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DisplayVideo360AdvertiserLink.to_json( - resources.DisplayVideo360AdvertiserLink() + req.return_value._content = resources.CustomDimension.to_json( + resources.CustomDimension() ) - request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + request = analytics_admin.CreateCustomDimensionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DisplayVideo360AdvertiserLink() + post.return_value = resources.CustomDimension() - client.update_display_video360_advertiser_link( + client.create_custom_dimension( request, metadata=[ ("key", "val"), @@ -72821,9 +82900,8 @@ def test_update_display_video360_advertiser_link_rest_interceptors(null_intercep post.assert_called_once() -def test_update_display_video360_advertiser_link_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, +def test_create_custom_dimension_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateCustomDimensionRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -72831,11 +82909,7 @@ def test_update_display_video360_advertiser_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "display_video_360_advertiser_link": { - "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" - } - } + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -72847,10 +82921,10 @@ def test_update_display_video360_advertiser_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_display_video360_advertiser_link(request) + client.create_custom_dimension(request) -def test_update_display_video360_advertiser_link_rest_flattened(): +def test_create_custom_dimension_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -72859,21 +82933,15 @@ def test_update_display_video360_advertiser_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLink() + return_value = resources.CustomDimension() # get arguments that satisfy an http rule for this method - sample_request = { - "display_video_360_advertiser_link": { - "name": "properties/sample1/displayVideo360AdvertiserLinks/sample2" - } - } + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", + custom_dimension=resources.CustomDimension(name="name_value"), ) mock_args.update(sample_request) @@ -72881,27 +82949,25 @@ def test_update_display_video360_advertiser_link_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLink.pb(return_value) + return_value = resources.CustomDimension.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_display_video360_advertiser_link(**mock_args) + client.create_custom_dimension(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{display_video_360_advertiser_link.name=properties/*/displayVideo360AdvertiserLinks/*}" + "%s/v1alpha/{parent=properties/*}/customDimensions" % client.transport._host, args[1], ) -def test_update_display_video360_advertiser_link_rest_flattened_error( - transport: str = "rest", -): +def test_create_custom_dimension_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -72910,70 +82976,149 @@ def test_update_display_video360_advertiser_link_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_display_video360_advertiser_link( - analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), - display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent="parent_value", + custom_dimension=resources.CustomDimension(name="name_value"), ) -def test_update_display_video360_advertiser_link_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) +def test_create_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.UpdateCustomDimensionRequest, + dict, + ], +) +def test_update_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "custom_dimension": {"name": "properties/sample1/customDimensions/sample2"} + } + request_init["custom_dimension"] = { + "name": "properties/sample1/customDimensions/sample2", + "parameter_name": "parameter_name_value", + "display_name": "display_name_value", + "description": "description_value", + "scope": 1, + "disallow_ads_personalization": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateCustomDimensionRequest.meta.fields[ + "custom_dimension" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, - dict, - ], -) -def test_get_display_video360_advertiser_link_proposal_rest(request_type): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + subfields_not_in_runtime = [] - # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" - } + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["custom_dimension"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["custom_dimension"][field])): + del request_init["custom_dimension"][field][i][subfield] + else: + del request_init["custom_dimension"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal( + return_value = resources.CustomDimension( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + return_value = resources.CustomDimension.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_display_video360_advertiser_link_proposal(request) + response = client.update_custom_dimension(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert isinstance(response, resources.CustomDimension) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True -def test_get_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): +def test_update_custom_dimension_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -72988,7 +83133,7 @@ def test_get_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_r # Ensure method has been cached assert ( - client._transport.get_display_video360_advertiser_link_proposal + client._transport.update_custom_dimension in client._transport._wrapped_methods ) @@ -72998,29 +83143,28 @@ def test_get_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_r "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_display_video360_advertiser_link_proposal + client._transport.update_custom_dimension ] = mock_rpc request = {} - client.get_display_video360_advertiser_link_proposal(request) + client.update_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_display_video360_advertiser_link_proposal(request) + client.update_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_display_video360_advertiser_link_proposal_rest_required_fields( - request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, +def test_update_custom_dimension_rest_required_fields( + request_type=analytics_admin.UpdateCustomDimensionRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -73031,25 +83175,19 @@ def test_get_display_video360_advertiser_link_proposal_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).update_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).update_custom_dimension._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -73058,7 +83196,7 @@ def test_get_display_video360_advertiser_link_proposal_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal() + return_value = resources.CustomDimension() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -73070,45 +83208,40 @@ def test_get_display_video360_advertiser_link_proposal_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb( - return_value - ) + return_value = resources.CustomDimension.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_display_video360_advertiser_link_proposal(request) + response = client.update_custom_dimension(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_display_video360_advertiser_link_proposal_rest_unset_required_fields(): +def test_update_custom_dimension_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_display_video360_advertiser_link_proposal._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_display_video360_advertiser_link_proposal_rest_interceptors( - null_interceptor, -): +def test_update_custom_dimension_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -73121,16 +83254,14 @@ def test_get_display_video360_advertiser_link_proposal_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_get_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "post_update_custom_dimension" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_dimension" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest.pb( - analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + pb_message = analytics_admin.UpdateCustomDimensionRequest.pb( + analytics_admin.UpdateCustomDimensionRequest() ) transcode.return_value = { "method": "post", @@ -73142,21 +83273,19 @@ def test_get_display_video360_advertiser_link_proposal_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - resources.DisplayVideo360AdvertiserLinkProposal.to_json( - resources.DisplayVideo360AdvertiserLinkProposal() - ) + req.return_value._content = resources.CustomDimension.to_json( + resources.CustomDimension() ) - request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.UpdateCustomDimensionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + post.return_value = resources.CustomDimension() - client.get_display_video360_advertiser_link_proposal( + client.update_custom_dimension( request, metadata=[ ("key", "val"), @@ -73168,9 +83297,8 @@ def test_get_display_video360_advertiser_link_proposal_rest_interceptors( post.assert_called_once() -def test_get_display_video360_advertiser_link_proposal_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, +def test_update_custom_dimension_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateCustomDimensionRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -73179,7 +83307,7 @@ def test_get_display_video360_advertiser_link_proposal_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + "custom_dimension": {"name": "properties/sample1/customDimensions/sample2"} } request = request_type(**request_init) @@ -73192,10 +83320,10 @@ def test_get_display_video360_advertiser_link_proposal_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_display_video360_advertiser_link_proposal(request) + client.update_custom_dimension(request) -def test_get_display_video360_advertiser_link_proposal_rest_flattened(): +def test_update_custom_dimension_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -73204,16 +83332,17 @@ def test_get_display_video360_advertiser_link_proposal_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal() + return_value = resources.CustomDimension() # get arguments that satisfy an http rule for this method sample_request = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + "custom_dimension": {"name": "properties/sample1/customDimensions/sample2"} } # get truthy value for each flattened field mock_args = dict( - name="name_value", + custom_dimension=resources.CustomDimension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -73221,27 +83350,25 @@ def test_get_display_video360_advertiser_link_proposal_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + return_value = resources.CustomDimension.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_display_video360_advertiser_link_proposal(**mock_args) + client.update_custom_dimension(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}" + "%s/v1alpha/{custom_dimension.name=properties/*/customDimensions/*}" % client.transport._host, args[1], ) -def test_get_display_video360_advertiser_link_proposal_rest_flattened_error( - transport: str = "rest", -): +def test_update_custom_dimension_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -73250,13 +83377,14 @@ def test_get_display_video360_advertiser_link_proposal_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_display_video360_advertiser_link_proposal( - analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), - name="name_value", + client.update_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_display_video360_advertiser_link_proposal_rest_error(): +def test_update_custom_dimension_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -73265,11 +83393,11 @@ def test_get_display_video360_advertiser_link_proposal_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + analytics_admin.ListCustomDimensionsRequest, dict, ], ) -def test_list_display_video360_advertiser_link_proposals_rest(request_type): +def test_list_custom_dimensions_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -73282,33 +83410,27 @@ def test_list_display_video360_advertiser_link_proposals_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - next_page_token="next_page_token_value", - ) + return_value = analytics_admin.ListCustomDimensionsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb( - return_value - ) - ) + return_value = analytics_admin.ListCustomDimensionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_display_video360_advertiser_link_proposals(request) + response = client.list_custom_dimensions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsPager) + assert isinstance(response, pagers.ListCustomDimensionsPager) assert response.next_page_token == "next_page_token_value" -def test_list_display_video360_advertiser_link_proposals_rest_use_cached_wrapped_rpc(): +def test_list_custom_dimensions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -73323,7 +83445,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_use_cached_wrapped # Ensure method has been cached assert ( - client._transport.list_display_video360_advertiser_link_proposals + client._transport.list_custom_dimensions in client._transport._wrapped_methods ) @@ -73333,24 +83455,24 @@ def test_list_display_video360_advertiser_link_proposals_rest_use_cached_wrapped "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_display_video360_advertiser_link_proposals + client._transport.list_custom_dimensions ] = mock_rpc request = {} - client.list_display_video360_advertiser_link_proposals(request) + client.list_custom_dimensions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_display_video360_advertiser_link_proposals(request) + client.list_custom_dimensions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_display_video360_advertiser_link_proposals_rest_required_fields( - request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, +def test_list_custom_dimensions_rest_required_fields( + request_type=analytics_admin.ListCustomDimensionsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -73366,9 +83488,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_display_video360_advertiser_link_proposals._get_unset_required_fields( - jsonified_request - ) + ).list_custom_dimensions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -73377,9 +83497,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_display_video360_advertiser_link_proposals._get_unset_required_fields( - jsonified_request - ) + ).list_custom_dimensions._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -73400,7 +83518,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + return_value = analytics_admin.ListCustomDimensionsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -73421,31 +83539,25 @@ def test_list_display_video360_advertiser_link_proposals_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb( - return_value - ) - ) + return_value = analytics_admin.ListCustomDimensionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_display_video360_advertiser_link_proposals(request) + response = client.list_custom_dimensions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_display_video360_advertiser_link_proposals_rest_unset_required_fields(): +def test_list_custom_dimensions_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_display_video360_advertiser_link_proposals._get_unset_required_fields( - {} - ) + unset_fields = transport.list_custom_dimensions._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -73458,9 +83570,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_unset_required_fie @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_display_video360_advertiser_link_proposals_rest_interceptors( - null_interceptor, -): +def test_list_custom_dimensions_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -73473,18 +83583,14 @@ def test_list_display_video360_advertiser_link_proposals_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_list_display_video360_advertiser_link_proposals", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_custom_dimensions" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_list_display_video360_advertiser_link_proposals", + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_dimensions" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest.pb( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ) + pb_message = analytics_admin.ListCustomDimensionsRequest.pb( + analytics_admin.ListCustomDimensionsRequest() ) transcode.return_value = { "method": "post", @@ -73497,22 +83603,20 @@ def test_list_display_video360_advertiser_link_proposals_rest_interceptors( req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.to_json( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + analytics_admin.ListCustomDimensionsResponse.to_json( + analytics_admin.ListCustomDimensionsResponse() ) ) - request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + request = analytics_admin.ListCustomDimensionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() - ) + post.return_value = analytics_admin.ListCustomDimensionsResponse() - client.list_display_video360_advertiser_link_proposals( + client.list_custom_dimensions( request, metadata=[ ("key", "val"), @@ -73524,9 +83628,8 @@ def test_list_display_video360_advertiser_link_proposals_rest_interceptors( post.assert_called_once() -def test_list_display_video360_advertiser_link_proposals_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, +def test_list_custom_dimensions_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListCustomDimensionsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -73546,10 +83649,10 @@ def test_list_display_video360_advertiser_link_proposals_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_display_video360_advertiser_link_proposals(request) + client.list_custom_dimensions(request) -def test_list_display_video360_advertiser_link_proposals_rest_flattened(): +def test_list_custom_dimensions_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -73558,9 +83661,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() - ) + return_value = analytics_admin.ListCustomDimensionsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -73575,31 +83676,25 @@ def test_list_display_video360_advertiser_link_proposals_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb( - return_value - ) - ) + return_value = analytics_admin.ListCustomDimensionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_display_video360_advertiser_link_proposals(**mock_args) + client.list_custom_dimensions(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals" + "%s/v1alpha/{parent=properties/*}/customDimensions" % client.transport._host, args[1], ) -def test_list_display_video360_advertiser_link_proposals_rest_flattened_error( - transport: str = "rest", -): +def test_list_custom_dimensions_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -73608,15 +83703,13 @@ def test_list_display_video360_advertiser_link_proposals_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_display_video360_advertiser_link_proposals( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + client.list_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), parent="parent_value", ) -def test_list_display_video360_advertiser_link_proposals_rest_pager( - transport: str = "rest", -): +def test_list_custom_dimensions_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -73628,28 +83721,28 @@ def test_list_display_video360_advertiser_link_proposals_rest_pager( # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), ], next_page_token="abc", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[], + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], next_page_token="def", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), ], next_page_token="ghi", ), - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( - display_video_360_advertiser_link_proposals=[ - resources.DisplayVideo360AdvertiserLinkProposal(), - resources.DisplayVideo360AdvertiserLinkProposal(), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), ], ), ) @@ -73658,10 +83751,7 @@ def test_list_display_video360_advertiser_link_proposals_rest_pager( # Wrap the values into proper Response objs response = tuple( - analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.to_json( - x - ) - for x in response + analytics_admin.ListCustomDimensionsResponse.to_json(x) for x in response ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): @@ -73671,22 +83761,13 @@ def test_list_display_video360_advertiser_link_proposals_rest_pager( sample_request = {"parent": "properties/sample1"} - pager = client.list_display_video360_advertiser_link_proposals( - request=sample_request - ) + pager = client.list_custom_dimensions(request=sample_request) results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) - for i in results - ) + assert all(isinstance(i, resources.CustomDimension) for i in results) - pages = list( - client.list_display_video360_advertiser_link_proposals( - request=sample_request - ).pages - ) + pages = list(client.list_custom_dimensions(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -73694,148 +83775,39 @@ def test_list_display_video360_advertiser_link_proposals_rest_pager( @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.ArchiveCustomDimensionRequest, dict, ], ) -def test_create_display_video360_advertiser_link_proposal_rest(request_type): +def test_archive_custom_dimension_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["display_video_360_advertiser_link_proposal"] = { - "name": "name_value", - "advertiser_id": "advertiser_id_value", - "link_proposal_status_details": { - "link_proposal_initiating_product": 1, - "requestor_email": "requestor_email_value", - "link_proposal_state": 1, - }, - "advertiser_display_name": "advertiser_display_name_value", - "validation_email": "validation_email_value", - "ads_personalization_enabled": {"value": True}, - "campaign_data_sharing_enabled": {}, - "cost_data_sharing_enabled": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.meta.fields[ - "display_video_360_advertiser_link_proposal" - ] - ) - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "display_video_360_advertiser_link_proposal" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, - len( - request_init["display_video_360_advertiser_link_proposal"][ - field - ] - ), - ): - del request_init["display_video_360_advertiser_link_proposal"][ - field - ][i][subfield] - else: - del request_init["display_video_360_advertiser_link_proposal"][field][ - subfield - ] + request_init = {"name": "properties/sample1/customDimensions/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_display_video360_advertiser_link_proposal(request) + response = client.archive_custom_dimension(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" + assert response is None -def test_create_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): +def test_archive_custom_dimension_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -73850,7 +83822,7 @@ def test_create_display_video360_advertiser_link_proposal_rest_use_cached_wrappe # Ensure method has been cached assert ( - client._transport.create_display_video360_advertiser_link_proposal + client._transport.archive_custom_dimension in client._transport._wrapped_methods ) @@ -73860,29 +83832,29 @@ def test_create_display_video360_advertiser_link_proposal_rest_use_cached_wrappe "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_display_video360_advertiser_link_proposal + client._transport.archive_custom_dimension ] = mock_rpc request = {} - client.create_display_video360_advertiser_link_proposal(request) + client.archive_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_display_video360_advertiser_link_proposal(request) + client.archive_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_display_video360_advertiser_link_proposal_rest_required_fields( - request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, +def test_archive_custom_dimension_rest_required_fields( + request_type=analytics_admin.ArchiveCustomDimensionRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -73893,25 +83865,21 @@ def test_create_display_video360_advertiser_link_proposal_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).archive_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).archive_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -73920,7 +83888,7 @@ def test_create_display_video360_advertiser_link_proposal_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -73940,46 +83908,29 @@ def test_create_display_video360_advertiser_link_proposal_rest_required_fields( response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_display_video360_advertiser_link_proposal(request) + response = client.archive_custom_dimension(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_display_video360_advertiser_link_proposal_rest_unset_required_fields(): +def test_archive_custom_dimension_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_display_video360_advertiser_link_proposal._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "displayVideo360AdvertiserLinkProposal", - ) - ) - ) + unset_fields = transport.archive_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_display_video360_advertiser_link_proposal_rest_interceptors( - null_interceptor, -): +def test_archive_custom_dimension_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -73992,18 +83943,11 @@ def test_create_display_video360_advertiser_link_proposal_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_create_display_video360_advertiser_link_proposal", - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_create_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_dimension" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = ( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.pb( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ) + pb_message = analytics_admin.ArchiveCustomDimensionRequest.pb( + analytics_admin.ArchiveCustomDimensionRequest() ) transcode.return_value = { "method": "post", @@ -74015,21 +83959,15 @@ def test_create_display_video360_advertiser_link_proposal_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - resources.DisplayVideo360AdvertiserLinkProposal.to_json( - resources.DisplayVideo360AdvertiserLinkProposal() - ) - ) - request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.ArchiveCustomDimensionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() - client.create_display_video360_advertiser_link_proposal( + client.archive_custom_dimension( request, metadata=[ ("key", "val"), @@ -74038,12 +83976,10 @@ def test_create_display_video360_advertiser_link_proposal_rest_interceptors( ) pre.assert_called_once() - post.assert_called_once() -def test_create_display_video360_advertiser_link_proposal_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, +def test_archive_custom_dimension_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ArchiveCustomDimensionRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -74051,7 +83987,7 @@ def test_create_display_video360_advertiser_link_proposal_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/customDimensions/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -74063,10 +83999,10 @@ def test_create_display_video360_advertiser_link_proposal_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_display_video360_advertiser_link_proposal(request) + client.archive_custom_dimension(request) -def test_create_display_video360_advertiser_link_proposal_rest_flattened(): +def test_archive_custom_dimension_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -74075,45 +84011,38 @@ def test_create_display_video360_advertiser_link_proposal_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"name": "properties/sample1/customDimensions/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( - name="name_value" - ), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_display_video360_advertiser_link_proposal(**mock_args) + client.archive_custom_dimension(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals" + "%s/v1alpha/{name=properties/*/customDimensions/*}:archive" % client.transport._host, args[1], ) -def test_create_display_video360_advertiser_link_proposal_rest_flattened_error( - transport: str = "rest", -): +def test_archive_custom_dimension_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -74122,16 +84051,13 @@ def test_create_display_video360_advertiser_link_proposal_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_display_video360_advertiser_link_proposal( - analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), - parent="parent_value", - display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal( - name="name_value" - ), + client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name="name_value", ) -def test_create_display_video360_advertiser_link_proposal_rest_error(): +def test_archive_custom_dimension_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -74140,41 +84066,54 @@ def test_create_display_video360_advertiser_link_proposal_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.GetCustomDimensionRequest, dict, ], ) -def test_delete_display_video360_advertiser_link_proposal_rest(request_type): +def test_get_custom_dimension_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" - } + request_init = {"name": "properties/sample1/customDimensions/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.CustomDimension( + name="name_value", + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.CustomDimension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_display_video360_advertiser_link_proposal(request) + response = client.get_custom_dimension(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.CustomDimension) + assert response.name == "name_value" + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True -def test_delete_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): +def test_get_custom_dimension_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -74189,8 +84128,7 @@ def test_delete_display_video360_advertiser_link_proposal_rest_use_cached_wrappe # Ensure method has been cached assert ( - client._transport.delete_display_video360_advertiser_link_proposal - in client._transport._wrapped_methods + client._transport.get_custom_dimension in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -74199,24 +84137,24 @@ def test_delete_display_video360_advertiser_link_proposal_rest_use_cached_wrappe "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_display_video360_advertiser_link_proposal + client._transport.get_custom_dimension ] = mock_rpc request = {} - client.delete_display_video360_advertiser_link_proposal(request) + client.get_custom_dimension(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_display_video360_advertiser_link_proposal(request) + client.get_custom_dimension(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_display_video360_advertiser_link_proposal_rest_required_fields( - request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, +def test_get_custom_dimension_rest_required_fields( + request_type=analytics_admin.GetCustomDimensionRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -74232,9 +84170,7 @@ def test_delete_display_video360_advertiser_link_proposal_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).get_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -74243,9 +84179,7 @@ def test_delete_display_video360_advertiser_link_proposal_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).get_custom_dimension._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -74259,7 +84193,7 @@ def test_delete_display_video360_advertiser_link_proposal_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.CustomDimension() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -74271,40 +84205,39 @@ def test_delete_display_video360_advertiser_link_proposal_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.CustomDimension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_display_video360_advertiser_link_proposal(request) + response = client.get_custom_dimension(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_display_video360_advertiser_link_proposal_rest_unset_required_fields(): +def test_get_custom_dimension_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_display_video360_advertiser_link_proposal._get_unset_required_fields( - {} - ) + unset_fields = transport.get_custom_dimension._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_display_video360_advertiser_link_proposal_rest_interceptors( - null_interceptor, -): +def test_get_custom_dimension_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -74317,14 +84250,14 @@ def test_delete_display_video360_advertiser_link_proposal_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_delete_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_custom_dimension" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_dimension" ) as pre: pre.assert_not_called() - pb_message = ( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest.pb( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ) + post.assert_not_called() + pb_message = analytics_admin.GetCustomDimensionRequest.pb( + analytics_admin.GetCustomDimensionRequest() ) transcode.return_value = { "method": "post", @@ -74336,15 +84269,19 @@ def test_delete_display_video360_advertiser_link_proposal_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.CustomDimension.to_json( + resources.CustomDimension() + ) - request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.GetCustomDimensionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.CustomDimension() - client.delete_display_video360_advertiser_link_proposal( + client.get_custom_dimension( request, metadata=[ ("key", "val"), @@ -74353,11 +84290,11 @@ def test_delete_display_video360_advertiser_link_proposal_rest_interceptors( ) pre.assert_called_once() + post.assert_called_once() -def test_delete_display_video360_advertiser_link_proposal_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, +def test_get_custom_dimension_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetCustomDimensionRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -74365,9 +84302,7 @@ def test_delete_display_video360_advertiser_link_proposal_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" - } + request_init = {"name": "properties/sample1/customDimensions/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -74379,10 +84314,10 @@ def test_delete_display_video360_advertiser_link_proposal_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_display_video360_advertiser_link_proposal(request) + client.get_custom_dimension(request) -def test_delete_display_video360_advertiser_link_proposal_rest_flattened(): +def test_get_custom_dimension_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -74391,12 +84326,10 @@ def test_delete_display_video360_advertiser_link_proposal_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.CustomDimension() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" - } + sample_request = {"name": "properties/sample1/customDimensions/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -74407,26 +84340,26 @@ def test_delete_display_video360_advertiser_link_proposal_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.CustomDimension.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_display_video360_advertiser_link_proposal(**mock_args) + client.get_custom_dimension(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}" + "%s/v1alpha/{name=properties/*/customDimensions/*}" % client.transport._host, args[1], ) -def test_delete_display_video360_advertiser_link_proposal_rest_flattened_error( - transport: str = "rest", -): +def test_get_custom_dimension_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -74435,13 +84368,13 @@ def test_delete_display_video360_advertiser_link_proposal_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_display_video360_advertiser_link_proposal( - analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + client.get_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), name="name_value", ) -def test_delete_display_video360_advertiser_link_proposal_rest_error(): +def test_get_custom_dimension_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -74450,51 +84383,136 @@ def test_delete_display_video360_advertiser_link_proposal_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.CreateCustomMetricRequest, dict, ], ) -def test_approve_display_video360_advertiser_link_proposal_rest(request_type): +def test_create_custom_metric_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + request_init = {"parent": "properties/sample1"} + request_init["custom_metric"] = { + "name": "name_value", + "parameter_name": "parameter_name_value", + "display_name": "display_name_value", + "description": "description_value", + "measurement_unit": 1, + "scope": 1, + "restricted_metric_type": [1], } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateCustomMetricRequest.meta.fields["custom_metric"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["custom_metric"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["custom_metric"][field])): + del request_init["custom_metric"][field][i][subfield] + else: + del request_init["custom_metric"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + return_value = resources.CustomMetric( + name="name_value", + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb( - return_value - ) - ) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.approve_display_video360_advertiser_link_proposal(request) + response = client.create_custom_metric(request) # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse - ) + assert isinstance(response, resources.CustomMetric) + assert response.name == "name_value" + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] -def test_approve_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): +def test_create_custom_metric_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -74509,8 +84527,7 @@ def test_approve_display_video360_advertiser_link_proposal_rest_use_cached_wrapp # Ensure method has been cached assert ( - client._transport.approve_display_video360_advertiser_link_proposal - in client._transport._wrapped_methods + client._transport.create_custom_metric in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -74519,29 +84536,29 @@ def test_approve_display_video360_advertiser_link_proposal_rest_use_cached_wrapp "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.approve_display_video360_advertiser_link_proposal + client._transport.create_custom_metric ] = mock_rpc request = {} - client.approve_display_video360_advertiser_link_proposal(request) + client.create_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.approve_display_video360_advertiser_link_proposal(request) + client.create_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_approve_display_video360_advertiser_link_proposal_rest_required_fields( - request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, +def test_create_custom_metric_rest_required_fields( + request_type=analytics_admin.CreateCustomMetricRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -74552,25 +84569,21 @@ def test_approve_display_video360_advertiser_link_proposal_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).approve_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).create_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).approve_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).create_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -74579,9 +84592,7 @@ def test_approve_display_video360_advertiser_link_proposal_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() - ) + return_value = resources.CustomMetric() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -74603,38 +84614,38 @@ def test_approve_display_video360_advertiser_link_proposal_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb( - return_value - ) - ) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.approve_display_video360_advertiser_link_proposal(request) + response = client.create_custom_metric(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_approve_display_video360_advertiser_link_proposal_rest_unset_required_fields(): +def test_create_custom_metric_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.approve_display_video360_advertiser_link_proposal._get_unset_required_fields( - {} + unset_fields = transport.create_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "customMetric", + ) + ) ) - assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_approve_display_video360_advertiser_link_proposal_rest_interceptors( - null_interceptor, -): +def test_create_custom_metric_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -74647,18 +84658,14 @@ def test_approve_display_video360_advertiser_link_proposal_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_approve_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "post_create_custom_metric" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_approve_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_metric" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest.pb( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ) + pb_message = analytics_admin.CreateCustomMetricRequest.pb( + analytics_admin.CreateCustomMetricRequest() ) transcode.return_value = { "method": "post", @@ -74670,21 +84677,19 @@ def test_approve_display_video360_advertiser_link_proposal_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.to_json( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + req.return_value._content = resources.CustomMetric.to_json( + resources.CustomMetric() ) - request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.CreateCustomMetricRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = ( - analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() - ) + post.return_value = resources.CustomMetric() - client.approve_display_video360_advertiser_link_proposal( + client.create_custom_metric( request, metadata=[ ("key", "val"), @@ -74696,9 +84701,8 @@ def test_approve_display_video360_advertiser_link_proposal_rest_interceptors( post.assert_called_once() -def test_approve_display_video360_advertiser_link_proposal_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, +def test_create_custom_metric_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateCustomMetricRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -74706,9 +84710,7 @@ def test_approve_display_video360_advertiser_link_proposal_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" - } + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -74720,10 +84722,68 @@ def test_approve_display_video360_advertiser_link_proposal_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.approve_display_video360_advertiser_link_proposal(request) + client.create_custom_metric(request) + + +def test_create_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + custom_metric=resources.CustomMetric(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_custom_metric(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=properties/*}/customMetrics" % client.transport._host, + args[1], + ) + + +def test_create_custom_metric_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent="parent_value", + custom_metric=resources.CustomMetric(name="name_value"), + ) -def test_approve_display_video360_advertiser_link_proposal_rest_error(): +def test_create_custom_metric_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -74732,11 +84792,11 @@ def test_approve_display_video360_advertiser_link_proposal_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, + analytics_admin.UpdateCustomMetricRequest, dict, ], ) -def test_cancel_display_video360_advertiser_link_proposal_rest(request_type): +def test_update_custom_metric_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -74744,40 +84804,126 @@ def test_cancel_display_video360_advertiser_link_proposal_rest(request_type): # send a request that will satisfy transcoding request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + "custom_metric": {"name": "properties/sample1/customMetrics/sample2"} } + request_init["custom_metric"] = { + "name": "properties/sample1/customMetrics/sample2", + "parameter_name": "parameter_name_value", + "display_name": "display_name_value", + "description": "description_value", + "measurement_unit": 1, + "scope": 1, + "restricted_metric_type": [1], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateCustomMetricRequest.meta.fields["custom_metric"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["custom_metric"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["custom_metric"][field])): + del request_init["custom_metric"][field][i][subfield] + else: + del request_init["custom_metric"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal( + return_value = resources.CustomMetric( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - validation_email="validation_email_value", + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.cancel_display_video360_advertiser_link_proposal(request) + response = client.update_custom_metric(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert isinstance(response, resources.CustomMetric) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" - assert response.validation_email == "validation_email_value" + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] -def test_cancel_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): +def test_update_custom_metric_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -74792,8 +84938,7 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_use_cached_wrappe # Ensure method has been cached assert ( - client._transport.cancel_display_video360_advertiser_link_proposal - in client._transport._wrapped_methods + client._transport.update_custom_metric in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -74802,29 +84947,28 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_use_cached_wrappe "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.cancel_display_video360_advertiser_link_proposal + client._transport.update_custom_metric ] = mock_rpc request = {} - client.cancel_display_video360_advertiser_link_proposal(request) + client.update_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.cancel_display_video360_advertiser_link_proposal(request) + client.update_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields( - request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, +def test_update_custom_metric_rest_required_fields( + request_type=analytics_admin.UpdateCustomMetricRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -74835,25 +84979,19 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).update_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel_display_video360_advertiser_link_proposal._get_unset_required_fields( - jsonified_request - ) + ).update_custom_metric._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -74862,7 +85000,7 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DisplayVideo360AdvertiserLinkProposal() + return_value = resources.CustomMetric() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -74874,7 +85012,7 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -74884,36 +85022,30 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DisplayVideo360AdvertiserLinkProposal.pb( - return_value - ) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.cancel_display_video360_advertiser_link_proposal(request) + response = client.update_custom_metric(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_cancel_display_video360_advertiser_link_proposal_rest_unset_required_fields(): +def test_update_custom_metric_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.cancel_display_video360_advertiser_link_proposal._get_unset_required_fields( - {} - ) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_cancel_display_video360_advertiser_link_proposal_rest_interceptors( - null_interceptor, -): +def test_update_custom_metric_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -74926,18 +85058,14 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_interceptors( ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_cancel_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "post_update_custom_metric" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_cancel_display_video360_advertiser_link_proposal", + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_metric" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = ( - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest.pb( - analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() - ) + pb_message = analytics_admin.UpdateCustomMetricRequest.pb( + analytics_admin.UpdateCustomMetricRequest() ) transcode.return_value = { "method": "post", @@ -74949,21 +85077,19 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_interceptors( req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - resources.DisplayVideo360AdvertiserLinkProposal.to_json( - resources.DisplayVideo360AdvertiserLinkProposal() - ) + req.return_value._content = resources.CustomMetric.to_json( + resources.CustomMetric() ) - request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + request = analytics_admin.UpdateCustomMetricRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + post.return_value = resources.CustomMetric() - client.cancel_display_video360_advertiser_link_proposal( + client.update_custom_metric( request, metadata=[ ("key", "val"), @@ -74975,9 +85101,8 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_interceptors( post.assert_called_once() -def test_cancel_display_video360_advertiser_link_proposal_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, +def test_update_custom_metric_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateCustomMetricRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -74986,7 +85111,7 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "properties/sample1/displayVideo360AdvertiserLinkProposals/sample2" + "custom_metric": {"name": "properties/sample1/customMetrics/sample2"} } request = request_type(**request_init) @@ -74999,10 +85124,71 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.cancel_display_video360_advertiser_link_proposal(request) + client.update_custom_metric(request) -def test_cancel_display_video360_advertiser_link_proposal_rest_error(): +def test_update_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = { + "custom_metric": {"name": "properties/sample1/customMetrics/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + custom_metric=resources.CustomMetric(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_custom_metric(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{custom_metric.name=properties/*/customMetrics/*}" + % client.transport._host, + args[1], + ) + + +def test_update_custom_metric_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_custom_metric_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -75011,11 +85197,11 @@ def test_cancel_display_video360_advertiser_link_proposal_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateCustomDimensionRequest, + analytics_admin.ListCustomMetricsRequest, dict, ], ) -def test_create_custom_dimension_rest(request_type): +def test_list_custom_metrics_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -75023,119 +85209,32 @@ def test_create_custom_dimension_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "properties/sample1"} - request_init["custom_dimension"] = { - "name": "name_value", - "parameter_name": "parameter_name_value", - "display_name": "display_name_value", - "description": "description_value", - "scope": 1, - "disallow_ads_personalization": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateCustomDimensionRequest.meta.fields[ - "custom_dimension" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["custom_dimension"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["custom_dimension"][field])): - del request_init["custom_dimension"][field][i][subfield] - else: - del request_init["custom_dimension"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension( - name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + return_value = analytics_admin.ListCustomMetricsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) + return_value = analytics_admin.ListCustomMetricsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_custom_dimension(request) + response = client.list_custom_metrics(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) - assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert isinstance(response, pagers.ListCustomMetricsPager) + assert response.next_page_token == "next_page_token_value" -def test_create_custom_dimension_rest_use_cached_wrapped_rpc(): +def test_list_custom_metrics_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -75150,8 +85249,7 @@ def test_create_custom_dimension_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_custom_dimension - in client._transport._wrapped_methods + client._transport.list_custom_metrics in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -75160,24 +85258,24 @@ def test_create_custom_dimension_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_custom_dimension + client._transport.list_custom_metrics ] = mock_rpc request = {} - client.create_custom_dimension(request) + client.list_custom_metrics(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_dimension(request) + client.list_custom_metrics(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_custom_dimension_rest_required_fields( - request_type=analytics_admin.CreateCustomDimensionRequest, +def test_list_custom_metrics_rest_required_fields( + request_type=analytics_admin.ListCustomMetricsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -75193,7 +85291,7 @@ def test_create_custom_dimension_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_dimension._get_unset_required_fields(jsonified_request) + ).list_custom_metrics._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -75202,7 +85300,14 @@ def test_create_custom_dimension_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_dimension._get_unset_required_fields(jsonified_request) + ).list_custom_metrics._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -75216,7 +85321,7 @@ def test_create_custom_dimension_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension() + return_value = analytics_admin.ListCustomMetricsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -75228,48 +85333,47 @@ def test_create_custom_dimension_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) + return_value = analytics_admin.ListCustomMetricsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_custom_dimension(request) + response = client.list_custom_metrics(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_custom_dimension_rest_unset_required_fields(): +def test_list_custom_metrics_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_custom_dimension._get_unset_required_fields({}) + unset_fields = transport.list_custom_metrics._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "customDimension", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_custom_dimension_rest_interceptors(null_interceptor): +def test_list_custom_metrics_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -75282,14 +85386,14 @@ def test_create_custom_dimension_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_custom_dimension" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_custom_metrics" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_dimension" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_metrics" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateCustomDimensionRequest.pb( - analytics_admin.CreateCustomDimensionRequest() + pb_message = analytics_admin.ListCustomMetricsRequest.pb( + analytics_admin.ListCustomMetricsRequest() ) transcode.return_value = { "method": "post", @@ -75301,19 +85405,19 @@ def test_create_custom_dimension_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.CustomDimension.to_json( - resources.CustomDimension() + req.return_value._content = analytics_admin.ListCustomMetricsResponse.to_json( + analytics_admin.ListCustomMetricsResponse() ) - request = analytics_admin.CreateCustomDimensionRequest() + request = analytics_admin.ListCustomMetricsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CustomDimension() + post.return_value = analytics_admin.ListCustomMetricsResponse() - client.create_custom_dimension( + client.list_custom_metrics( request, metadata=[ ("key", "val"), @@ -75325,8 +85429,8 @@ def test_create_custom_dimension_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_custom_dimension_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateCustomDimensionRequest +def test_list_custom_metrics_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListCustomMetricsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -75346,10 +85450,10 @@ def test_create_custom_dimension_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_custom_dimension(request) + client.list_custom_metrics(request) -def test_create_custom_dimension_rest_flattened(): +def test_list_custom_metrics_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -75358,7 +85462,7 @@ def test_create_custom_dimension_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension() + return_value = analytics_admin.ListCustomMetricsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -75366,7 +85470,6 @@ def test_create_custom_dimension_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - custom_dimension=resources.CustomDimension(name="name_value"), ) mock_args.update(sample_request) @@ -75374,176 +85477,137 @@ def test_create_custom_dimension_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) + return_value = analytics_admin.ListCustomMetricsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_custom_dimension(**mock_args) + client.list_custom_metrics(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/customDimensions" - % client.transport._host, + "%s/v1alpha/{parent=properties/*}/customMetrics" % client.transport._host, args[1], ) -def test_create_custom_dimension_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) +def test_list_custom_metrics_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent="parent_value", + ) + + +def test_list_custom_metrics_rest_pager(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token="abc", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token="def", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token="ghi", + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListCustomMetricsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_custom_dimension( - analytics_admin.CreateCustomDimensionRequest(), - parent="parent_value", - custom_dimension=resources.CustomDimension(name="name_value"), - ) + pager = client.list_custom_metrics(request=sample_request) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomMetric) for i in results) -def test_create_custom_dimension_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + pages = list(client.list_custom_metrics(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateCustomDimensionRequest, + analytics_admin.ArchiveCustomMetricRequest, dict, ], ) -def test_update_custom_dimension_rest(request_type): +def test_archive_custom_metric_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "custom_dimension": {"name": "properties/sample1/customDimensions/sample2"} - } - request_init["custom_dimension"] = { - "name": "properties/sample1/customDimensions/sample2", - "parameter_name": "parameter_name_value", - "display_name": "display_name_value", - "description": "description_value", - "scope": 1, - "disallow_ads_personalization": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateCustomDimensionRequest.meta.fields[ - "custom_dimension" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["custom_dimension"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["custom_dimension"][field])): - del request_init["custom_dimension"][field][i][subfield] - else: - del request_init["custom_dimension"][field][subfield] + request_init = {"name": "properties/sample1/customMetrics/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension( - name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_custom_dimension(request) + response = client.archive_custom_metric(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) - assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert response is None -def test_update_custom_dimension_rest_use_cached_wrapped_rpc(): +def test_archive_custom_metric_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -75558,7 +85622,7 @@ def test_update_custom_dimension_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_custom_dimension + client._transport.archive_custom_metric in client._transport._wrapped_methods ) @@ -75568,28 +85632,29 @@ def test_update_custom_dimension_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_custom_dimension + client._transport.archive_custom_metric ] = mock_rpc request = {} - client.update_custom_dimension(request) + client.archive_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_custom_dimension(request) + client.archive_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_custom_dimension_rest_required_fields( - request_type=analytics_admin.UpdateCustomDimensionRequest, +def test_archive_custom_metric_rest_required_fields( + request_type=analytics_admin.ArchiveCustomMetricRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -75600,19 +85665,21 @@ def test_update_custom_dimension_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_custom_dimension._get_unset_required_fields(jsonified_request) + ).archive_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_custom_dimension._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).archive_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -75621,7 +85688,7 @@ def test_update_custom_dimension_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -75633,7 +85700,7 @@ def test_update_custom_dimension_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -75641,32 +85708,29 @@ def test_update_custom_dimension_rest_required_fields( response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_custom_dimension(request) + response = client.archive_custom_metric(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_custom_dimension_rest_unset_required_fields(): +def test_archive_custom_metric_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_custom_dimension._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + unset_fields = transport.archive_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_custom_dimension_rest_interceptors(null_interceptor): +def test_archive_custom_metric_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -75679,14 +85743,11 @@ def test_update_custom_dimension_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_custom_dimension" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_dimension" + transports.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_metric" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateCustomDimensionRequest.pb( - analytics_admin.UpdateCustomDimensionRequest() + pb_message = analytics_admin.ArchiveCustomMetricRequest.pb( + analytics_admin.ArchiveCustomMetricRequest() ) transcode.return_value = { "method": "post", @@ -75698,19 +85759,15 @@ def test_update_custom_dimension_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.CustomDimension.to_json( - resources.CustomDimension() - ) - request = analytics_admin.UpdateCustomDimensionRequest() + request = analytics_admin.ArchiveCustomMetricRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CustomDimension() - client.update_custom_dimension( + client.archive_custom_metric( request, metadata=[ ("key", "val"), @@ -75719,11 +85776,10 @@ def test_update_custom_dimension_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_custom_dimension_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateCustomDimensionRequest +def test_archive_custom_metric_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ArchiveCustomMetricRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -75731,9 +85787,7 @@ def test_update_custom_dimension_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "custom_dimension": {"name": "properties/sample1/customDimensions/sample2"} - } + request_init = {"name": "properties/sample1/customMetrics/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -75745,10 +85799,10 @@ def test_update_custom_dimension_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_custom_dimension(request) + client.archive_custom_metric(request) -def test_update_custom_dimension_rest_flattened(): +def test_archive_custom_metric_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -75757,43 +85811,38 @@ def test_update_custom_dimension_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "custom_dimension": {"name": "properties/sample1/customDimensions/sample2"} - } + sample_request = {"name": "properties/sample1/customMetrics/sample2"} # get truthy value for each flattened field mock_args = dict( - custom_dimension=resources.CustomDimension(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_custom_dimension(**mock_args) + client.archive_custom_metric(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{custom_dimension.name=properties/*/customDimensions/*}" + "%s/v1alpha/{name=properties/*/customMetrics/*}:archive" % client.transport._host, args[1], ) -def test_update_custom_dimension_rest_flattened_error(transport: str = "rest"): +def test_archive_custom_metric_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -75802,14 +85851,13 @@ def test_update_custom_dimension_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_custom_dimension( - analytics_admin.UpdateCustomDimensionRequest(), - custom_dimension=resources.CustomDimension(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name="name_value", ) -def test_update_custom_dimension_rest_error(): +def test_archive_custom_metric_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -75818,44 +85866,60 @@ def test_update_custom_dimension_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListCustomDimensionsRequest, + analytics_admin.GetCustomMetricRequest, dict, ], ) -def test_list_custom_dimensions_rest(request_type): +def test_get_custom_metric_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/customMetrics/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListCustomDimensionsResponse( - next_page_token="next_page_token_value", + return_value = resources.CustomMetric( + name="name_value", + parameter_name="parameter_name_value", + display_name="display_name_value", + description="description_value", + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_custom_dimensions(request) + response = client.get_custom_metric(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomDimensionsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.CustomMetric) + assert response.name == "name_value" + assert response.parameter_name == "parameter_name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [ + resources.CustomMetric.RestrictedMetricType.COST_DATA + ] -def test_list_custom_dimensions_rest_use_cached_wrapped_rpc(): +def test_get_custom_metric_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -75869,10 +85933,7 @@ def test_list_custom_dimensions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_custom_dimensions - in client._transport._wrapped_methods - ) + assert client._transport.get_custom_metric in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -75880,29 +85941,29 @@ def test_list_custom_dimensions_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_custom_dimensions + client._transport.get_custom_metric ] = mock_rpc request = {} - client.list_custom_dimensions(request) + client.get_custom_metric(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_custom_dimensions(request) + client.get_custom_metric(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_custom_dimensions_rest_required_fields( - request_type=analytics_admin.ListCustomDimensionsRequest, +def test_get_custom_metric_rest_required_fields( + request_type=analytics_admin.GetCustomMetricRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -75913,28 +85974,21 @@ def test_list_custom_dimensions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_custom_dimensions._get_unset_required_fields(jsonified_request) + ).get_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_custom_dimensions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).get_custom_metric._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -75943,7 +85997,7 @@ def test_list_custom_dimensions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListCustomDimensionsResponse() + return_value = resources.CustomMetric() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -75964,38 +86018,30 @@ def test_list_custom_dimensions_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_custom_dimensions(request) + response = client.get_custom_metric(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_custom_dimensions_rest_unset_required_fields(): +def test_get_custom_metric_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_custom_dimensions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_custom_dimensions_rest_interceptors(null_interceptor): +def test_get_custom_metric_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -76008,14 +86054,14 @@ def test_list_custom_dimensions_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_custom_dimensions" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_custom_metric" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_dimensions" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_metric" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListCustomDimensionsRequest.pb( - analytics_admin.ListCustomDimensionsRequest() + pb_message = analytics_admin.GetCustomMetricRequest.pb( + analytics_admin.GetCustomMetricRequest() ) transcode.return_value = { "method": "post", @@ -76027,21 +86073,19 @@ def test_list_custom_dimensions_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListCustomDimensionsResponse.to_json( - analytics_admin.ListCustomDimensionsResponse() - ) + req.return_value._content = resources.CustomMetric.to_json( + resources.CustomMetric() ) - request = analytics_admin.ListCustomDimensionsRequest() + request = analytics_admin.GetCustomMetricRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListCustomDimensionsResponse() + post.return_value = resources.CustomMetric() - client.list_custom_dimensions( + client.get_custom_metric( request, metadata=[ ("key", "val"), @@ -76053,8 +86097,8 @@ def test_list_custom_dimensions_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_custom_dimensions_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListCustomDimensionsRequest +def test_get_custom_metric_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetCustomMetricRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -76062,7 +86106,7 @@ def test_list_custom_dimensions_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/customMetrics/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -76074,10 +86118,10 @@ def test_list_custom_dimensions_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_custom_dimensions(request) + client.get_custom_metric(request) -def test_list_custom_dimensions_rest_flattened(): +def test_get_custom_metric_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -76086,14 +86130,14 @@ def test_list_custom_dimensions_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListCustomDimensionsResponse() + return_value = resources.CustomMetric() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"name": "properties/sample1/customMetrics/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -76101,25 +86145,24 @@ def test_list_custom_dimensions_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + return_value = resources.CustomMetric.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_custom_dimensions(**mock_args) + client.get_custom_metric(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/customDimensions" - % client.transport._host, + "%s/v1alpha/{name=properties/*/customMetrics/*}" % client.transport._host, args[1], ) -def test_list_custom_dimensions_rest_flattened_error(transport: str = "rest"): +def test_get_custom_metric_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -76128,111 +86171,66 @@ def test_list_custom_dimensions_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_custom_dimensions( - analytics_admin.ListCustomDimensionsRequest(), - parent="parent_value", + client.get_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name="name_value", ) -def test_list_custom_dimensions_rest_pager(transport: str = "rest"): +def test_get_custom_metric_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - resources.CustomDimension(), - ], - next_page_token="abc", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[], - next_page_token="def", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCustomDimensionsResponse( - custom_dimensions=[ - resources.CustomDimension(), - resources.CustomDimension(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListCustomDimensionsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_custom_dimensions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CustomDimension) for i in results) - - pages = list(client.list_custom_dimensions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.ArchiveCustomDimensionRequest, + analytics_admin.GetDataRetentionSettingsRequest, dict, ], ) -def test_archive_custom_dimension_rest(request_type): +def test_get_data_retention_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customDimensions/sample2"} + request_init = {"name": "properties/sample1/dataRetentionSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DataRetentionSettings( + name="name_value", + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.archive_custom_dimension(request) + response = client.get_data_retention_settings(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == "name_value" + assert ( + response.event_data_retention + == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + ) + assert response.reset_user_data_on_new_activity is True -def test_archive_custom_dimension_rest_use_cached_wrapped_rpc(): +def test_get_data_retention_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -76247,7 +86245,7 @@ def test_archive_custom_dimension_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.archive_custom_dimension + client._transport.get_data_retention_settings in client._transport._wrapped_methods ) @@ -76257,24 +86255,24 @@ def test_archive_custom_dimension_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.archive_custom_dimension + client._transport.get_data_retention_settings ] = mock_rpc request = {} - client.archive_custom_dimension(request) + client.get_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.archive_custom_dimension(request) + client.get_data_retention_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_archive_custom_dimension_rest_required_fields( - request_type=analytics_admin.ArchiveCustomDimensionRequest, +def test_get_data_retention_settings_rest_required_fields( + request_type=analytics_admin.GetDataRetentionSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -76290,7 +86288,7 @@ def test_archive_custom_dimension_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).archive_custom_dimension._get_unset_required_fields(jsonified_request) + ).get_data_retention_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -76299,7 +86297,7 @@ def test_archive_custom_dimension_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).archive_custom_dimension._get_unset_required_fields(jsonified_request) + ).get_data_retention_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -76313,7 +86311,7 @@ def test_archive_custom_dimension_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DataRetentionSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -76325,37 +86323,39 @@ def test_archive_custom_dimension_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.archive_custom_dimension(request) + response = client.get_data_retention_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_archive_custom_dimension_rest_unset_required_fields(): +def test_get_data_retention_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.archive_custom_dimension._get_unset_required_fields({}) + unset_fields = transport.get_data_retention_settings._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_archive_custom_dimension_rest_interceptors(null_interceptor): +def test_get_data_retention_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -76368,11 +86368,16 @@ def test_archive_custom_dimension_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_dimension" + transports.AnalyticsAdminServiceRestInterceptor, + "post_get_data_retention_settings", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_get_data_retention_settings", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.ArchiveCustomDimensionRequest.pb( - analytics_admin.ArchiveCustomDimensionRequest() + post.assert_not_called() + pb_message = analytics_admin.GetDataRetentionSettingsRequest.pb( + analytics_admin.GetDataRetentionSettingsRequest() ) transcode.return_value = { "method": "post", @@ -76384,15 +86389,19 @@ def test_archive_custom_dimension_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.DataRetentionSettings.to_json( + resources.DataRetentionSettings() + ) - request = analytics_admin.ArchiveCustomDimensionRequest() + request = analytics_admin.GetDataRetentionSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.DataRetentionSettings() - client.archive_custom_dimension( + client.get_data_retention_settings( request, metadata=[ ("key", "val"), @@ -76401,10 +86410,12 @@ def test_archive_custom_dimension_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_archive_custom_dimension_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ArchiveCustomDimensionRequest +def test_get_data_retention_settings_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.GetDataRetentionSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -76412,7 +86423,7 @@ def test_archive_custom_dimension_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customDimensions/sample2"} + request_init = {"name": "properties/sample1/dataRetentionSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -76424,10 +86435,10 @@ def test_archive_custom_dimension_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.archive_custom_dimension(request) + client.get_data_retention_settings(request) -def test_archive_custom_dimension_rest_flattened(): +def test_get_data_retention_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -76436,10 +86447,10 @@ def test_archive_custom_dimension_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.DataRetentionSettings() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/customDimensions/sample2"} + sample_request = {"name": "properties/sample1/dataRetentionSettings"} # get truthy value for each flattened field mock_args = dict( @@ -76450,24 +86461,26 @@ def test_archive_custom_dimension_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.archive_custom_dimension(**mock_args) + client.get_data_retention_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/customDimensions/*}:archive" + "%s/v1alpha/{name=properties/*/dataRetentionSettings}" % client.transport._host, args[1], ) -def test_archive_custom_dimension_rest_flattened_error(transport: str = "rest"): +def test_get_data_retention_settings_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -76476,13 +86489,13 @@ def test_archive_custom_dimension_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.archive_custom_dimension( - analytics_admin.ArchiveCustomDimensionRequest(), + client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), name="name_value", ) -def test_archive_custom_dimension_rest_error(): +def test_get_data_retention_settings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -76491,54 +86504,129 @@ def test_archive_custom_dimension_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetCustomDimensionRequest, + analytics_admin.UpdateDataRetentionSettingsRequest, dict, ], ) -def test_get_custom_dimension_rest(request_type): +def test_update_data_retention_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customDimensions/sample2"} + request_init = { + "data_retention_settings": {"name": "properties/sample1/dataRetentionSettings"} + } + request_init["data_retention_settings"] = { + "name": "properties/sample1/dataRetentionSettings", + "event_data_retention": 1, + "reset_user_data_on_new_activity": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateDataRetentionSettingsRequest.meta.fields[ + "data_retention_settings" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "data_retention_settings" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_retention_settings"][field])): + del request_init["data_retention_settings"][field][i][subfield] + else: + del request_init["data_retention_settings"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension( + return_value = resources.DataRetentionSettings( name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - scope=resources.CustomDimension.DimensionScope.EVENT, - disallow_ads_personalization=True, + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) + return_value = resources.DataRetentionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_custom_dimension(request) + response = client.update_data_retention_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomDimension) + assert isinstance(response, resources.DataRetentionSettings) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.scope == resources.CustomDimension.DimensionScope.EVENT - assert response.disallow_ads_personalization is True + assert ( + response.event_data_retention + == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + ) + assert response.reset_user_data_on_new_activity is True -def test_get_custom_dimension_rest_use_cached_wrapped_rpc(): +def test_update_data_retention_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -76553,7 +86641,8 @@ def test_get_custom_dimension_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_custom_dimension in client._transport._wrapped_methods + client._transport.update_data_retention_settings + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -76562,29 +86651,28 @@ def test_get_custom_dimension_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_custom_dimension + client._transport.update_data_retention_settings ] = mock_rpc request = {} - client.get_custom_dimension(request) + client.update_data_retention_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_custom_dimension(request) + client.update_data_retention_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_custom_dimension_rest_required_fields( - request_type=analytics_admin.GetCustomDimensionRequest, +def test_update_data_retention_settings_rest_required_fields( + request_type=analytics_admin.UpdateDataRetentionSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -76595,21 +86683,19 @@ def test_get_custom_dimension_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_custom_dimension._get_unset_required_fields(jsonified_request) + ).update_data_retention_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_custom_dimension._get_unset_required_fields(jsonified_request) + ).update_data_retention_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -76618,7 +86704,7 @@ def test_get_custom_dimension_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension() + return_value = resources.DataRetentionSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -76630,39 +86716,50 @@ def test_get_custom_dimension_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) + return_value = resources.DataRetentionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_custom_dimension(request) + response = client.update_data_retention_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_custom_dimension_rest_unset_required_fields(): +def test_update_data_retention_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_custom_dimension._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_data_retention_settings._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "dataRetentionSettings", + "updateMask", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_custom_dimension_rest_interceptors(null_interceptor): +def test_update_data_retention_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -76675,14 +86772,16 @@ def test_get_custom_dimension_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_custom_dimension" + transports.AnalyticsAdminServiceRestInterceptor, + "post_update_data_retention_settings", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_dimension" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_update_data_retention_settings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetCustomDimensionRequest.pb( - analytics_admin.GetCustomDimensionRequest() + pb_message = analytics_admin.UpdateDataRetentionSettingsRequest.pb( + analytics_admin.UpdateDataRetentionSettingsRequest() ) transcode.return_value = { "method": "post", @@ -76694,19 +86793,19 @@ def test_get_custom_dimension_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.CustomDimension.to_json( - resources.CustomDimension() + req.return_value._content = resources.DataRetentionSettings.to_json( + resources.DataRetentionSettings() ) - request = analytics_admin.GetCustomDimensionRequest() + request = analytics_admin.UpdateDataRetentionSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CustomDimension() + post.return_value = resources.DataRetentionSettings() - client.get_custom_dimension( + client.update_data_retention_settings( request, metadata=[ ("key", "val"), @@ -76718,8 +86817,9 @@ def test_get_custom_dimension_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_custom_dimension_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetCustomDimensionRequest +def test_update_data_retention_settings_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.UpdateDataRetentionSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -76727,7 +86827,9 @@ def test_get_custom_dimension_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customDimensions/sample2"} + request_init = { + "data_retention_settings": {"name": "properties/sample1/dataRetentionSettings"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -76739,10 +86841,10 @@ def test_get_custom_dimension_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_custom_dimension(request) + client.update_data_retention_settings(request) -def test_get_custom_dimension_rest_flattened(): +def test_update_data_retention_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -76751,14 +86853,19 @@ def test_get_custom_dimension_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomDimension() + return_value = resources.DataRetentionSettings() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/customDimensions/sample2"} + sample_request = { + "data_retention_settings": { + "name": "properties/sample1/dataRetentionSettings" + } + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + data_retention_settings=resources.DataRetentionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -76766,25 +86873,25 @@ def test_get_custom_dimension_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomDimension.pb(return_value) + return_value = resources.DataRetentionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_custom_dimension(**mock_args) + client.update_data_retention_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/customDimensions/*}" + "%s/v1alpha/{data_retention_settings.name=properties/*/dataRetentionSettings}" % client.transport._host, args[1], ) -def test_get_custom_dimension_rest_flattened_error(transport: str = "rest"): +def test_update_data_retention_settings_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -76793,13 +86900,14 @@ def test_get_custom_dimension_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_custom_dimension( - analytics_admin.GetCustomDimensionRequest(), - name="name_value", + client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_custom_dimension_rest_error(): +def test_update_data_retention_settings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -76808,11 +86916,11 @@ def test_get_custom_dimension_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateCustomMetricRequest, + analytics_admin.CreateDataStreamRequest, dict, ], ) -def test_create_custom_metric_rest(request_type): +def test_create_data_stream_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -76820,21 +86928,32 @@ def test_create_custom_metric_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "properties/sample1"} - request_init["custom_metric"] = { + request_init["data_stream"] = { + "web_stream_data": { + "measurement_id": "measurement_id_value", + "firebase_app_id": "firebase_app_id_value", + "default_uri": "default_uri_value", + }, + "android_app_stream_data": { + "firebase_app_id": "firebase_app_id_value", + "package_name": "package_name_value", + }, + "ios_app_stream_data": { + "firebase_app_id": "firebase_app_id_value", + "bundle_id": "bundle_id_value", + }, "name": "name_value", - "parameter_name": "parameter_name_value", + "type_": 1, "display_name": "display_name_value", - "description": "description_value", - "measurement_unit": 1, - "scope": 1, - "restricted_metric_type": [1], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateCustomMetricRequest.meta.fields["custom_metric"] + test_field = analytics_admin.CreateDataStreamRequest.meta.fields["data_stream"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -76862,7 +86981,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["custom_metric"].items(): # pragma: NO COVER + for field, value in request_init["data_stream"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -76892,52 +87011,40 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["custom_metric"][field])): - del request_init["custom_metric"][field][i][subfield] + for i in range(0, len(request_init["data_stream"][field])): + del request_init["data_stream"][field][i][subfield] else: - del request_init["custom_metric"][field][subfield] + del request_init["data_stream"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric( + return_value = resources.DataStream( name="name_value", - parameter_name="parameter_name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_custom_metric(request) + response = client.create_data_stream(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.DataStream) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] -def test_create_custom_metric_rest_use_cached_wrapped_rpc(): +def test_create_data_stream_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -76952,7 +87059,7 @@ def test_create_custom_metric_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_custom_metric in client._transport._wrapped_methods + client._transport.create_data_stream in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -76961,24 +87068,24 @@ def test_create_custom_metric_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_custom_metric + client._transport.create_data_stream ] = mock_rpc request = {} - client.create_custom_metric(request) + client.create_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_custom_metric(request) + client.create_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_custom_metric_rest_required_fields( - request_type=analytics_admin.CreateCustomMetricRequest, +def test_create_data_stream_rest_required_fields( + request_type=analytics_admin.CreateDataStreamRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -76994,7 +87101,7 @@ def test_create_custom_metric_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_metric._get_unset_required_fields(jsonified_request) + ).create_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -77003,7 +87110,7 @@ def test_create_custom_metric_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_custom_metric._get_unset_required_fields(jsonified_request) + ).create_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -77017,7 +87124,7 @@ def test_create_custom_metric_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric() + return_value = resources.DataStream() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -77039,38 +87146,38 @@ def test_create_custom_metric_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_custom_metric(request) + response = client.create_data_stream(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_custom_metric_rest_unset_required_fields(): +def test_create_data_stream_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_custom_metric._get_unset_required_fields({}) + unset_fields = transport.create_data_stream._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "parent", - "customMetric", + "dataStream", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_custom_metric_rest_interceptors(null_interceptor): +def test_create_data_stream_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -77083,14 +87190,14 @@ def test_create_custom_metric_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_custom_metric" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_data_stream" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_metric" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_data_stream" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateCustomMetricRequest.pb( - analytics_admin.CreateCustomMetricRequest() + pb_message = analytics_admin.CreateDataStreamRequest.pb( + analytics_admin.CreateDataStreamRequest() ) transcode.return_value = { "method": "post", @@ -77102,19 +87209,17 @@ def test_create_custom_metric_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.CustomMetric.to_json( - resources.CustomMetric() - ) + req.return_value._content = resources.DataStream.to_json(resources.DataStream()) - request = analytics_admin.CreateCustomMetricRequest() + request = analytics_admin.CreateDataStreamRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CustomMetric() + post.return_value = resources.DataStream() - client.create_custom_metric( + client.create_data_stream( request, metadata=[ ("key", "val"), @@ -77126,8 +87231,8 @@ def test_create_custom_metric_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_custom_metric_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateCustomMetricRequest +def test_create_data_stream_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateDataStreamRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -77147,10 +87252,10 @@ def test_create_custom_metric_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_custom_metric(request) + client.create_data_stream(request) -def test_create_custom_metric_rest_flattened(): +def test_create_data_stream_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -77159,7 +87264,7 @@ def test_create_custom_metric_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric() + return_value = resources.DataStream() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -77167,7 +87272,11 @@ def test_create_custom_metric_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - custom_metric=resources.CustomMetric(name="name_value"), + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), ) mock_args.update(sample_request) @@ -77175,24 +87284,24 @@ def test_create_custom_metric_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_custom_metric(**mock_args) + client.create_data_stream(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/customMetrics" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/dataStreams" % client.transport._host, args[1], ) -def test_create_custom_metric_rest_flattened_error(transport: str = "rest"): +def test_create_data_stream_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -77201,14 +87310,18 @@ def test_create_custom_metric_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_custom_metric( - analytics_admin.CreateCustomMetricRequest(), + client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), parent="parent_value", - custom_metric=resources.CustomMetric(name="name_value"), + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), ) -def test_create_custom_metric_rest_error(): +def test_create_data_stream_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -77216,139 +87329,40 @@ def test_create_custom_metric_rest_error(): @pytest.mark.parametrize( "request_type", - [ - analytics_admin.UpdateCustomMetricRequest, - dict, - ], -) -def test_update_custom_metric_rest(request_type): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = { - "custom_metric": {"name": "properties/sample1/customMetrics/sample2"} - } - request_init["custom_metric"] = { - "name": "properties/sample1/customMetrics/sample2", - "parameter_name": "parameter_name_value", - "display_name": "display_name_value", - "description": "description_value", - "measurement_unit": 1, - "scope": 1, - "restricted_metric_type": [1], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateCustomMetricRequest.meta.fields["custom_metric"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["custom_metric"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["custom_metric"][field])): - del request_init["custom_metric"][field][i][subfield] - else: - del request_init["custom_metric"][field][subfield] + [ + analytics_admin.DeleteDataStreamRequest, + dict, + ], +) +def test_delete_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric( - name="name_value", - parameter_name="parameter_name_value", - display_name="display_name_value", - description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_custom_metric(request) + response = client.delete_data_stream(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) - assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] + assert response is None -def test_update_custom_metric_rest_use_cached_wrapped_rpc(): +def test_delete_data_stream_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -77363,7 +87377,7 @@ def test_update_custom_metric_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_custom_metric in client._transport._wrapped_methods + client._transport.delete_data_stream in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -77372,28 +87386,29 @@ def test_update_custom_metric_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_custom_metric + client._transport.delete_data_stream ] = mock_rpc request = {} - client.update_custom_metric(request) + client.delete_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_custom_metric(request) + client.delete_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_custom_metric_rest_required_fields( - request_type=analytics_admin.UpdateCustomMetricRequest, +def test_delete_data_stream_rest_required_fields( + request_type=analytics_admin.DeleteDataStreamRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -77404,19 +87419,21 @@ def test_update_custom_metric_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_custom_metric._get_unset_required_fields(jsonified_request) + ).delete_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_custom_metric._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).delete_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -77425,7 +87442,7 @@ def test_update_custom_metric_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -77437,40 +87454,36 @@ def test_update_custom_metric_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_custom_metric(request) + response = client.delete_data_stream(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_custom_metric_rest_unset_required_fields(): +def test_delete_data_stream_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_custom_metric._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + unset_fields = transport.delete_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_custom_metric_rest_interceptors(null_interceptor): +def test_delete_data_stream_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -77483,14 +87496,11 @@ def test_update_custom_metric_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_custom_metric" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_metric" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_data_stream" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateCustomMetricRequest.pb( - analytics_admin.UpdateCustomMetricRequest() + pb_message = analytics_admin.DeleteDataStreamRequest.pb( + analytics_admin.DeleteDataStreamRequest() ) transcode.return_value = { "method": "post", @@ -77502,19 +87512,15 @@ def test_update_custom_metric_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.CustomMetric.to_json( - resources.CustomMetric() - ) - request = analytics_admin.UpdateCustomMetricRequest() + request = analytics_admin.DeleteDataStreamRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CustomMetric() - client.update_custom_metric( + client.delete_data_stream( request, metadata=[ ("key", "val"), @@ -77523,11 +87529,10 @@ def test_update_custom_metric_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_custom_metric_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateCustomMetricRequest +def test_delete_data_stream_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteDataStreamRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -77535,9 +87540,7 @@ def test_update_custom_metric_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "custom_metric": {"name": "properties/sample1/customMetrics/sample2"} - } + request_init = {"name": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -77549,10 +87552,10 @@ def test_update_custom_metric_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_custom_metric(request) + client.delete_data_stream(request) -def test_update_custom_metric_rest_flattened(): +def test_delete_data_stream_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -77561,43 +87564,37 @@ def test_update_custom_metric_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "custom_metric": {"name": "properties/sample1/customMetrics/sample2"} - } + sample_request = {"name": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( - custom_metric=resources.CustomMetric(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_custom_metric(**mock_args) + client.delete_data_stream(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{custom_metric.name=properties/*/customMetrics/*}" - % client.transport._host, + "%s/v1alpha/{name=properties/*/dataStreams/*}" % client.transport._host, args[1], ) -def test_update_custom_metric_rest_flattened_error(transport: str = "rest"): +def test_delete_data_stream_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -77606,14 +87603,13 @@ def test_update_custom_metric_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_custom_metric( - analytics_admin.UpdateCustomMetricRequest(), - custom_metric=resources.CustomMetric(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name="name_value", ) -def test_update_custom_metric_rest_error(): +def test_delete_data_stream_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -77622,44 +87618,135 @@ def test_update_custom_metric_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListCustomMetricsRequest, + analytics_admin.UpdateDataStreamRequest, dict, ], ) -def test_list_custom_metrics_rest(request_type): +def test_update_data_stream_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"data_stream": {"name": "properties/sample1/dataStreams/sample2"}} + request_init["data_stream"] = { + "web_stream_data": { + "measurement_id": "measurement_id_value", + "firebase_app_id": "firebase_app_id_value", + "default_uri": "default_uri_value", + }, + "android_app_stream_data": { + "firebase_app_id": "firebase_app_id_value", + "package_name": "package_name_value", + }, + "ios_app_stream_data": { + "firebase_app_id": "firebase_app_id_value", + "bundle_id": "bundle_id_value", + }, + "name": "properties/sample1/dataStreams/sample2", + "type_": 1, + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateDataStreamRequest.meta.fields["data_stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_stream"][field])): + del request_init["data_stream"][field][i][subfield] + else: + del request_init["data_stream"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListCustomMetricsResponse( - next_page_token="next_page_token_value", + return_value = resources.DataStream( + name="name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name="display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListCustomMetricsResponse.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_custom_metrics(request) + response = client.update_data_stream(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCustomMetricsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.DataStream) + assert response.name == "name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == "display_name_value" -def test_list_custom_metrics_rest_use_cached_wrapped_rpc(): +def test_update_data_stream_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -77674,7 +87761,7 @@ def test_list_custom_metrics_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_custom_metrics in client._transport._wrapped_methods + client._transport.update_data_stream in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -77683,29 +87770,28 @@ def test_list_custom_metrics_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_custom_metrics + client._transport.update_data_stream ] = mock_rpc request = {} - client.list_custom_metrics(request) + client.update_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_custom_metrics(request) + client.update_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_custom_metrics_rest_required_fields( - request_type=analytics_admin.ListCustomMetricsRequest, +def test_update_data_stream_rest_required_fields( + request_type=analytics_admin.UpdateDataStreamRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -77716,28 +87802,19 @@ def test_list_custom_metrics_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_custom_metrics._get_unset_required_fields(jsonified_request) + ).update_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_custom_metrics._get_unset_required_fields(jsonified_request) + ).update_data_stream._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -77746,7 +87823,7 @@ def test_list_custom_metrics_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListCustomMetricsResponse() + return_value = resources.DataStream() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -77758,47 +87835,40 @@ def test_list_custom_metrics_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListCustomMetricsResponse.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_custom_metrics(request) + response = client.update_data_stream(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_custom_metrics_rest_unset_required_fields(): +def test_update_data_stream_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_custom_metrics._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.update_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_custom_metrics_rest_interceptors(null_interceptor): +def test_update_data_stream_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -77811,14 +87881,14 @@ def test_list_custom_metrics_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_custom_metrics" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_data_stream" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_metrics" + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_stream" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListCustomMetricsRequest.pb( - analytics_admin.ListCustomMetricsRequest() + pb_message = analytics_admin.UpdateDataStreamRequest.pb( + analytics_admin.UpdateDataStreamRequest() ) transcode.return_value = { "method": "post", @@ -77830,19 +87900,17 @@ def test_list_custom_metrics_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListCustomMetricsResponse.to_json( - analytics_admin.ListCustomMetricsResponse() - ) + req.return_value._content = resources.DataStream.to_json(resources.DataStream()) - request = analytics_admin.ListCustomMetricsRequest() + request = analytics_admin.UpdateDataStreamRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListCustomMetricsResponse() + post.return_value = resources.DataStream() - client.list_custom_metrics( + client.update_data_stream( request, metadata=[ ("key", "val"), @@ -77854,8 +87922,8 @@ def test_list_custom_metrics_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_custom_metrics_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListCustomMetricsRequest +def test_update_data_stream_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateDataStreamRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -77863,7 +87931,7 @@ def test_list_custom_metrics_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"data_stream": {"name": "properties/sample1/dataStreams/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -77875,10 +87943,10 @@ def test_list_custom_metrics_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_custom_metrics(request) + client.update_data_stream(request) -def test_list_custom_metrics_rest_flattened(): +def test_update_data_stream_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -77887,14 +87955,21 @@ def test_list_custom_metrics_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListCustomMetricsResponse() + return_value = resources.DataStream() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = { + "data_stream": {"name": "properties/sample1/dataStreams/sample2"} + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -77902,24 +87977,25 @@ def test_list_custom_metrics_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListCustomMetricsResponse.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_custom_metrics(**mock_args) + client.update_data_stream(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/customMetrics" % client.transport._host, + "%s/v1alpha/{data_stream.name=properties/*/dataStreams/*}" + % client.transport._host, args[1], ) -def test_list_custom_metrics_rest_flattened_error(transport: str = "rest"): +def test_update_data_stream_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -77928,111 +88004,64 @@ def test_list_custom_metrics_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_custom_metrics( - analytics_admin.ListCustomMetricsRequest(), - parent="parent_value", + client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream( + web_stream_data=resources.DataStream.WebStreamData( + measurement_id="measurement_id_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_custom_metrics_rest_pager(transport: str = "rest"): +def test_update_data_stream_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), - resources.CustomMetric(), - ], - next_page_token="abc", - ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[], - next_page_token="def", - ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - ], - next_page_token="ghi", - ), - analytics_admin.ListCustomMetricsResponse( - custom_metrics=[ - resources.CustomMetric(), - resources.CustomMetric(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListCustomMetricsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_custom_metrics(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CustomMetric) for i in results) - - pages = list(client.list_custom_metrics(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.ArchiveCustomMetricRequest, + analytics_admin.ListDataStreamsRequest, dict, ], ) -def test_archive_custom_metric_rest(request_type): +def test_list_data_streams_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customMetrics/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListDataStreamsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.archive_custom_metric(request) + response = client.list_data_streams(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListDataStreamsPager) + assert response.next_page_token == "next_page_token_value" -def test_archive_custom_metric_rest_use_cached_wrapped_rpc(): +def test_list_data_streams_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -78046,10 +88075,7 @@ def test_archive_custom_metric_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.archive_custom_metric - in client._transport._wrapped_methods - ) + assert client._transport.list_data_streams in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -78057,29 +88083,29 @@ def test_archive_custom_metric_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.archive_custom_metric + client._transport.list_data_streams ] = mock_rpc request = {} - client.archive_custom_metric(request) + client.list_data_streams(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.archive_custom_metric(request) + client.list_data_streams(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_archive_custom_metric_rest_required_fields( - request_type=analytics_admin.ArchiveCustomMetricRequest, +def test_list_data_streams_rest_required_fields( + request_type=analytics_admin.ListDataStreamsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -78090,21 +88116,28 @@ def test_archive_custom_metric_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).archive_custom_metric._get_unset_required_fields(jsonified_request) + ).list_data_streams._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).archive_custom_metric._get_unset_required_fields(jsonified_request) + ).list_data_streams._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -78113,7 +88146,7 @@ def test_archive_custom_metric_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListDataStreamsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -78125,37 +88158,47 @@ def test_archive_custom_metric_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.archive_custom_metric(request) + response = client.list_data_streams(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_archive_custom_metric_rest_unset_required_fields(): +def test_list_data_streams_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.archive_custom_metric._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - + unset_fields = transport.list_data_streams._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_archive_custom_metric_rest_interceptors(null_interceptor): +def test_list_data_streams_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -78168,11 +88211,14 @@ def test_archive_custom_metric_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_metric" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_data_streams" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_data_streams" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.ArchiveCustomMetricRequest.pb( - analytics_admin.ArchiveCustomMetricRequest() + post.assert_not_called() + pb_message = analytics_admin.ListDataStreamsRequest.pb( + analytics_admin.ListDataStreamsRequest() ) transcode.return_value = { "method": "post", @@ -78184,15 +88230,19 @@ def test_archive_custom_metric_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = analytics_admin.ListDataStreamsResponse.to_json( + analytics_admin.ListDataStreamsResponse() + ) - request = analytics_admin.ArchiveCustomMetricRequest() + request = analytics_admin.ListDataStreamsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = analytics_admin.ListDataStreamsResponse() - client.archive_custom_metric( + client.list_data_streams( request, metadata=[ ("key", "val"), @@ -78201,10 +88251,11 @@ def test_archive_custom_metric_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_archive_custom_metric_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ArchiveCustomMetricRequest +def test_list_data_streams_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListDataStreamsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -78212,7 +88263,7 @@ def test_archive_custom_metric_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customMetrics/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -78224,10 +88275,10 @@ def test_archive_custom_metric_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.archive_custom_metric(request) + client.list_data_streams(request) -def test_archive_custom_metric_rest_flattened(): +def test_list_data_streams_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -78236,38 +88287,39 @@ def test_archive_custom_metric_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListDataStreamsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/customMetrics/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.archive_custom_metric(**mock_args) + client.list_data_streams(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/customMetrics/*}:archive" - % client.transport._host, + "%s/v1alpha/{parent=properties/*}/dataStreams" % client.transport._host, args[1], ) -def test_archive_custom_metric_rest_flattened_error(transport: str = "rest"): +def test_list_data_streams_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -78276,75 +88328,120 @@ def test_archive_custom_metric_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.archive_custom_metric( - analytics_admin.ArchiveCustomMetricRequest(), - name="name_value", + client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent="parent_value", ) -def test_archive_custom_metric_rest_error(): +def test_list_data_streams_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token="abc", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token="def", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token="ghi", + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListDataStreamsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_data_streams(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DataStream) for i in results) + + pages = list(client.list_data_streams(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetCustomMetricRequest, + analytics_admin.GetDataStreamRequest, dict, ], ) -def test_get_custom_metric_rest(request_type): +def test_get_data_stream_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customMetrics/sample2"} + request_init = {"name": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric( + return_value = resources.DataStream( name="name_value", - parameter_name="parameter_name_value", + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", - description="description_value", - measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, - scope=resources.CustomMetric.MetricScope.EVENT, - restricted_metric_type=[ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_custom_metric(request) + response = client.get_data_stream(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CustomMetric) + assert isinstance(response, resources.DataStream) assert response.name == "name_value" - assert response.parameter_name == "parameter_name_value" + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD - assert response.scope == resources.CustomMetric.MetricScope.EVENT - assert response.restricted_metric_type == [ - resources.CustomMetric.RestrictedMetricType.COST_DATA - ] -def test_get_custom_metric_rest_use_cached_wrapped_rpc(): +def test_get_data_stream_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -78358,32 +88455,30 @@ def test_get_custom_metric_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_custom_metric in client._transport._wrapped_methods + assert client._transport.get_data_stream in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_custom_metric - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc request = {} - client.get_custom_metric(request) + client.get_data_stream(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_custom_metric(request) + client.get_data_stream(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_custom_metric_rest_required_fields( - request_type=analytics_admin.GetCustomMetricRequest, +def test_get_data_stream_rest_required_fields( + request_type=analytics_admin.GetDataStreamRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -78399,7 +88494,7 @@ def test_get_custom_metric_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_custom_metric._get_unset_required_fields(jsonified_request) + ).get_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -78408,7 +88503,7 @@ def test_get_custom_metric_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_custom_metric._get_unset_required_fields(jsonified_request) + ).get_data_stream._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -78422,7 +88517,7 @@ def test_get_custom_metric_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric() + return_value = resources.DataStream() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -78443,30 +88538,30 @@ def test_get_custom_metric_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_custom_metric(request) + response = client.get_data_stream(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_custom_metric_rest_unset_required_fields(): +def test_get_data_stream_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_custom_metric._get_unset_required_fields({}) + unset_fields = transport.get_data_stream._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_custom_metric_rest_interceptors(null_interceptor): +def test_get_data_stream_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -78479,14 +88574,14 @@ def test_get_custom_metric_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_custom_metric" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_data_stream" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_metric" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_stream" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetCustomMetricRequest.pb( - analytics_admin.GetCustomMetricRequest() + pb_message = analytics_admin.GetDataStreamRequest.pb( + analytics_admin.GetDataStreamRequest() ) transcode.return_value = { "method": "post", @@ -78498,19 +88593,17 @@ def test_get_custom_metric_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.CustomMetric.to_json( - resources.CustomMetric() - ) + req.return_value._content = resources.DataStream.to_json(resources.DataStream()) - request = analytics_admin.GetCustomMetricRequest() + request = analytics_admin.GetDataStreamRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CustomMetric() + post.return_value = resources.DataStream() - client.get_custom_metric( + client.get_data_stream( request, metadata=[ ("key", "val"), @@ -78522,8 +88615,8 @@ def test_get_custom_metric_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_custom_metric_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetCustomMetricRequest +def test_get_data_stream_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetDataStreamRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -78531,7 +88624,7 @@ def test_get_custom_metric_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/customMetrics/sample2"} + request_init = {"name": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -78543,10 +88636,10 @@ def test_get_custom_metric_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_custom_metric(request) + client.get_data_stream(request) -def test_get_custom_metric_rest_flattened(): +def test_get_data_stream_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -78555,10 +88648,10 @@ def test_get_custom_metric_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CustomMetric() + return_value = resources.DataStream() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/customMetrics/sample2"} + sample_request = {"name": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -78570,24 +88663,24 @@ def test_get_custom_metric_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CustomMetric.pb(return_value) + return_value = resources.DataStream.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_custom_metric(**mock_args) + client.get_data_stream(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/customMetrics/*}" % client.transport._host, + "%s/v1alpha/{name=properties/*/dataStreams/*}" % client.transport._host, args[1], ) -def test_get_custom_metric_rest_flattened_error(transport: str = "rest"): +def test_get_data_stream_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -78596,13 +88689,13 @@ def test_get_custom_metric_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_custom_metric( - analytics_admin.GetCustomMetricRequest(), + client.get_data_stream( + analytics_admin.GetDataStreamRequest(), name="name_value", ) -def test_get_custom_metric_rest_error(): +def test_get_data_stream_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -78611,51 +88704,57 @@ def test_get_custom_metric_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDataRetentionSettingsRequest, + analytics_admin.GetAudienceRequest, dict, ], ) -def test_get_data_retention_settings_rest(request_type): +def test_get_audience_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataRetentionSettings"} + request_init = {"name": "properties/sample1/audiences/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataRetentionSettings( + return_value = audience.Audience( name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataRetentionSettings.pb(return_value) + return_value = audience.Audience.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_data_retention_settings(request) + response = client.get_audience(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRetentionSettings) + assert isinstance(response, audience.Audience) assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True assert ( - response.event_data_retention - == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + response.exclusion_duration_mode + == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY ) - assert response.reset_user_data_on_new_activity is True -def test_get_data_retention_settings_rest_use_cached_wrapped_rpc(): +def test_get_audience_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -78669,35 +88768,30 @@ def test_get_data_retention_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_data_retention_settings - in client._transport._wrapped_methods - ) + assert client._transport.get_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_data_retention_settings - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_audience] = mock_rpc request = {} - client.get_data_retention_settings(request) + client.get_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_retention_settings(request) + client.get_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_data_retention_settings_rest_required_fields( - request_type=analytics_admin.GetDataRetentionSettingsRequest, +def test_get_audience_rest_required_fields( + request_type=analytics_admin.GetAudienceRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -78713,7 +88807,7 @@ def test_get_data_retention_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_data_retention_settings._get_unset_required_fields(jsonified_request) + ).get_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -78722,7 +88816,7 @@ def test_get_data_retention_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_data_retention_settings._get_unset_required_fields(jsonified_request) + ).get_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -78736,7 +88830,7 @@ def test_get_data_retention_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DataRetentionSettings() + return_value = audience.Audience() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -78757,30 +88851,30 @@ def test_get_data_retention_settings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataRetentionSettings.pb(return_value) + return_value = audience.Audience.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_data_retention_settings(request) + response = client.get_audience(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_data_retention_settings_rest_unset_required_fields(): +def test_get_audience_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_data_retention_settings._get_unset_required_fields({}) + unset_fields = transport.get_audience._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_retention_settings_rest_interceptors(null_interceptor): +def test_get_audience_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -78793,16 +88887,14 @@ def test_get_data_retention_settings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_get_data_retention_settings", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_audience" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_data_retention_settings", + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_audience" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetDataRetentionSettingsRequest.pb( - analytics_admin.GetDataRetentionSettingsRequest() + pb_message = analytics_admin.GetAudienceRequest.pb( + analytics_admin.GetAudienceRequest() ) transcode.return_value = { "method": "post", @@ -78814,19 +88906,17 @@ def test_get_data_retention_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DataRetentionSettings.to_json( - resources.DataRetentionSettings() - ) + req.return_value._content = audience.Audience.to_json(audience.Audience()) - request = analytics_admin.GetDataRetentionSettingsRequest() + request = analytics_admin.GetAudienceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DataRetentionSettings() + post.return_value = audience.Audience() - client.get_data_retention_settings( + client.get_audience( request, metadata=[ ("key", "val"), @@ -78838,9 +88928,8 @@ def test_get_data_retention_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_data_retention_settings_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.GetDataRetentionSettingsRequest, +def test_get_audience_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetAudienceRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -78848,7 +88937,7 @@ def test_get_data_retention_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataRetentionSettings"} + request_init = {"name": "properties/sample1/audiences/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -78860,10 +88949,10 @@ def test_get_data_retention_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_data_retention_settings(request) + client.get_audience(request) -def test_get_data_retention_settings_rest_flattened(): +def test_get_audience_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -78872,10 +88961,10 @@ def test_get_data_retention_settings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataRetentionSettings() + return_value = audience.Audience() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/dataRetentionSettings"} + sample_request = {"name": "properties/sample1/audiences/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -78887,25 +88976,24 @@ def test_get_data_retention_settings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataRetentionSettings.pb(return_value) + return_value = audience.Audience.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_data_retention_settings(**mock_args) + client.get_audience(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataRetentionSettings}" - % client.transport._host, + "%s/v1alpha/{name=properties/*/audiences/*}" % client.transport._host, args[1], ) -def test_get_data_retention_settings_rest_flattened_error(transport: str = "rest"): +def test_get_audience_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -78914,13 +89002,13 @@ def test_get_data_retention_settings_rest_flattened_error(transport: str = "rest # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_retention_settings( - analytics_admin.GetDataRetentionSettingsRequest(), + client.get_audience( + analytics_admin.GetAudienceRequest(), name="name_value", ) -def test_get_data_retention_settings_rest_error(): +def test_get_audience_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -78929,129 +89017,44 @@ def test_get_data_retention_settings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateDataRetentionSettingsRequest, + analytics_admin.ListAudiencesRequest, dict, ], ) -def test_update_data_retention_settings_rest(request_type): +def test_list_audiences_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "data_retention_settings": {"name": "properties/sample1/dataRetentionSettings"} - } - request_init["data_retention_settings"] = { - "name": "properties/sample1/dataRetentionSettings", - "event_data_retention": 1, - "reset_user_data_on_new_activity": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateDataRetentionSettingsRequest.meta.fields[ - "data_retention_settings" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "data_retention_settings" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["data_retention_settings"][field])): - del request_init["data_retention_settings"][field][i][subfield] - else: - del request_init["data_retention_settings"][field][subfield] + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataRetentionSettings( - name="name_value", - event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, - reset_user_data_on_new_activity=True, + return_value = analytics_admin.ListAudiencesResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataRetentionSettings.pb(return_value) + return_value = analytics_admin.ListAudiencesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_data_retention_settings(request) + response = client.list_audiences(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataRetentionSettings) - assert response.name == "name_value" - assert ( - response.event_data_retention - == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS - ) - assert response.reset_user_data_on_new_activity is True + assert isinstance(response, pagers.ListAudiencesPager) + assert response.next_page_token == "next_page_token_value" -def test_update_data_retention_settings_rest_use_cached_wrapped_rpc(): +def test_list_audiences_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -79065,39 +89068,35 @@ def test_update_data_retention_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_data_retention_settings - in client._transport._wrapped_methods - ) + assert client._transport.list_audiences in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_data_retention_settings - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_audiences] = mock_rpc request = {} - client.update_data_retention_settings(request) + client.list_audiences(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_retention_settings(request) + client.list_audiences(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_retention_settings_rest_required_fields( - request_type=analytics_admin.UpdateDataRetentionSettingsRequest, +def test_list_audiences_rest_required_fields( + request_type=analytics_admin.ListAudiencesRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -79108,19 +89107,28 @@ def test_update_data_retention_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_data_retention_settings._get_unset_required_fields(jsonified_request) + ).list_audiences._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_data_retention_settings._get_unset_required_fields(jsonified_request) + ).list_audiences._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -79129,7 +89137,7 @@ def test_update_data_retention_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DataRetentionSettings() + return_value = analytics_admin.ListAudiencesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -79141,50 +89149,47 @@ def test_update_data_retention_settings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataRetentionSettings.pb(return_value) + return_value = analytics_admin.ListAudiencesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_data_retention_settings(request) + response = client.list_audiences(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_data_retention_settings_rest_unset_required_fields(): +def test_list_audiences_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_data_retention_settings._get_unset_required_fields( - {} - ) + unset_fields = transport.list_audiences._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) - & set( + set( ( - "dataRetentionSettings", - "updateMask", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_data_retention_settings_rest_interceptors(null_interceptor): +def test_list_audiences_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -79197,16 +89202,14 @@ def test_update_data_retention_settings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_update_data_retention_settings", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_audiences" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_data_retention_settings", + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_audiences" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateDataRetentionSettingsRequest.pb( - analytics_admin.UpdateDataRetentionSettingsRequest() + pb_message = analytics_admin.ListAudiencesRequest.pb( + analytics_admin.ListAudiencesRequest() ) transcode.return_value = { "method": "post", @@ -79218,19 +89221,19 @@ def test_update_data_retention_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DataRetentionSettings.to_json( - resources.DataRetentionSettings() + req.return_value._content = analytics_admin.ListAudiencesResponse.to_json( + analytics_admin.ListAudiencesResponse() ) - request = analytics_admin.UpdateDataRetentionSettingsRequest() + request = analytics_admin.ListAudiencesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DataRetentionSettings() + post.return_value = analytics_admin.ListAudiencesResponse() - client.update_data_retention_settings( + client.list_audiences( request, metadata=[ ("key", "val"), @@ -79242,9 +89245,8 @@ def test_update_data_retention_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_data_retention_settings_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.UpdateDataRetentionSettingsRequest, +def test_list_audiences_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListAudiencesRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -79252,9 +89254,7 @@ def test_update_data_retention_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "data_retention_settings": {"name": "properties/sample1/dataRetentionSettings"} - } + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -79266,10 +89266,10 @@ def test_update_data_retention_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_data_retention_settings(request) + client.list_audiences(request) -def test_update_data_retention_settings_rest_flattened(): +def test_list_audiences_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -79278,19 +89278,14 @@ def test_update_data_retention_settings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataRetentionSettings() + return_value = analytics_admin.ListAudiencesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "data_retention_settings": { - "name": "properties/sample1/dataRetentionSettings" - } - } + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - data_retention_settings=resources.DataRetentionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) @@ -79298,25 +89293,24 @@ def test_update_data_retention_settings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataRetentionSettings.pb(return_value) + return_value = analytics_admin.ListAudiencesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_data_retention_settings(**mock_args) + client.list_audiences(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{data_retention_settings.name=properties/*/dataRetentionSettings}" - % client.transport._host, + "%s/v1alpha/{parent=properties/*}/audiences" % client.transport._host, args[1], ) -def test_update_data_retention_settings_rest_flattened_error(transport: str = "rest"): +def test_list_audiences_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -79325,27 +89319,83 @@ def test_update_data_retention_settings_rest_flattened_error(transport: str = "r # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_retention_settings( - analytics_admin.UpdateDataRetentionSettingsRequest(), - data_retention_settings=resources.DataRetentionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_audiences( + analytics_admin.ListAudiencesRequest(), + parent="parent_value", ) -def test_update_data_retention_settings_rest_error(): +def test_list_audiences_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), + ], + next_page_token="abc", + ), + analytics_admin.ListAudiencesResponse( + audiences=[], + next_page_token="def", + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListAudiencesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_audiences(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, audience.Audience) for i in results) + + pages = list(client.list_audiences(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateDataStreamRequest, + analytics_admin.CreateAudienceRequest, dict, ], ) -def test_create_data_stream_rest(request_type): +def test_create_audience_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -79353,32 +89403,73 @@ def test_create_data_stream_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "properties/sample1"} - request_init["data_stream"] = { - "web_stream_data": { - "measurement_id": "measurement_id_value", - "firebase_app_id": "firebase_app_id_value", - "default_uri": "default_uri_value", - }, - "android_app_stream_data": { - "firebase_app_id": "firebase_app_id_value", - "package_name": "package_name_value", - }, - "ios_app_stream_data": { - "firebase_app_id": "firebase_app_id_value", - "bundle_id": "bundle_id_value", - }, + request_init["audience"] = { "name": "name_value", - "type_": 1, "display_name": "display_name_value", + "description": "description_value", + "membership_duration_days": 2561, + "ads_personalization_enabled": True, + "event_trigger": {"event_name": "event_name_value", "log_condition": 1}, + "exclusion_duration_mode": 1, + "filter_clauses": [ + { + "simple_filter": { + "scope": 1, + "filter_expression": { + "and_group": {"filter_expressions": {}}, + "or_group": {}, + "not_expression": {}, + "dimension_or_metric_filter": { + "string_filter": { + "match_type": 1, + "value": "value_value", + "case_sensitive": True, + }, + "in_list_filter": { + "values": ["values_value1", "values_value2"], + "case_sensitive": True, + }, + "numeric_filter": { + "operation": 1, + "value": { + "int64_value": 1073, + "double_value": 0.12710000000000002, + }, + }, + "between_filter": {"from_value": {}, "to_value": {}}, + "field_name": "field_name_value", + "at_any_point_in_time": True, + "in_any_n_day_period": 1994, + }, + "event_filter": { + "event_name": "event_name_value", + "event_parameter_filter_expression": {}, + }, + }, + }, + "sequence_filter": { + "scope": 1, + "sequence_maximum_duration": {"seconds": 751, "nanos": 543}, + "sequence_steps": [ + { + "scope": 1, + "immediately_follows": True, + "constraint_duration": {}, + "filter_expression": {}, + } + ], + }, + "clause_type": 1, + } + ], "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateDataStreamRequest.meta.fields["data_stream"] + test_field = analytics_admin.CreateAudienceRequest.meta.fields["audience"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -79406,7 +89497,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["data_stream"].items(): # pragma: NO COVER + for field, value in request_init["audience"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -79436,40 +89527,49 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["data_stream"][field])): - del request_init["data_stream"][field][i][subfield] + for i in range(0, len(request_init["audience"][field])): + del request_init["audience"][field][i][subfield] else: - del request_init["data_stream"][field][subfield] + del request_init["audience"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataStream( + return_value = gaa_audience.Audience( name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) + return_value = gaa_audience.Audience.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_data_stream(request) + response = client.create_audience(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) + assert isinstance(response, gaa_audience.Audience) assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) -def test_create_data_stream_rest_use_cached_wrapped_rpc(): +def test_create_audience_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -79483,34 +89583,30 @@ def test_create_data_stream_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_data_stream in client._transport._wrapped_methods - ) + assert client._transport.create_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_data_stream - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_audience] = mock_rpc request = {} - client.create_data_stream(request) + client.create_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_data_stream(request) + client.create_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_data_stream_rest_required_fields( - request_type=analytics_admin.CreateDataStreamRequest, +def test_create_audience_rest_required_fields( + request_type=analytics_admin.CreateAudienceRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -79526,7 +89622,7 @@ def test_create_data_stream_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_data_stream._get_unset_required_fields(jsonified_request) + ).create_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -79535,7 +89631,7 @@ def test_create_data_stream_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_data_stream._get_unset_required_fields(jsonified_request) + ).create_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -79549,7 +89645,7 @@ def test_create_data_stream_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DataStream() + return_value = gaa_audience.Audience() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -79571,38 +89667,38 @@ def test_create_data_stream_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) + return_value = gaa_audience.Audience.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_data_stream(request) + response = client.create_audience(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_data_stream_rest_unset_required_fields(): +def test_create_audience_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_data_stream._get_unset_required_fields({}) + unset_fields = transport.create_audience._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "parent", - "dataStream", + "audience", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_data_stream_rest_interceptors(null_interceptor): +def test_create_audience_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -79615,14 +89711,14 @@ def test_create_data_stream_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_data_stream" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_audience" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_data_stream" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_audience" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateDataStreamRequest.pb( - analytics_admin.CreateDataStreamRequest() + pb_message = analytics_admin.CreateAudienceRequest.pb( + analytics_admin.CreateAudienceRequest() ) transcode.return_value = { "method": "post", @@ -79634,17 +89730,19 @@ def test_create_data_stream_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DataStream.to_json(resources.DataStream()) + req.return_value._content = gaa_audience.Audience.to_json( + gaa_audience.Audience() + ) - request = analytics_admin.CreateDataStreamRequest() + request = analytics_admin.CreateAudienceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DataStream() + post.return_value = gaa_audience.Audience() - client.create_data_stream( + client.create_audience( request, metadata=[ ("key", "val"), @@ -79656,8 +89754,8 @@ def test_create_data_stream_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_data_stream_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateDataStreamRequest +def test_create_audience_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateAudienceRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -79677,10 +89775,10 @@ def test_create_data_stream_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_data_stream(request) + client.create_audience(request) -def test_create_data_stream_rest_flattened(): +def test_create_audience_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -79689,7 +89787,7 @@ def test_create_data_stream_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataStream() + return_value = gaa_audience.Audience() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -79697,11 +89795,7 @@ def test_create_data_stream_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), + audience=gaa_audience.Audience(name="name_value"), ) mock_args.update(sample_request) @@ -79709,24 +89803,24 @@ def test_create_data_stream_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) + return_value = gaa_audience.Audience.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_data_stream(**mock_args) + client.create_audience(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/dataStreams" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/audiences" % client.transport._host, args[1], ) -def test_create_data_stream_rest_flattened_error(transport: str = "rest"): +def test_create_audience_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -79735,18 +89829,14 @@ def test_create_data_stream_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_data_stream( - analytics_admin.CreateDataStreamRequest(), + client.create_audience( + analytics_admin.CreateAudienceRequest(), parent="parent_value", - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), + audience=gaa_audience.Audience(name="name_value"), ) -def test_create_data_stream_rest_error(): +def test_create_audience_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -79755,39 +89845,185 @@ def test_create_data_stream_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteDataStreamRequest, + analytics_admin.UpdateAudienceRequest, dict, ], ) -def test_delete_data_stream_rest(request_type): +def test_update_audience_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataStreams/sample2"} + request_init = {"audience": {"name": "properties/sample1/audiences/sample2"}} + request_init["audience"] = { + "name": "properties/sample1/audiences/sample2", + "display_name": "display_name_value", + "description": "description_value", + "membership_duration_days": 2561, + "ads_personalization_enabled": True, + "event_trigger": {"event_name": "event_name_value", "log_condition": 1}, + "exclusion_duration_mode": 1, + "filter_clauses": [ + { + "simple_filter": { + "scope": 1, + "filter_expression": { + "and_group": {"filter_expressions": {}}, + "or_group": {}, + "not_expression": {}, + "dimension_or_metric_filter": { + "string_filter": { + "match_type": 1, + "value": "value_value", + "case_sensitive": True, + }, + "in_list_filter": { + "values": ["values_value1", "values_value2"], + "case_sensitive": True, + }, + "numeric_filter": { + "operation": 1, + "value": { + "int64_value": 1073, + "double_value": 0.12710000000000002, + }, + }, + "between_filter": {"from_value": {}, "to_value": {}}, + "field_name": "field_name_value", + "at_any_point_in_time": True, + "in_any_n_day_period": 1994, + }, + "event_filter": { + "event_name": "event_name_value", + "event_parameter_filter_expression": {}, + }, + }, + }, + "sequence_filter": { + "scope": 1, + "sequence_maximum_duration": {"seconds": 751, "nanos": 543}, + "sequence_steps": [ + { + "scope": 1, + "immediately_follows": True, + "constraint_duration": {}, + "filter_expression": {}, + } + ], + }, + "clause_type": 1, + } + ], + "create_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateAudienceRequest.meta.fields["audience"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["audience"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["audience"][field])): + del request_init["audience"][field][i][subfield] + else: + del request_init["audience"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = gaa_audience.Audience( + name="name_value", + display_name="display_name_value", + description="description_value", + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = gaa_audience.Audience.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_data_stream(request) + response = client.update_audience(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, gaa_audience.Audience) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert ( + response.exclusion_duration_mode + == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + ) -def test_delete_data_stream_rest_use_cached_wrapped_rpc(): +def test_update_audience_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -79801,39 +90037,34 @@ def test_delete_data_stream_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_data_stream in client._transport._wrapped_methods - ) + assert client._transport.update_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_data_stream - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_audience] = mock_rpc request = {} - client.delete_data_stream(request) + client.update_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_data_stream(request) + client.update_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_data_stream_rest_required_fields( - request_type=analytics_admin.DeleteDataStreamRequest, +def test_update_audience_rest_required_fields( + request_type=analytics_admin.UpdateAudienceRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -79844,21 +90075,19 @@ def test_delete_data_stream_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_data_stream._get_unset_required_fields(jsonified_request) + ).update_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_data_stream._get_unset_required_fields(jsonified_request) + ).update_audience._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -79867,7 +90096,7 @@ def test_delete_data_stream_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = gaa_audience.Audience() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -79879,36 +90108,48 @@ def test_delete_data_stream_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = gaa_audience.Audience.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_data_stream(request) + response = client.update_audience(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_data_stream_rest_unset_required_fields(): +def test_update_audience_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_data_stream._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_audience._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "audience", + "updateMask", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_data_stream_rest_interceptors(null_interceptor): +def test_update_audience_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -79921,11 +90162,14 @@ def test_delete_data_stream_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_data_stream" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_audience" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_audience" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteDataStreamRequest.pb( - analytics_admin.DeleteDataStreamRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateAudienceRequest.pb( + analytics_admin.UpdateAudienceRequest() ) transcode.return_value = { "method": "post", @@ -79937,15 +90181,19 @@ def test_delete_data_stream_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = gaa_audience.Audience.to_json( + gaa_audience.Audience() + ) - request = analytics_admin.DeleteDataStreamRequest() + request = analytics_admin.UpdateAudienceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = gaa_audience.Audience() - client.delete_data_stream( + client.update_audience( request, metadata=[ ("key", "val"), @@ -79954,10 +90202,11 @@ def test_delete_data_stream_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_data_stream_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteDataStreamRequest +def test_update_audience_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateAudienceRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -79965,7 +90214,7 @@ def test_delete_data_stream_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataStreams/sample2"} + request_init = {"audience": {"name": "properties/sample1/audiences/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -79977,10 +90226,10 @@ def test_delete_data_stream_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_data_stream(request) + client.update_audience(request) -def test_delete_data_stream_rest_flattened(): +def test_update_audience_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -79989,37 +90238,41 @@ def test_delete_data_stream_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = gaa_audience.Audience() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/dataStreams/sample2"} + sample_request = {"audience": {"name": "properties/sample1/audiences/sample2"}} # get truthy value for each flattened field mock_args = dict( - name="name_value", + audience=gaa_audience.Audience(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = gaa_audience.Audience.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_data_stream(**mock_args) + client.update_audience(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*}" % client.transport._host, + "%s/v1alpha/{audience.name=properties/*/audiences/*}" + % client.transport._host, args[1], ) -def test_delete_data_stream_rest_flattened_error(transport: str = "rest"): +def test_update_audience_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -80028,13 +90281,14 @@ def test_delete_data_stream_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_data_stream( - analytics_admin.DeleteDataStreamRequest(), - name="name_value", + client.update_audience( + analytics_admin.UpdateAudienceRequest(), + audience=gaa_audience.Audience(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_data_stream_rest_error(): +def test_update_audience_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -80043,135 +90297,39 @@ def test_delete_data_stream_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateDataStreamRequest, + analytics_admin.ArchiveAudienceRequest, dict, ], ) -def test_update_data_stream_rest(request_type): +def test_archive_audience_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"data_stream": {"name": "properties/sample1/dataStreams/sample2"}} - request_init["data_stream"] = { - "web_stream_data": { - "measurement_id": "measurement_id_value", - "firebase_app_id": "firebase_app_id_value", - "default_uri": "default_uri_value", - }, - "android_app_stream_data": { - "firebase_app_id": "firebase_app_id_value", - "package_name": "package_name_value", - }, - "ios_app_stream_data": { - "firebase_app_id": "firebase_app_id_value", - "bundle_id": "bundle_id_value", - }, - "name": "properties/sample1/dataStreams/sample2", - "type_": 1, - "display_name": "display_name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateDataStreamRequest.meta.fields["data_stream"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["data_stream"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["data_stream"][field])): - del request_init["data_stream"][field][i][subfield] - else: - del request_init["data_stream"][field][subfield] + request_init = {"name": "properties/sample1/audiences/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataStream( - name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_data_stream(request) + response = client.archive_audience(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) - assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM - assert response.display_name == "display_name_value" + assert response is None -def test_update_data_stream_rest_use_cached_wrapped_rpc(): +def test_archive_audience_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -80185,9 +90343,7 @@ def test_update_data_stream_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_data_stream in client._transport._wrapped_methods - ) + assert client._transport.archive_audience in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -80195,28 +90351,29 @@ def test_update_data_stream_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_data_stream + client._transport.archive_audience ] = mock_rpc request = {} - client.update_data_stream(request) + client.archive_audience(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_data_stream(request) + client.archive_audience(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_data_stream_rest_required_fields( - request_type=analytics_admin.UpdateDataStreamRequest, +def test_archive_audience_rest_required_fields( + request_type=analytics_admin.ArchiveAudienceRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -80227,19 +90384,21 @@ def test_update_data_stream_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_data_stream._get_unset_required_fields(jsonified_request) + ).archive_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_data_stream._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).archive_audience._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -80248,7 +90407,7 @@ def test_update_data_stream_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DataStream() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -80260,7 +90419,7 @@ def test_update_data_stream_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -80268,32 +90427,29 @@ def test_update_data_stream_rest_required_fields( response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_data_stream(request) + response = client.archive_audience(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_data_stream_rest_unset_required_fields(): +def test_archive_audience_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_data_stream._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + unset_fields = transport.archive_audience._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_data_stream_rest_interceptors(null_interceptor): +def test_archive_audience_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -80306,14 +90462,11 @@ def test_update_data_stream_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_data_stream" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_stream" + transports.AnalyticsAdminServiceRestInterceptor, "pre_archive_audience" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateDataStreamRequest.pb( - analytics_admin.UpdateDataStreamRequest() + pb_message = analytics_admin.ArchiveAudienceRequest.pb( + analytics_admin.ArchiveAudienceRequest() ) transcode.return_value = { "method": "post", @@ -80325,17 +90478,15 @@ def test_update_data_stream_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DataStream.to_json(resources.DataStream()) - request = analytics_admin.UpdateDataStreamRequest() + request = analytics_admin.ArchiveAudienceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DataStream() - client.update_data_stream( + client.archive_audience( request, metadata=[ ("key", "val"), @@ -80344,11 +90495,10 @@ def test_update_data_stream_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_data_stream_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateDataStreamRequest +def test_archive_audience_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ArchiveAudienceRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -80356,7 +90506,7 @@ def test_update_data_stream_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"data_stream": {"name": "properties/sample1/dataStreams/sample2"}} + request_init = {"name": "properties/sample1/audiences/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -80368,79 +90518,10 @@ def test_update_data_stream_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_data_stream(request) - - -def test_update_data_stream_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.DataStream() - - # get arguments that satisfy an http rule for this method - sample_request = { - "data_stream": {"name": "properties/sample1/dataStreams/sample2"} - } - - # get truthy value for each flattened field - mock_args = dict( - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_data_stream(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{data_stream.name=properties/*/dataStreams/*}" - % client.transport._host, - args[1], - ) - - -def test_update_data_stream_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_data_stream( - analytics_admin.UpdateDataStreamRequest(), - data_stream=resources.DataStream( - web_stream_data=resources.DataStream.WebStreamData( - measurement_id="measurement_id_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + client.archive_audience(request) -def test_update_data_stream_rest_error(): +def test_archive_audience_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -80449,44 +90530,48 @@ def test_update_data_stream_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListDataStreamsRequest, + analytics_admin.GetSearchAds360LinkRequest, dict, ], ) -def test_list_data_streams_rest(request_type): +def test_get_search_ads360_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/searchAds360Links/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDataStreamsResponse( - next_page_token="next_page_token_value", + return_value = resources.SearchAds360Link( + name="name_value", + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListDataStreamsResponse.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_data_streams(request) + response = client.get_search_ads360_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataStreamsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.SearchAds360Link) + assert response.name == "name_value" + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_list_data_streams_rest_use_cached_wrapped_rpc(): +def test_get_search_ads360_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -80500,7 +90585,10 @@ def test_list_data_streams_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_streams in client._transport._wrapped_methods + assert ( + client._transport.get_search_ads360_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -80508,29 +90596,29 @@ def test_list_data_streams_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_data_streams + client._transport.get_search_ads360_link ] = mock_rpc request = {} - client.list_data_streams(request) + client.get_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_streams(request) + client.get_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_data_streams_rest_required_fields( - request_type=analytics_admin.ListDataStreamsRequest, +def test_get_search_ads360_link_rest_required_fields( + request_type=analytics_admin.GetSearchAds360LinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -80541,28 +90629,21 @@ def test_list_data_streams_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_data_streams._get_unset_required_fields(jsonified_request) + ).get_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_data_streams._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).get_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -80571,7 +90652,7 @@ def test_list_data_streams_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDataStreamsResponse() + return_value = resources.SearchAds360Link() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -80592,38 +90673,30 @@ def test_list_data_streams_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListDataStreamsResponse.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_data_streams(request) + response = client.get_search_ads360_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_data_streams_rest_unset_required_fields(): +def test_get_search_ads360_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_data_streams._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_data_streams_rest_interceptors(null_interceptor): +def test_get_search_ads360_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -80636,14 +90709,14 @@ def test_list_data_streams_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_data_streams" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_search_ads360_link" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_data_streams" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_search_ads360_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListDataStreamsRequest.pb( - analytics_admin.ListDataStreamsRequest() + pb_message = analytics_admin.GetSearchAds360LinkRequest.pb( + analytics_admin.GetSearchAds360LinkRequest() ) transcode.return_value = { "method": "post", @@ -80655,19 +90728,19 @@ def test_list_data_streams_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListDataStreamsResponse.to_json( - analytics_admin.ListDataStreamsResponse() + req.return_value._content = resources.SearchAds360Link.to_json( + resources.SearchAds360Link() ) - request = analytics_admin.ListDataStreamsRequest() + request = analytics_admin.GetSearchAds360LinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListDataStreamsResponse() + post.return_value = resources.SearchAds360Link() - client.list_data_streams( + client.get_search_ads360_link( request, metadata=[ ("key", "val"), @@ -80679,8 +90752,8 @@ def test_list_data_streams_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_data_streams_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListDataStreamsRequest +def test_get_search_ads360_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetSearchAds360LinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -80688,7 +90761,7 @@ def test_list_data_streams_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/searchAds360Links/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -80700,10 +90773,10 @@ def test_list_data_streams_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_data_streams(request) + client.get_search_ads360_link(request) -def test_list_data_streams_rest_flattened(): +def test_get_search_ads360_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -80712,161 +90785,101 @@ def test_list_data_streams_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListDataStreamsResponse() + return_value = resources.SearchAds360Link() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListDataStreamsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.list_data_streams(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/dataStreams" % client.transport._host, - args[1], - ) - - -def test_list_data_streams_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_data_streams( - analytics_admin.ListDataStreamsRequest(), - parent="parent_value", - ) - - -def test_list_data_streams_rest_pager(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - resources.DataStream(), - ], - next_page_token="abc", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[], - next_page_token="def", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - ], - next_page_token="ghi", - ), - analytics_admin.ListDataStreamsResponse( - data_streams=[ - resources.DataStream(), - resources.DataStream(), - ], - ), + sample_request = {"name": "properties/sample1/searchAds360Links/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - # Two responses for two calls - response = response + response + mock_args.update(sample_request) - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListDataStreamsResponse.to_json(x) for x in response + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_search_ads360_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/searchAds360Links/*}" + % client.transport._host, + args[1], ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - sample_request = {"parent": "properties/sample1"} - pager = client.list_data_streams(request=sample_request) +def test_get_search_ads360_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.DataStream) for i in results) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_search_ads360_link( + analytics_admin.GetSearchAds360LinkRequest(), + name="name_value", + ) - pages = list(client.list_data_streams(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + +def test_get_search_ads360_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetDataStreamRequest, + analytics_admin.ListSearchAds360LinksRequest, dict, ], ) -def test_get_data_stream_rest(request_type): +def test_list_search_ads360_links_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataStreams/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataStream( - name="name_value", - type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, - display_name="display_name_value", + return_value = analytics_admin.ListSearchAds360LinksResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) + return_value = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_data_stream(request) + response = client.list_search_ads360_links(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.DataStream) - assert response.name == "name_value" - assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM - assert response.display_name == "display_name_value" + assert isinstance(response, pagers.ListSearchAds360LinksPager) + assert response.next_page_token == "next_page_token_value" -def test_get_data_stream_rest_use_cached_wrapped_rpc(): +def test_list_search_ads360_links_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -80880,35 +90893,40 @@ def test_get_data_stream_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_stream in client._transport._wrapped_methods + assert ( + client._transport.list_search_ads360_links + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_search_ads360_links + ] = mock_rpc request = {} - client.get_data_stream(request) + client.list_search_ads360_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_stream(request) + client.list_search_ads360_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_data_stream_rest_required_fields( - request_type=analytics_admin.GetDataStreamRequest, +def test_list_search_ads360_links_rest_required_fields( + request_type=analytics_admin.ListSearchAds360LinksRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -80919,21 +90937,28 @@ def test_get_data_stream_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_data_stream._get_unset_required_fields(jsonified_request) + ).list_search_ads360_links._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_data_stream._get_unset_required_fields(jsonified_request) + ).list_search_ads360_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -80942,7 +90967,7 @@ def test_get_data_stream_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.DataStream() + return_value = analytics_admin.ListSearchAds360LinksResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -80963,30 +90988,40 @@ def test_get_data_stream_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) + return_value = analytics_admin.ListSearchAds360LinksResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_data_stream(request) + response = client.list_search_ads360_links(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_data_stream_rest_unset_required_fields(): +def test_list_search_ads360_links_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_data_stream._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_search_ads360_links._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_stream_rest_interceptors(null_interceptor): +def test_list_search_ads360_links_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -80999,14 +91034,14 @@ def test_get_data_stream_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_data_stream" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_search_ads360_links" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_stream" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_search_ads360_links" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetDataStreamRequest.pb( - analytics_admin.GetDataStreamRequest() + pb_message = analytics_admin.ListSearchAds360LinksRequest.pb( + analytics_admin.ListSearchAds360LinksRequest() ) transcode.return_value = { "method": "post", @@ -81018,17 +91053,21 @@ def test_get_data_stream_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.DataStream.to_json(resources.DataStream()) + req.return_value._content = ( + analytics_admin.ListSearchAds360LinksResponse.to_json( + analytics_admin.ListSearchAds360LinksResponse() + ) + ) - request = analytics_admin.GetDataStreamRequest() + request = analytics_admin.ListSearchAds360LinksRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.DataStream() + post.return_value = analytics_admin.ListSearchAds360LinksResponse() - client.get_data_stream( + client.list_search_ads360_links( request, metadata=[ ("key", "val"), @@ -81040,8 +91079,8 @@ def test_get_data_stream_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_data_stream_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetDataStreamRequest +def test_list_search_ads360_links_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListSearchAds360LinksRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -81049,7 +91088,7 @@ def test_get_data_stream_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/dataStreams/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -81061,10 +91100,10 @@ def test_get_data_stream_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_data_stream(request) + client.list_search_ads360_links(request) -def test_get_data_stream_rest_flattened(): +def test_list_search_ads360_links_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -81073,14 +91112,14 @@ def test_get_data_stream_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.DataStream() + return_value = analytics_admin.ListSearchAds360LinksResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/dataStreams/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -81088,24 +91127,25 @@ def test_get_data_stream_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.DataStream.pb(return_value) + return_value = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_data_stream(**mock_args) + client.list_search_ads360_links(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*}" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/searchAds360Links" + % client.transport._host, args[1], ) -def test_get_data_stream_rest_flattened_error(transport: str = "rest"): +def test_list_search_ads360_links_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -81114,72 +91154,198 @@ def test_get_data_stream_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_stream( - analytics_admin.GetDataStreamRequest(), - name="name_value", + client.list_search_ads360_links( + analytics_admin.ListSearchAds360LinksRequest(), + parent="parent_value", ) -def test_get_data_stream_rest_error(): +def test_list_search_ads360_links_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token="abc", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token="def", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token="ghi", + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListSearchAds360LinksResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_search_ads360_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SearchAds360Link) for i in results) + + pages = list(client.list_search_ads360_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAudienceRequest, + analytics_admin.CreateSearchAds360LinkRequest, dict, ], ) -def test_get_audience_rest(request_type): +def test_create_search_ads360_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/audiences/sample2"} + request_init = {"parent": "properties/sample1"} + request_init["search_ads_360_link"] = { + "name": "name_value", + "advertiser_id": "advertiser_id_value", + "campaign_data_sharing_enabled": {"value": True}, + "cost_data_sharing_enabled": {}, + "advertiser_display_name": "advertiser_display_name_value", + "ads_personalization_enabled": {}, + "site_stats_sharing_enabled": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateSearchAds360LinkRequest.meta.fields[ + "search_ads_360_link" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_ads_360_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_ads_360_link"][field])): + del request_init["search_ads_360_link"][field][i][subfield] + else: + del request_init["search_ads_360_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = audience.Audience( + return_value = resources.SearchAds360Link( name="name_value", - display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = audience.Audience.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_audience(request) + response = client.create_search_ads360_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, audience.Audience) + assert isinstance(response, resources.SearchAds360Link) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_get_audience_rest_use_cached_wrapped_rpc(): +def test_create_search_ads360_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -81193,35 +91359,40 @@ def test_get_audience_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_audience in client._transport._wrapped_methods + assert ( + client._transport.create_search_ads360_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_audience] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_search_ads360_link + ] = mock_rpc request = {} - client.get_audience(request) + client.create_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_audience(request) + client.create_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_audience_rest_required_fields( - request_type=analytics_admin.GetAudienceRequest, +def test_create_search_ads360_link_rest_required_fields( + request_type=analytics_admin.CreateSearchAds360LinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -81232,21 +91403,21 @@ def test_get_audience_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_audience._get_unset_required_fields(jsonified_request) + ).create_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_audience._get_unset_required_fields(jsonified_request) + ).create_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -81255,7 +91426,7 @@ def test_get_audience_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = audience.Audience() + return_value = resources.SearchAds360Link() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -81267,39 +91438,48 @@ def test_get_audience_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = audience.Audience.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_audience(request) + response = client.create_search_ads360_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_audience_rest_unset_required_fields(): +def test_create_search_ads360_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_audience._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "searchAds360Link", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_audience_rest_interceptors(null_interceptor): +def test_create_search_ads360_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -81312,14 +91492,15 @@ def test_get_audience_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_audience" + transports.AnalyticsAdminServiceRestInterceptor, + "post_create_search_ads360_link", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_audience" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_search_ads360_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetAudienceRequest.pb( - analytics_admin.GetAudienceRequest() + pb_message = analytics_admin.CreateSearchAds360LinkRequest.pb( + analytics_admin.CreateSearchAds360LinkRequest() ) transcode.return_value = { "method": "post", @@ -81331,17 +91512,19 @@ def test_get_audience_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = audience.Audience.to_json(audience.Audience()) + req.return_value._content = resources.SearchAds360Link.to_json( + resources.SearchAds360Link() + ) - request = analytics_admin.GetAudienceRequest() + request = analytics_admin.CreateSearchAds360LinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = audience.Audience() + post.return_value = resources.SearchAds360Link() - client.get_audience( + client.create_search_ads360_link( request, metadata=[ ("key", "val"), @@ -81353,8 +91536,8 @@ def test_get_audience_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_audience_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetAudienceRequest +def test_create_search_ads360_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateSearchAds360LinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -81362,7 +91545,7 @@ def test_get_audience_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/audiences/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -81374,10 +91557,10 @@ def test_get_audience_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_audience(request) + client.create_search_ads360_link(request) -def test_get_audience_rest_flattened(): +def test_create_search_ads360_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -81386,14 +91569,15 @@ def test_get_audience_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = audience.Audience() + return_value = resources.SearchAds360Link() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/audiences/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + search_ads_360_link=resources.SearchAds360Link(name="name_value"), ) mock_args.update(sample_request) @@ -81401,24 +91585,25 @@ def test_get_audience_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = audience.Audience.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_audience(**mock_args) + client.create_search_ads360_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/audiences/*}" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/searchAds360Links" + % client.transport._host, args[1], ) -def test_get_audience_rest_flattened_error(transport: str = "rest"): +def test_create_search_ads360_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -81427,13 +91612,14 @@ def test_get_audience_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_audience( - analytics_admin.GetAudienceRequest(), - name="name_value", + client.create_search_ads360_link( + analytics_admin.CreateSearchAds360LinkRequest(), + parent="parent_value", + search_ads_360_link=resources.SearchAds360Link(name="name_value"), ) -def test_get_audience_rest_error(): +def test_create_search_ads360_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -81442,44 +91628,39 @@ def test_get_audience_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListAudiencesRequest, + analytics_admin.DeleteSearchAds360LinkRequest, dict, ], ) -def test_list_audiences_rest(request_type): +def test_delete_search_ads360_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/searchAds360Links/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAudiencesResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListAudiencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_audiences(request) + response = client.delete_search_ads360_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAudiencesPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_audiences_rest_use_cached_wrapped_rpc(): +def test_delete_search_ads360_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -81493,35 +91674,40 @@ def test_list_audiences_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_audiences in client._transport._wrapped_methods + assert ( + client._transport.delete_search_ads360_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_audiences] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_search_ads360_link + ] = mock_rpc request = {} - client.list_audiences(request) + client.delete_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_audiences(request) + client.delete_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_audiences_rest_required_fields( - request_type=analytics_admin.ListAudiencesRequest, +def test_delete_search_ads360_link_rest_required_fields( + request_type=analytics_admin.DeleteSearchAds360LinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -81532,28 +91718,21 @@ def test_list_audiences_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_audiences._get_unset_required_fields(jsonified_request) + ).delete_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_audiences._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).delete_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -81562,7 +91741,7 @@ def test_list_audiences_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAudiencesResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -81574,47 +91753,36 @@ def test_list_audiences_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = analytics_admin.ListAudiencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_audiences(request) + response = client.delete_search_ads360_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_audiences_rest_unset_required_fields(): +def test_delete_search_ads360_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_audiences._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.delete_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_audiences_rest_interceptors(null_interceptor): +def test_delete_search_ads360_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -81627,14 +91795,11 @@ def test_list_audiences_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_audiences" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_audiences" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_search_ads360_link" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ListAudiencesRequest.pb( - analytics_admin.ListAudiencesRequest() + pb_message = analytics_admin.DeleteSearchAds360LinkRequest.pb( + analytics_admin.DeleteSearchAds360LinkRequest() ) transcode.return_value = { "method": "post", @@ -81646,19 +91811,15 @@ def test_list_audiences_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListAudiencesResponse.to_json( - analytics_admin.ListAudiencesResponse() - ) - request = analytics_admin.ListAudiencesRequest() + request = analytics_admin.DeleteSearchAds360LinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListAudiencesResponse() - client.list_audiences( + client.delete_search_ads360_link( request, metadata=[ ("key", "val"), @@ -81667,11 +91828,10 @@ def test_list_audiences_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_list_audiences_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListAudiencesRequest +def test_delete_search_ads360_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteSearchAds360LinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -81679,7 +91839,7 @@ def test_list_audiences_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/searchAds360Links/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -81691,10 +91851,10 @@ def test_list_audiences_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_audiences(request) + client.delete_search_ads360_link(request) -def test_list_audiences_rest_flattened(): +def test_delete_search_ads360_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -81703,39 +91863,38 @@ def test_list_audiences_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAudiencesResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"name": "properties/sample1/searchAds360Links/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListAudiencesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_audiences(**mock_args) + client.delete_search_ads360_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/audiences" % client.transport._host, + "%s/v1alpha/{name=properties/*/searchAds360Links/*}" + % client.transport._host, args[1], ) -def test_list_audiences_rest_flattened_error(transport: str = "rest"): +def test_delete_search_ads360_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -81744,156 +91903,52 @@ def test_list_audiences_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_audiences( - analytics_admin.ListAudiencesRequest(), - parent="parent_value", + client.delete_search_ads360_link( + analytics_admin.DeleteSearchAds360LinkRequest(), + name="name_value", ) -def test_list_audiences_rest_pager(transport: str = "rest"): +def test_delete_search_ads360_link_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - audience.Audience(), - ], - next_page_token="abc", - ), - analytics_admin.ListAudiencesResponse( - audiences=[], - next_page_token="def", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAudiencesResponse( - audiences=[ - audience.Audience(), - audience.Audience(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListAudiencesResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_audiences(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, audience.Audience) for i in results) - - pages = list(client.list_audiences(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateAudienceRequest, + analytics_admin.UpdateSearchAds360LinkRequest, dict, ], ) -def test_create_audience_rest(request_type): +def test_update_search_ads360_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["audience"] = { - "name": "name_value", - "display_name": "display_name_value", - "description": "description_value", - "membership_duration_days": 2561, - "ads_personalization_enabled": True, - "event_trigger": {"event_name": "event_name_value", "log_condition": 1}, - "exclusion_duration_mode": 1, - "filter_clauses": [ - { - "simple_filter": { - "scope": 1, - "filter_expression": { - "and_group": {"filter_expressions": {}}, - "or_group": {}, - "not_expression": {}, - "dimension_or_metric_filter": { - "string_filter": { - "match_type": 1, - "value": "value_value", - "case_sensitive": True, - }, - "in_list_filter": { - "values": ["values_value1", "values_value2"], - "case_sensitive": True, - }, - "numeric_filter": { - "operation": 1, - "value": { - "int64_value": 1073, - "double_value": 0.12710000000000002, - }, - }, - "between_filter": {"from_value": {}, "to_value": {}}, - "field_name": "field_name_value", - "at_any_point_in_time": True, - "in_any_n_day_period": 1994, - }, - "event_filter": { - "event_name": "event_name_value", - "event_parameter_filter_expression": {}, - }, - }, - }, - "sequence_filter": { - "scope": 1, - "sequence_maximum_duration": {"seconds": 751, "nanos": 543}, - "sequence_steps": [ - { - "scope": 1, - "immediately_follows": True, - "constraint_duration": {}, - "filter_expression": {}, - } - ], - }, - "clause_type": 1, - } - ], + request_init = { + "search_ads_360_link": {"name": "properties/sample1/searchAds360Links/sample2"} + } + request_init["search_ads_360_link"] = { + "name": "properties/sample1/searchAds360Links/sample2", + "advertiser_id": "advertiser_id_value", + "campaign_data_sharing_enabled": {"value": True}, + "cost_data_sharing_enabled": {}, + "advertiser_display_name": "advertiser_display_name_value", + "ads_personalization_enabled": {}, + "site_stats_sharing_enabled": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateAudienceRequest.meta.fields["audience"] + test_field = analytics_admin.UpdateSearchAds360LinkRequest.meta.fields[ + "search_ads_360_link" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -81921,7 +91976,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["audience"].items(): # pragma: NO COVER + for field, value in request_init["search_ads_360_link"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -81951,49 +92006,40 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["audience"][field])): - del request_init["audience"][field][i][subfield] + for i in range(0, len(request_init["search_ads_360_link"][field])): + del request_init["search_ads_360_link"][field][i][subfield] else: - del request_init["audience"][field][subfield] + del request_init["search_ads_360_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_audience.Audience( + return_value = resources.SearchAds360Link( name="name_value", - display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + advertiser_id="advertiser_id_value", + advertiser_display_name="advertiser_display_name_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_audience.Audience.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_audience(request) + response = client.update_search_ads360_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, gaa_audience.Audience) + assert isinstance(response, resources.SearchAds360Link) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True - assert ( - response.exclusion_duration_mode - == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY - ) + assert response.advertiser_id == "advertiser_id_value" + assert response.advertiser_display_name == "advertiser_display_name_value" -def test_create_audience_rest_use_cached_wrapped_rpc(): +def test_update_search_ads360_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -82007,35 +92053,39 @@ def test_create_audience_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_audience in client._transport._wrapped_methods + assert ( + client._transport.update_search_ads360_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_audience] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_search_ads360_link + ] = mock_rpc request = {} - client.create_audience(request) + client.update_search_ads360_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_audience(request) + client.update_search_ads360_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_audience_rest_required_fields( - request_type=analytics_admin.CreateAudienceRequest, +def test_update_search_ads360_link_rest_required_fields( + request_type=analytics_admin.UpdateSearchAds360LinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -82046,21 +92096,19 @@ def test_create_audience_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_audience._get_unset_required_fields(jsonified_request) + ).update_search_ads360_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_audience._get_unset_required_fields(jsonified_request) + ).update_search_ads360_link._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -82069,7 +92117,7 @@ def test_create_audience_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gaa_audience.Audience() + return_value = resources.SearchAds360Link() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -82081,7 +92129,7 @@ def test_create_audience_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -82091,38 +92139,30 @@ def test_create_audience_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_audience.Audience.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_audience(request) + response = client.update_search_ads360_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_audience_rest_unset_required_fields(): +def test_update_search_ads360_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_audience._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "audience", - ) - ) - ) + unset_fields = transport.update_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_audience_rest_interceptors(null_interceptor): +def test_update_search_ads360_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -82135,14 +92175,15 @@ def test_create_audience_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_audience" + transports.AnalyticsAdminServiceRestInterceptor, + "post_update_search_ads360_link", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_audience" + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_search_ads360_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateAudienceRequest.pb( - analytics_admin.CreateAudienceRequest() + pb_message = analytics_admin.UpdateSearchAds360LinkRequest.pb( + analytics_admin.UpdateSearchAds360LinkRequest() ) transcode.return_value = { "method": "post", @@ -82154,19 +92195,19 @@ def test_create_audience_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gaa_audience.Audience.to_json( - gaa_audience.Audience() + req.return_value._content = resources.SearchAds360Link.to_json( + resources.SearchAds360Link() ) - request = analytics_admin.CreateAudienceRequest() + request = analytics_admin.UpdateSearchAds360LinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gaa_audience.Audience() + post.return_value = resources.SearchAds360Link() - client.create_audience( + client.update_search_ads360_link( request, metadata=[ ("key", "val"), @@ -82178,8 +92219,8 @@ def test_create_audience_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_audience_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateAudienceRequest +def test_update_search_ads360_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateSearchAds360LinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -82187,7 +92228,9 @@ def test_create_audience_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "search_ads_360_link": {"name": "properties/sample1/searchAds360Links/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -82199,10 +92242,10 @@ def test_create_audience_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_audience(request) + client.update_search_ads360_link(request) -def test_create_audience_rest_flattened(): +def test_update_search_ads360_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -82211,15 +92254,19 @@ def test_create_audience_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_audience.Audience() + return_value = resources.SearchAds360Link() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = { + "search_ads_360_link": { + "name": "properties/sample1/searchAds360Links/sample2" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - audience=gaa_audience.Audience(name="name_value"), + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -82227,24 +92274,25 @@ def test_create_audience_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_audience.Audience.pb(return_value) + return_value = resources.SearchAds360Link.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_audience(**mock_args) + client.update_search_ads360_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/audiences" % client.transport._host, + "%s/v1alpha/{search_ads_360_link.name=properties/*/searchAds360Links/*}" + % client.transport._host, args[1], ) -def test_create_audience_rest_flattened_error(transport: str = "rest"): +def test_update_search_ads360_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -82253,14 +92301,14 @@ def test_create_audience_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_audience( - analytics_admin.CreateAudienceRequest(), - parent="parent_value", - audience=gaa_audience.Audience(name="name_value"), + client.update_search_ads360_link( + analytics_admin.UpdateSearchAds360LinkRequest(), + search_ads_360_link=resources.SearchAds360Link(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_audience_rest_error(): +def test_update_search_ads360_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -82269,184 +92317,64 @@ def test_create_audience_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAudienceRequest, - dict, - ], -) -def test_update_audience_rest(request_type): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"audience": {"name": "properties/sample1/audiences/sample2"}} - request_init["audience"] = { - "name": "properties/sample1/audiences/sample2", - "display_name": "display_name_value", - "description": "description_value", - "membership_duration_days": 2561, - "ads_personalization_enabled": True, - "event_trigger": {"event_name": "event_name_value", "log_condition": 1}, - "exclusion_duration_mode": 1, - "filter_clauses": [ - { - "simple_filter": { - "scope": 1, - "filter_expression": { - "and_group": {"filter_expressions": {}}, - "or_group": {}, - "not_expression": {}, - "dimension_or_metric_filter": { - "string_filter": { - "match_type": 1, - "value": "value_value", - "case_sensitive": True, - }, - "in_list_filter": { - "values": ["values_value1", "values_value2"], - "case_sensitive": True, - }, - "numeric_filter": { - "operation": 1, - "value": { - "int64_value": 1073, - "double_value": 0.12710000000000002, - }, - }, - "between_filter": {"from_value": {}, "to_value": {}}, - "field_name": "field_name_value", - "at_any_point_in_time": True, - "in_any_n_day_period": 1994, - }, - "event_filter": { - "event_name": "event_name_value", - "event_parameter_filter_expression": {}, - }, - }, - }, - "sequence_filter": { - "scope": 1, - "sequence_maximum_duration": {"seconds": 751, "nanos": 543}, - "sequence_steps": [ - { - "scope": 1, - "immediately_follows": True, - "constraint_duration": {}, - "filter_expression": {}, - } - ], - }, - "clause_type": 1, - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateAudienceRequest.meta.fields["audience"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["audience"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + analytics_admin.GetAttributionSettingsRequest, + dict, + ], +) +def test_get_attribution_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["audience"][field])): - del request_init["audience"][field][i][subfield] - else: - del request_init["audience"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"name": "properties/sample1/attributionSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_audience.Audience( + return_value = resources.AttributionSettings( name="name_value", - display_name="display_name_value", - description="description_value", - membership_duration_days=2561, - ads_personalization_enabled=True, - exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_audience.Audience.pb(return_value) + return_value = resources.AttributionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_audience(request) + response = client.get_attribution_settings(request) # Establish that the response is the type that we expect. - assert isinstance(response, gaa_audience.Audience) + assert isinstance(response, resources.AttributionSettings) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.membership_duration_days == 2561 - assert response.ads_personalization_enabled is True assert ( - response.exclusion_duration_mode - == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + response.acquisition_conversion_event_lookback_window + == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + ) + assert ( + response.other_conversion_event_lookback_window + == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + ) + assert ( + response.reporting_attribution_model + == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + ) + assert ( + response.ads_web_conversion_data_export_scope + == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET ) -def test_update_audience_rest_use_cached_wrapped_rpc(): +def test_get_attribution_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -82460,34 +92388,40 @@ def test_update_audience_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_audience in client._transport._wrapped_methods + assert ( + client._transport.get_attribution_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_audience] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_attribution_settings + ] = mock_rpc request = {} - client.update_audience(request) + client.get_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_audience(request) + client.get_attribution_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_audience_rest_required_fields( - request_type=analytics_admin.UpdateAudienceRequest, +def test_get_attribution_settings_rest_required_fields( + request_type=analytics_admin.GetAttributionSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -82498,19 +92432,21 @@ def test_update_audience_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_audience._get_unset_required_fields(jsonified_request) + ).get_attribution_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_audience._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).get_attribution_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -82519,7 +92455,7 @@ def test_update_audience_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gaa_audience.Audience() + return_value = resources.AttributionSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -82531,48 +92467,39 @@ def test_update_audience_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_audience.Audience.pb(return_value) + return_value = resources.AttributionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_audience(request) + response = client.get_attribution_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_audience_rest_unset_required_fields(): +def test_get_attribution_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_audience._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "audience", - "updateMask", - ) - ) - ) + unset_fields = transport.get_attribution_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_audience_rest_interceptors(null_interceptor): +def test_get_attribution_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -82585,14 +92512,14 @@ def test_update_audience_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_audience" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_attribution_settings" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_audience" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_attribution_settings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateAudienceRequest.pb( - analytics_admin.UpdateAudienceRequest() + pb_message = analytics_admin.GetAttributionSettingsRequest.pb( + analytics_admin.GetAttributionSettingsRequest() ) transcode.return_value = { "method": "post", @@ -82604,19 +92531,19 @@ def test_update_audience_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gaa_audience.Audience.to_json( - gaa_audience.Audience() + req.return_value._content = resources.AttributionSettings.to_json( + resources.AttributionSettings() ) - request = analytics_admin.UpdateAudienceRequest() + request = analytics_admin.GetAttributionSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gaa_audience.Audience() + post.return_value = resources.AttributionSettings() - client.update_audience( + client.get_attribution_settings( request, metadata=[ ("key", "val"), @@ -82628,8 +92555,8 @@ def test_update_audience_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_audience_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateAudienceRequest +def test_get_attribution_settings_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetAttributionSettingsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -82637,7 +92564,7 @@ def test_update_audience_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"audience": {"name": "properties/sample1/audiences/sample2"}} + request_init = {"name": "properties/sample1/attributionSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -82649,10 +92576,10 @@ def test_update_audience_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_audience(request) + client.get_attribution_settings(request) -def test_update_audience_rest_flattened(): +def test_get_attribution_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -82661,15 +92588,14 @@ def test_update_audience_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_audience.Audience() + return_value = resources.AttributionSettings() # get arguments that satisfy an http rule for this method - sample_request = {"audience": {"name": "properties/sample1/audiences/sample2"}} + sample_request = {"name": "properties/sample1/attributionSettings"} # get truthy value for each flattened field mock_args = dict( - audience=gaa_audience.Audience(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -82677,25 +92603,25 @@ def test_update_audience_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_audience.Audience.pb(return_value) + return_value = resources.AttributionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_audience(**mock_args) + client.get_attribution_settings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{audience.name=properties/*/audiences/*}" + "%s/v1alpha/{name=properties/*/attributionSettings}" % client.transport._host, args[1], ) -def test_update_audience_rest_flattened_error(transport: str = "rest"): +def test_get_attribution_settings_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -82704,14 +92630,13 @@ def test_update_audience_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_audience( - analytics_admin.UpdateAudienceRequest(), - audience=gaa_audience.Audience(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_attribution_settings( + analytics_admin.GetAttributionSettingsRequest(), + name="name_value", ) -def test_update_audience_rest_error(): +def test_get_attribution_settings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -82720,39 +92645,144 @@ def test_update_audience_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ArchiveAudienceRequest, + analytics_admin.UpdateAttributionSettingsRequest, dict, ], ) -def test_archive_audience_rest(request_type): +def test_update_attribution_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/audiences/sample2"} + request_init = { + "attribution_settings": {"name": "properties/sample1/attributionSettings"} + } + request_init["attribution_settings"] = { + "name": "properties/sample1/attributionSettings", + "acquisition_conversion_event_lookback_window": 1, + "other_conversion_event_lookback_window": 1, + "reporting_attribution_model": 1, + "ads_web_conversion_data_export_scope": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateAttributionSettingsRequest.meta.fields[ + "attribution_settings" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "attribution_settings" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["attribution_settings"][field])): + del request_init["attribution_settings"][field][i][subfield] + else: + del request_init["attribution_settings"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.AttributionSettings( + name="name_value", + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.AttributionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.archive_audience(request) + response = client.update_attribution_settings(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.AttributionSettings) + assert response.name == "name_value" + assert ( + response.acquisition_conversion_event_lookback_window + == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + ) + assert ( + response.other_conversion_event_lookback_window + == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + ) + assert ( + response.reporting_attribution_model + == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + ) + assert ( + response.ads_web_conversion_data_export_scope + == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + ) -def test_archive_audience_rest_use_cached_wrapped_rpc(): +def test_update_attribution_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -82766,7 +92796,10 @@ def test_archive_audience_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.archive_audience in client._transport._wrapped_methods + assert ( + client._transport.update_attribution_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -82774,29 +92807,28 @@ def test_archive_audience_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.archive_audience + client._transport.update_attribution_settings ] = mock_rpc request = {} - client.archive_audience(request) + client.update_attribution_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.archive_audience(request) + client.update_attribution_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_archive_audience_rest_required_fields( - request_type=analytics_admin.ArchiveAudienceRequest, +def test_update_attribution_settings_rest_required_fields( + request_type=analytics_admin.UpdateAttributionSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -82807,21 +92839,19 @@ def test_archive_audience_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).archive_audience._get_unset_required_fields(jsonified_request) + ).update_attribution_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).archive_audience._get_unset_required_fields(jsonified_request) + ).update_attribution_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -82830,7 +92860,7 @@ def test_archive_audience_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.AttributionSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -82842,7 +92872,7 @@ def test_archive_audience_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -82850,29 +92880,40 @@ def test_archive_audience_rest_required_fields( response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.AttributionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.archive_audience(request) + response = client.update_attribution_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_archive_audience_rest_unset_required_fields(): +def test_update_attribution_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.archive_audience._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_attribution_settings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "attributionSettings", + "updateMask", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_archive_audience_rest_interceptors(null_interceptor): +def test_update_attribution_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -82885,11 +92926,16 @@ def test_archive_audience_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_archive_audience" + transports.AnalyticsAdminServiceRestInterceptor, + "post_update_attribution_settings", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_update_attribution_settings", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.ArchiveAudienceRequest.pb( - analytics_admin.ArchiveAudienceRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateAttributionSettingsRequest.pb( + analytics_admin.UpdateAttributionSettingsRequest() ) transcode.return_value = { "method": "post", @@ -82901,15 +92947,19 @@ def test_archive_audience_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.AttributionSettings.to_json( + resources.AttributionSettings() + ) - request = analytics_admin.ArchiveAudienceRequest() + request = analytics_admin.UpdateAttributionSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.AttributionSettings() - client.archive_audience( + client.update_attribution_settings( request, metadata=[ ("key", "val"), @@ -82918,10 +92968,12 @@ def test_archive_audience_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_archive_audience_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ArchiveAudienceRequest +def test_update_attribution_settings_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.UpdateAttributionSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -82929,7 +92981,9 @@ def test_archive_audience_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/audiences/sample2"} + request_init = { + "attribution_settings": {"name": "properties/sample1/attributionSettings"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -82941,185 +92995,156 @@ def test_archive_audience_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.archive_audience(request) - - -def test_archive_audience_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.update_attribution_settings(request) -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.GetSearchAds360LinkRequest, - dict, - ], -) -def test_get_search_ads360_link_rest(request_type): +def test_update_attribution_settings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/searchAds360Links/sample2"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + return_value = resources.AttributionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = { + "attribution_settings": {"name": "properties/sample1/attributionSettings"} + } + + # get truthy value for each flattened field + mock_args = dict( + attribution_settings=resources.AttributionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) + return_value = resources.AttributionSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_search_ads360_link(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + client.update_attribution_settings(**mock_args) -def test_get_search_ads360_link_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{attribution_settings.name=properties/*/attributionSettings}" + % client.transport._host, + args[1], ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert ( - client._transport.get_search_ads360_link - in client._transport._wrapped_methods - ) +def test_update_attribution_settings_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_attribution_settings( + analytics_admin.UpdateAttributionSettingsRequest(), + attribution_settings=resources.AttributionSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[ - client._transport.get_search_ads360_link - ] = mock_rpc - - request = {} - client.get_search_ads360_link(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_search_ads360_link(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 -def test_get_search_ads360_link_rest_required_fields( - request_type=analytics_admin.GetSearchAds360LinkRequest, -): - transport_class = transports.AnalyticsAdminServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_update_attribution_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_search_ads360_link._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_search_ads360_link._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.RunAccessReportRequest, + dict, + ], +) +def test_run_access_report_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) + + # send a request that will satisfy transcoding + request_init = {"entity": "properties/sample1"} request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.RunAccessReportResponse( + row_count=992, + ) - response_value = Response() - response_value.status_code = 200 + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.RunAccessReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.run_access_report(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 - response = client.get_search_ads360_link(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +def test_run_access_report_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_get_search_ads360_link_rest_unset_required_fields(): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Ensure method has been cached + assert client._transport.run_access_report in client._transport._wrapped_methods - unset_fields = transport.get_search_ads360_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.run_access_report + ] = mock_rpc + + request = {} + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_search_ads360_link_rest_interceptors(null_interceptor): +def test_run_access_report_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -83132,14 +93157,14 @@ def test_get_search_ads360_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_search_ads360_link" + transports.AnalyticsAdminServiceRestInterceptor, "post_run_access_report" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_search_ads360_link" + transports.AnalyticsAdminServiceRestInterceptor, "pre_run_access_report" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetSearchAds360LinkRequest.pb( - analytics_admin.GetSearchAds360LinkRequest() + pb_message = analytics_admin.RunAccessReportRequest.pb( + analytics_admin.RunAccessReportRequest() ) transcode.return_value = { "method": "post", @@ -83151,19 +93176,19 @@ def test_get_search_ads360_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.SearchAds360Link.to_json( - resources.SearchAds360Link() + req.return_value._content = analytics_admin.RunAccessReportResponse.to_json( + analytics_admin.RunAccessReportResponse() ) - request = analytics_admin.GetSearchAds360LinkRequest() + request = analytics_admin.RunAccessReportRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SearchAds360Link() + post.return_value = analytics_admin.RunAccessReportResponse() - client.get_search_ads360_link( + client.run_access_report( request, metadata=[ ("key", "val"), @@ -83175,8 +93200,8 @@ def test_get_search_ads360_link_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_search_ads360_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetSearchAds360LinkRequest +def test_run_access_report_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.RunAccessReportRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -83184,7 +93209,7 @@ def test_get_search_ads360_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/searchAds360Links/sample2"} + request_init = {"entity": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -83196,67 +93221,10 @@ def test_get_search_ads360_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_search_ads360_link(request) - - -def test_get_search_ads360_link_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/searchAds360Links/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_search_ads360_link(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=properties/*/searchAds360Links/*}" - % client.transport._host, - args[1], - ) - - -def test_get_search_ads360_link_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_search_ads360_link( - analytics_admin.GetSearchAds360LinkRequest(), - name="name_value", - ) + client.run_access_report(request) -def test_get_search_ads360_link_rest_error(): +def test_run_access_report_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -83265,44 +93233,121 @@ def test_get_search_ads360_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListSearchAds360LinksRequest, + analytics_admin.CreateAccessBindingRequest, dict, ], ) -def test_list_search_ads360_links_rest(request_type): +def test_create_access_binding_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"parent": "accounts/sample1"} + request_init["access_binding"] = { + "user": "user_value", + "name": "name_value", + "roles": ["roles_value1", "roles_value2"], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateAccessBindingRequest.meta.fields[ + "access_binding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["access_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["access_binding"][field])): + del request_init["access_binding"][field][i][subfield] + else: + del request_init["access_binding"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListSearchAds360LinksResponse( - next_page_token="next_page_token_value", + return_value = resources.AccessBinding( + name="name_value", + roles=["roles_value"], + user="user_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) + return_value = resources.AccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_search_ads360_links(request) + response = client.create_access_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSearchAds360LinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] -def test_list_search_ads360_links_rest_use_cached_wrapped_rpc(): +def test_create_access_binding_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -83317,7 +93362,7 @@ def test_list_search_ads360_links_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_search_ads360_links + client._transport.create_access_binding in client._transport._wrapped_methods ) @@ -83327,24 +93372,24 @@ def test_list_search_ads360_links_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_search_ads360_links + client._transport.create_access_binding ] = mock_rpc request = {} - client.list_search_ads360_links(request) + client.create_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_search_ads360_links(request) + client.create_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_search_ads360_links_rest_required_fields( - request_type=analytics_admin.ListSearchAds360LinksRequest, +def test_create_access_binding_rest_required_fields( + request_type=analytics_admin.CreateAccessBindingRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -83360,7 +93405,7 @@ def test_list_search_ads360_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_search_ads360_links._get_unset_required_fields(jsonified_request) + ).create_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -83369,14 +93414,7 @@ def test_list_search_ads360_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_search_ads360_links._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).create_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -83390,7 +93428,7 @@ def test_list_search_ads360_links_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListSearchAds360LinksResponse() + return_value = resources.AccessBinding() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -83402,49 +93440,48 @@ def test_list_search_ads360_links_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListSearchAds360LinksResponse.pb( - return_value - ) + return_value = resources.AccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_search_ads360_links(request) + response = client.create_access_binding(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_search_ads360_links_rest_unset_required_fields(): +def test_create_access_binding_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_search_ads360_links._get_unset_required_fields({}) + unset_fields = transport.create_access_binding._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "parent", + "accessBinding", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_search_ads360_links_rest_interceptors(null_interceptor): +def test_create_access_binding_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -83457,14 +93494,14 @@ def test_list_search_ads360_links_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_search_ads360_links" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_access_binding" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_search_ads360_links" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_access_binding" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListSearchAds360LinksRequest.pb( - analytics_admin.ListSearchAds360LinksRequest() + pb_message = analytics_admin.CreateAccessBindingRequest.pb( + analytics_admin.CreateAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -83476,21 +93513,19 @@ def test_list_search_ads360_links_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListSearchAds360LinksResponse.to_json( - analytics_admin.ListSearchAds360LinksResponse() - ) + req.return_value._content = resources.AccessBinding.to_json( + resources.AccessBinding() ) - request = analytics_admin.ListSearchAds360LinksRequest() + request = analytics_admin.CreateAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListSearchAds360LinksResponse() + post.return_value = resources.AccessBinding() - client.list_search_ads360_links( + client.create_access_binding( request, metadata=[ ("key", "val"), @@ -83502,8 +93537,8 @@ def test_list_search_ads360_links_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_search_ads360_links_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListSearchAds360LinksRequest +def test_create_access_binding_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateAccessBindingRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -83511,7 +93546,7 @@ def test_list_search_ads360_links_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -83523,10 +93558,10 @@ def test_list_search_ads360_links_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_search_ads360_links(request) + client.create_access_binding(request) -def test_list_search_ads360_links_rest_flattened(): +def test_create_access_binding_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -83535,14 +93570,15 @@ def test_list_search_ads360_links_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListSearchAds360LinksResponse() + return_value = resources.AccessBinding() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", + access_binding=resources.AccessBinding(user="user_value"), ) mock_args.update(sample_request) @@ -83550,25 +93586,24 @@ def test_list_search_ads360_links_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) + return_value = resources.AccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_search_ads360_links(**mock_args) + client.create_access_binding(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/searchAds360Links" - % client.transport._host, + "%s/v1alpha/{parent=accounts/*}/accessBindings" % client.transport._host, args[1], ) -def test_list_search_ads360_links_rest_flattened_error(transport: str = "rest"): +def test_create_access_binding_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -83577,198 +93612,63 @@ def test_list_search_ads360_links_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_search_ads360_links( - analytics_admin.ListSearchAds360LinksRequest(), + client.create_access_binding( + analytics_admin.CreateAccessBindingRequest(), parent="parent_value", + access_binding=resources.AccessBinding(user="user_value"), ) -def test_list_search_ads360_links_rest_pager(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - resources.SearchAds360Link(), - ], - next_page_token="abc", - ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[], - next_page_token="def", - ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - ], - next_page_token="ghi", - ), - analytics_admin.ListSearchAds360LinksResponse( - search_ads_360_links=[ - resources.SearchAds360Link(), - resources.SearchAds360Link(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListSearchAds360LinksResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_search_ads360_links(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.SearchAds360Link) for i in results) - - pages = list(client.list_search_ads360_links(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.CreateSearchAds360LinkRequest, - dict, - ], -) -def test_create_search_ads360_link_rest(request_type): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["search_ads_360_link"] = { - "name": "name_value", - "advertiser_id": "advertiser_id_value", - "campaign_data_sharing_enabled": {"value": True}, - "cost_data_sharing_enabled": {}, - "advertiser_display_name": "advertiser_display_name_value", - "ads_personalization_enabled": {}, - "site_stats_sharing_enabled": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateSearchAds360LinkRequest.meta.fields[ - "search_ads_360_link" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["search_ads_360_link"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["search_ads_360_link"][field])): - del request_init["search_ads_360_link"][field][i][subfield] - else: - del request_init["search_ads_360_link"][field][subfield] +def test_create_access_binding_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetAccessBindingRequest, + dict, + ], +) +def test_get_access_binding_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "accounts/sample1/accessBindings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link( + return_value = resources.AccessBinding( name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", + roles=["roles_value"], + user="user_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) + return_value = resources.AccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_search_ads360_link(request) + response = client.get_access_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) + assert isinstance(response, resources.AccessBinding) assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response.roles == ["roles_value"] -def test_create_search_ads360_link_rest_use_cached_wrapped_rpc(): +def test_get_access_binding_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -83783,8 +93683,7 @@ def test_create_search_ads360_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_search_ads360_link - in client._transport._wrapped_methods + client._transport.get_access_binding in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -83793,29 +93692,29 @@ def test_create_search_ads360_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_search_ads360_link + client._transport.get_access_binding ] = mock_rpc request = {} - client.create_search_ads360_link(request) + client.get_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_search_ads360_link(request) + client.get_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_search_ads360_link_rest_required_fields( - request_type=analytics_admin.CreateSearchAds360LinkRequest, +def test_get_access_binding_rest_required_fields( + request_type=analytics_admin.GetAccessBindingRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -83826,21 +93725,21 @@ def test_create_search_ads360_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_search_ads360_link._get_unset_required_fields(jsonified_request) + ).get_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_search_ads360_link._get_unset_required_fields(jsonified_request) + ).get_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -83849,7 +93748,7 @@ def test_create_search_ads360_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link() + return_value = resources.AccessBinding() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -83861,48 +93760,39 @@ def test_create_search_ads360_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) + return_value = resources.AccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_search_ads360_link(request) + response = client.get_access_binding(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_search_ads360_link_rest_unset_required_fields(): +def test_get_access_binding_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_search_ads360_link._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "searchAds360Link", - ) - ) - ) + unset_fields = transport.get_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_search_ads360_link_rest_interceptors(null_interceptor): +def test_get_access_binding_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -83915,15 +93805,14 @@ def test_create_search_ads360_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_create_search_ads360_link", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_access_binding" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_search_ads360_link" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_access_binding" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateSearchAds360LinkRequest.pb( - analytics_admin.CreateSearchAds360LinkRequest() + pb_message = analytics_admin.GetAccessBindingRequest.pb( + analytics_admin.GetAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -83935,19 +93824,19 @@ def test_create_search_ads360_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.SearchAds360Link.to_json( - resources.SearchAds360Link() + req.return_value._content = resources.AccessBinding.to_json( + resources.AccessBinding() ) - request = analytics_admin.CreateSearchAds360LinkRequest() + request = analytics_admin.GetAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SearchAds360Link() + post.return_value = resources.AccessBinding() - client.create_search_ads360_link( + client.get_access_binding( request, metadata=[ ("key", "val"), @@ -83959,8 +93848,8 @@ def test_create_search_ads360_link_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_search_ads360_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateSearchAds360LinkRequest +def test_get_access_binding_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetAccessBindingRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -83968,7 +93857,7 @@ def test_create_search_ads360_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "accounts/sample1/accessBindings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -83980,10 +93869,10 @@ def test_create_search_ads360_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_search_ads360_link(request) + client.get_access_binding(request) -def test_create_search_ads360_link_rest_flattened(): +def test_get_access_binding_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -83992,15 +93881,14 @@ def test_create_search_ads360_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link() + return_value = resources.AccessBinding() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"name": "accounts/sample1/accessBindings/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - search_ads_360_link=resources.SearchAds360Link(name="name_value"), + name="name_value", ) mock_args.update(sample_request) @@ -84008,25 +93896,24 @@ def test_create_search_ads360_link_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) + return_value = resources.AccessBinding.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_search_ads360_link(**mock_args) + client.get_access_binding(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/searchAds360Links" - % client.transport._host, + "%s/v1alpha/{name=accounts/*/accessBindings/*}" % client.transport._host, args[1], ) -def test_create_search_ads360_link_rest_flattened_error(transport: str = "rest"): +def test_get_access_binding_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -84035,14 +93922,13 @@ def test_create_search_ads360_link_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_search_ads360_link( - analytics_admin.CreateSearchAds360LinkRequest(), - parent="parent_value", - search_ads_360_link=resources.SearchAds360Link(name="name_value"), + client.get_access_binding( + analytics_admin.GetAccessBindingRequest(), + name="name_value", ) -def test_create_search_ads360_link_rest_error(): +def test_get_access_binding_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -84051,39 +93937,123 @@ def test_create_search_ads360_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteSearchAds360LinkRequest, + analytics_admin.UpdateAccessBindingRequest, dict, ], ) -def test_delete_search_ads360_link_rest(request_type): +def test_update_access_binding_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/searchAds360Links/sample2"} + request_init = { + "access_binding": {"name": "accounts/sample1/accessBindings/sample2"} + } + request_init["access_binding"] = { + "user": "user_value", + "name": "accounts/sample1/accessBindings/sample2", + "roles": ["roles_value1", "roles_value2"], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateAccessBindingRequest.meta.fields[ + "access_binding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["access_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["access_binding"][field])): + del request_init["access_binding"][field][i][subfield] + else: + del request_init["access_binding"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.AccessBinding( + name="name_value", + roles=["roles_value"], + user="user_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.AccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_search_ads360_link(request) + response = client.update_access_binding(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.AccessBinding) + assert response.name == "name_value" + assert response.roles == ["roles_value"] -def test_delete_search_ads360_link_rest_use_cached_wrapped_rpc(): +def test_update_access_binding_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -84098,7 +94068,7 @@ def test_delete_search_ads360_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_search_ads360_link + client._transport.update_access_binding in client._transport._wrapped_methods ) @@ -84108,29 +94078,28 @@ def test_delete_search_ads360_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_search_ads360_link + client._transport.update_access_binding ] = mock_rpc request = {} - client.delete_search_ads360_link(request) + client.update_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_search_ads360_link(request) + client.update_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_search_ads360_link_rest_required_fields( - request_type=analytics_admin.DeleteSearchAds360LinkRequest, +def test_update_access_binding_rest_required_fields( + request_type=analytics_admin.UpdateAccessBindingRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -84141,21 +94110,17 @@ def test_delete_search_ads360_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_search_ads360_link._get_unset_required_fields(jsonified_request) + ).update_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_search_ads360_link._get_unset_required_fields(jsonified_request) + ).update_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -84164,7 +94129,7 @@ def test_delete_search_ads360_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.AccessBinding() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -84176,36 +94141,40 @@ def test_delete_search_ads360_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.AccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_search_ads360_link(request) + response = client.update_access_binding(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_search_ads360_link_rest_unset_required_fields(): +def test_update_access_binding_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_search_ads360_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("accessBinding",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_search_ads360_link_rest_interceptors(null_interceptor): +def test_update_access_binding_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -84218,11 +94187,14 @@ def test_delete_search_ads360_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_search_ads360_link" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_access_binding" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_access_binding" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteSearchAds360LinkRequest.pb( - analytics_admin.DeleteSearchAds360LinkRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateAccessBindingRequest.pb( + analytics_admin.UpdateAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -84234,15 +94206,19 @@ def test_delete_search_ads360_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.AccessBinding.to_json( + resources.AccessBinding() + ) - request = analytics_admin.DeleteSearchAds360LinkRequest() + request = analytics_admin.UpdateAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.AccessBinding() - client.delete_search_ads360_link( + client.update_access_binding( request, metadata=[ ("key", "val"), @@ -84251,10 +94227,11 @@ def test_delete_search_ads360_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_search_ads360_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteSearchAds360LinkRequest +def test_update_access_binding_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateAccessBindingRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -84262,7 +94239,9 @@ def test_delete_search_ads360_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/searchAds360Links/sample2"} + request_init = { + "access_binding": {"name": "accounts/sample1/accessBindings/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -84274,10 +94253,10 @@ def test_delete_search_ads360_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_search_ads360_link(request) + client.update_access_binding(request) -def test_delete_search_ads360_link_rest_flattened(): +def test_update_access_binding_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -84286,38 +94265,42 @@ def test_delete_search_ads360_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.AccessBinding() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/searchAds360Links/sample2"} + sample_request = { + "access_binding": {"name": "accounts/sample1/accessBindings/sample2"} + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + access_binding=resources.AccessBinding(user="user_value"), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.AccessBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_search_ads360_link(**mock_args) + client.update_access_binding(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/searchAds360Links/*}" + "%s/v1alpha/{access_binding.name=accounts/*/accessBindings/*}" % client.transport._host, args[1], ) -def test_delete_search_ads360_link_rest_flattened_error(transport: str = "rest"): +def test_update_access_binding_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -84326,13 +94309,13 @@ def test_delete_search_ads360_link_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_search_ads360_link( - analytics_admin.DeleteSearchAds360LinkRequest(), - name="name_value", + client.update_access_binding( + analytics_admin.UpdateAccessBindingRequest(), + access_binding=resources.AccessBinding(user="user_value"), ) -def test_delete_search_ads360_link_rest_error(): +def test_update_access_binding_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -84341,128 +94324,39 @@ def test_delete_search_ads360_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateSearchAds360LinkRequest, + analytics_admin.DeleteAccessBindingRequest, dict, ], ) -def test_update_search_ads360_link_rest(request_type): +def test_delete_access_binding_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "search_ads_360_link": {"name": "properties/sample1/searchAds360Links/sample2"} - } - request_init["search_ads_360_link"] = { - "name": "properties/sample1/searchAds360Links/sample2", - "advertiser_id": "advertiser_id_value", - "campaign_data_sharing_enabled": {"value": True}, - "cost_data_sharing_enabled": {}, - "advertiser_display_name": "advertiser_display_name_value", - "ads_personalization_enabled": {}, - "site_stats_sharing_enabled": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateSearchAds360LinkRequest.meta.fields[ - "search_ads_360_link" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["search_ads_360_link"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["search_ads_360_link"][field])): - del request_init["search_ads_360_link"][field][i][subfield] - else: - del request_init["search_ads_360_link"][field][subfield] + request_init = {"name": "accounts/sample1/accessBindings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link( - name="name_value", - advertiser_id="advertiser_id_value", - advertiser_display_name="advertiser_display_name_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_search_ads360_link(request) + response = client.delete_access_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.SearchAds360Link) - assert response.name == "name_value" - assert response.advertiser_id == "advertiser_id_value" - assert response.advertiser_display_name == "advertiser_display_name_value" + assert response is None -def test_update_search_ads360_link_rest_use_cached_wrapped_rpc(): +def test_delete_access_binding_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -84477,7 +94371,7 @@ def test_update_search_ads360_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_search_ads360_link + client._transport.delete_access_binding in client._transport._wrapped_methods ) @@ -84487,28 +94381,29 @@ def test_update_search_ads360_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_search_ads360_link + client._transport.delete_access_binding ] = mock_rpc request = {} - client.update_search_ads360_link(request) + client.delete_access_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_search_ads360_link(request) + client.delete_access_binding(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_search_ads360_link_rest_required_fields( - request_type=analytics_admin.UpdateSearchAds360LinkRequest, +def test_delete_access_binding_rest_required_fields( + request_type=analytics_admin.DeleteAccessBindingRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -84519,19 +94414,21 @@ def test_update_search_ads360_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_search_ads360_link._get_unset_required_fields(jsonified_request) + ).delete_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_search_ads360_link._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).delete_access_binding._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -84540,7 +94437,7 @@ def test_update_search_ads360_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -84552,40 +94449,36 @@ def test_update_search_ads360_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_search_ads360_link(request) + response = client.delete_access_binding(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_search_ads360_link_rest_unset_required_fields(): +def test_delete_access_binding_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_search_ads360_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + unset_fields = transport.delete_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_search_ads360_link_rest_interceptors(null_interceptor): +def test_delete_access_binding_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -84598,15 +94491,11 @@ def test_update_search_ads360_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_update_search_ads360_link", - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_search_ads360_link" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_access_binding" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateSearchAds360LinkRequest.pb( - analytics_admin.UpdateSearchAds360LinkRequest() + pb_message = analytics_admin.DeleteAccessBindingRequest.pb( + analytics_admin.DeleteAccessBindingRequest() ) transcode.return_value = { "method": "post", @@ -84618,19 +94507,15 @@ def test_update_search_ads360_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.SearchAds360Link.to_json( - resources.SearchAds360Link() - ) - request = analytics_admin.UpdateSearchAds360LinkRequest() + request = analytics_admin.DeleteAccessBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SearchAds360Link() - client.update_search_ads360_link( + client.delete_access_binding( request, metadata=[ ("key", "val"), @@ -84639,11 +94524,10 @@ def test_update_search_ads360_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_search_ads360_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateSearchAds360LinkRequest +def test_delete_access_binding_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteAccessBindingRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -84651,9 +94535,7 @@ def test_update_search_ads360_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "search_ads_360_link": {"name": "properties/sample1/searchAds360Links/sample2"} - } + request_init = {"name": "accounts/sample1/accessBindings/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -84665,10 +94547,10 @@ def test_update_search_ads360_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_search_ads360_link(request) + client.delete_access_binding(request) -def test_update_search_ads360_link_rest_flattened(): +def test_delete_access_binding_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -84677,45 +94559,37 @@ def test_update_search_ads360_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SearchAds360Link() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "search_ads_360_link": { - "name": "properties/sample1/searchAds360Links/sample2" - } - } + sample_request = {"name": "accounts/sample1/accessBindings/sample2"} # get truthy value for each flattened field mock_args = dict( - search_ads_360_link=resources.SearchAds360Link(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.SearchAds360Link.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_search_ads360_link(**mock_args) + client.delete_access_binding(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{search_ads_360_link.name=properties/*/searchAds360Links/*}" - % client.transport._host, + "%s/v1alpha/{name=accounts/*/accessBindings/*}" % client.transport._host, args[1], ) -def test_update_search_ads360_link_rest_flattened_error(transport: str = "rest"): +def test_delete_access_binding_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -84724,14 +94598,13 @@ def test_update_search_ads360_link_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_search_ads360_link( - analytics_admin.UpdateSearchAds360LinkRequest(), - search_ads_360_link=resources.SearchAds360Link(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_access_binding( + analytics_admin.DeleteAccessBindingRequest(), + name="name_value", ) -def test_update_search_ads360_link_rest_error(): +def test_delete_access_binding_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -84740,64 +94613,44 @@ def test_update_search_ads360_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAttributionSettingsRequest, + analytics_admin.ListAccessBindingsRequest, dict, ], ) -def test_get_attribution_settings_rest(request_type): +def test_list_access_bindings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/attributionSettings"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AttributionSettings( - name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + return_value = analytics_admin.ListAccessBindingsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AttributionSettings.pb(return_value) + return_value = analytics_admin.ListAccessBindingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_attribution_settings(request) + response = client.list_access_bindings(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AttributionSettings) - assert response.name == "name_value" - assert ( - response.acquisition_conversion_event_lookback_window - == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS - ) - assert ( - response.other_conversion_event_lookback_window - == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS - ) - assert ( - response.reporting_attribution_model - == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN - ) - assert ( - response.ads_web_conversion_data_export_scope - == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET - ) + assert isinstance(response, pagers.ListAccessBindingsPager) + assert response.next_page_token == "next_page_token_value" -def test_get_attribution_settings_rest_use_cached_wrapped_rpc(): +def test_list_access_bindings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -84812,8 +94665,7 @@ def test_get_attribution_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_attribution_settings - in client._transport._wrapped_methods + client._transport.list_access_bindings in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -84822,29 +94674,29 @@ def test_get_attribution_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_attribution_settings + client._transport.list_access_bindings ] = mock_rpc request = {} - client.get_attribution_settings(request) + client.list_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_attribution_settings(request) + client.list_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_attribution_settings_rest_required_fields( - request_type=analytics_admin.GetAttributionSettingsRequest, +def test_list_access_bindings_rest_required_fields( + request_type=analytics_admin.ListAccessBindingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -84855,21 +94707,28 @@ def test_get_attribution_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_attribution_settings._get_unset_required_fields(jsonified_request) + ).list_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_attribution_settings._get_unset_required_fields(jsonified_request) + ).list_access_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -84878,7 +94737,7 @@ def test_get_attribution_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AttributionSettings() + return_value = analytics_admin.ListAccessBindingsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -84899,30 +94758,38 @@ def test_get_attribution_settings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AttributionSettings.pb(return_value) + return_value = analytics_admin.ListAccessBindingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_attribution_settings(request) + response = client.list_access_bindings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_attribution_settings_rest_unset_required_fields(): +def test_list_access_bindings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_attribution_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_attribution_settings_rest_interceptors(null_interceptor): +def test_list_access_bindings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -84935,14 +94802,14 @@ def test_get_attribution_settings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_attribution_settings" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_access_bindings" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_attribution_settings" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_access_bindings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetAttributionSettingsRequest.pb( - analytics_admin.GetAttributionSettingsRequest() + pb_message = analytics_admin.ListAccessBindingsRequest.pb( + analytics_admin.ListAccessBindingsRequest() ) transcode.return_value = { "method": "post", @@ -84954,19 +94821,19 @@ def test_get_attribution_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AttributionSettings.to_json( - resources.AttributionSettings() + req.return_value._content = analytics_admin.ListAccessBindingsResponse.to_json( + analytics_admin.ListAccessBindingsResponse() ) - request = analytics_admin.GetAttributionSettingsRequest() + request = analytics_admin.ListAccessBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AttributionSettings() + post.return_value = analytics_admin.ListAccessBindingsResponse() - client.get_attribution_settings( + client.list_access_bindings( request, metadata=[ ("key", "val"), @@ -84978,8 +94845,8 @@ def test_get_attribution_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_attribution_settings_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetAttributionSettingsRequest +def test_list_access_bindings_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListAccessBindingsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -84987,7 +94854,7 @@ def test_get_attribution_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/attributionSettings"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -84999,10 +94866,10 @@ def test_get_attribution_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_attribution_settings(request) + client.list_access_bindings(request) -def test_get_attribution_settings_rest_flattened(): +def test_list_access_bindings_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -85011,14 +94878,14 @@ def test_get_attribution_settings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AttributionSettings() + return_value = analytics_admin.ListAccessBindingsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/attributionSettings"} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) @@ -85026,25 +94893,24 @@ def test_get_attribution_settings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AttributionSettings.pb(return_value) + return_value = analytics_admin.ListAccessBindingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_attribution_settings(**mock_args) + client.list_access_bindings(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/attributionSettings}" - % client.transport._host, + "%s/v1alpha/{parent=accounts/*}/accessBindings" % client.transport._host, args[1], ) -def test_get_attribution_settings_rest_flattened_error(transport: str = "rest"): +def test_list_access_bindings_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -85053,159 +94919,115 @@ def test_get_attribution_settings_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_attribution_settings( - analytics_admin.GetAttributionSettingsRequest(), - name="name_value", + client.list_access_bindings( + analytics_admin.ListAccessBindingsRequest(), + parent="parent_value", ) -def test_get_attribution_settings_rest_error(): +def test_list_access_bindings_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), + ], + next_page_token="abc", + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], + next_page_token="def", + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListAccessBindingsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "accounts/sample1"} + + pager = client.list_access_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccessBinding) for i in results) + + pages = list(client.list_access_bindings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAttributionSettingsRequest, + analytics_admin.BatchCreateAccessBindingsRequest, dict, ], ) -def test_update_attribution_settings_rest(request_type): +def test_batch_create_access_bindings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "attribution_settings": {"name": "properties/sample1/attributionSettings"} - } - request_init["attribution_settings"] = { - "name": "properties/sample1/attributionSettings", - "acquisition_conversion_event_lookback_window": 1, - "other_conversion_event_lookback_window": 1, - "reporting_attribution_model": 1, - "ads_web_conversion_data_export_scope": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateAttributionSettingsRequest.meta.fields[ - "attribution_settings" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "attribution_settings" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["attribution_settings"][field])): - del request_init["attribution_settings"][field][i][subfield] - else: - del request_init["attribution_settings"][field][subfield] + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AttributionSettings( - name="name_value", - acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, - other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, - reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, - ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, - ) + return_value = analytics_admin.BatchCreateAccessBindingsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AttributionSettings.pb(return_value) + return_value = analytics_admin.BatchCreateAccessBindingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_attribution_settings(request) + response = client.batch_create_access_bindings(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AttributionSettings) - assert response.name == "name_value" - assert ( - response.acquisition_conversion_event_lookback_window - == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS - ) - assert ( - response.other_conversion_event_lookback_window - == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS - ) - assert ( - response.reporting_attribution_model - == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN - ) - assert ( - response.ads_web_conversion_data_export_scope - == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET - ) + assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) -def test_update_attribution_settings_rest_use_cached_wrapped_rpc(): +def test_batch_create_access_bindings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -85220,7 +95042,7 @@ def test_update_attribution_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_attribution_settings + client._transport.batch_create_access_bindings in client._transport._wrapped_methods ) @@ -85230,28 +95052,29 @@ def test_update_attribution_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_attribution_settings + client._transport.batch_create_access_bindings ] = mock_rpc request = {} - client.update_attribution_settings(request) + client.batch_create_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_attribution_settings(request) + client.batch_create_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_attribution_settings_rest_required_fields( - request_type=analytics_admin.UpdateAttributionSettingsRequest, +def test_batch_create_access_bindings_rest_required_fields( + request_type=analytics_admin.BatchCreateAccessBindingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -85262,19 +95085,21 @@ def test_update_attribution_settings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_attribution_settings._get_unset_required_fields(jsonified_request) + ).batch_create_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_attribution_settings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).batch_create_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -85283,7 +95108,7 @@ def test_update_attribution_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AttributionSettings() + return_value = analytics_admin.BatchCreateAccessBindingsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -85295,7 +95120,7 @@ def test_update_attribution_settings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -85305,38 +95130,40 @@ def test_update_attribution_settings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AttributionSettings.pb(return_value) + return_value = analytics_admin.BatchCreateAccessBindingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_attribution_settings(request) + response = client.batch_create_access_bindings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_attribution_settings_rest_unset_required_fields(): +def test_batch_create_access_bindings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_attribution_settings._get_unset_required_fields({}) + unset_fields = transport.batch_create_access_bindings._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("updateMask",)) + set(()) & set( ( - "attributionSettings", - "updateMask", + "parent", + "requests", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_attribution_settings_rest_interceptors(null_interceptor): +def test_batch_create_access_bindings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -85350,15 +95177,15 @@ def test_update_attribution_settings_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_update_attribution_settings", + "post_batch_create_access_bindings", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_attribution_settings", + "pre_batch_create_access_bindings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateAttributionSettingsRequest.pb( - analytics_admin.UpdateAttributionSettingsRequest() + pb_message = analytics_admin.BatchCreateAccessBindingsRequest.pb( + analytics_admin.BatchCreateAccessBindingsRequest() ) transcode.return_value = { "method": "post", @@ -85370,19 +95197,21 @@ def test_update_attribution_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AttributionSettings.to_json( - resources.AttributionSettings() + req.return_value._content = ( + analytics_admin.BatchCreateAccessBindingsResponse.to_json( + analytics_admin.BatchCreateAccessBindingsResponse() + ) ) - request = analytics_admin.UpdateAttributionSettingsRequest() + request = analytics_admin.BatchCreateAccessBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AttributionSettings() + post.return_value = analytics_admin.BatchCreateAccessBindingsResponse() - client.update_attribution_settings( + client.batch_create_access_bindings( request, metadata=[ ("key", "val"), @@ -85394,95 +95223,32 @@ def test_update_attribution_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_attribution_settings_rest_bad_request( +def test_batch_create_access_bindings_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.UpdateAttributionSettingsRequest, -): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "attribution_settings": {"name": "properties/sample1/attributionSettings"} - } - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_attribution_settings(request) - - -def test_update_attribution_settings_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.AttributionSettings() - - # get arguments that satisfy an http rule for this method - sample_request = { - "attribution_settings": {"name": "properties/sample1/attributionSettings"} - } - - # get truthy value for each flattened field - mock_args = dict( - attribution_settings=resources.AttributionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.AttributionSettings.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_attribution_settings(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{attribution_settings.name=properties/*/attributionSettings}" - % client.transport._host, - args[1], - ) - - -def test_update_attribution_settings_rest_flattened_error(transport: str = "rest"): + request_type=analytics_admin.BatchCreateAccessBindingsRequest, +): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_attribution_settings( - analytics_admin.UpdateAttributionSettingsRequest(), - attribution_settings=resources.AttributionSettings(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + # send a request that will satisfy transcoding + request_init = {"parent": "accounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_access_bindings(request) -def test_update_attribution_settings_rest_error(): +def test_batch_create_access_bindings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -85491,44 +95257,41 @@ def test_update_attribution_settings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.RunAccessReportRequest, + analytics_admin.BatchGetAccessBindingsRequest, dict, ], ) -def test_run_access_report_rest(request_type): +def test_batch_get_access_bindings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"entity": "properties/sample1"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.RunAccessReportResponse( - row_count=992, - ) + return_value = analytics_admin.BatchGetAccessBindingsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.RunAccessReportResponse.pb(return_value) + return_value = analytics_admin.BatchGetAccessBindingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.run_access_report(request) + response = client.batch_get_access_bindings(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.RunAccessReportResponse) - assert response.row_count == 992 + assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) -def test_run_access_report_rest_use_cached_wrapped_rpc(): +def test_batch_get_access_bindings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -85542,7 +95305,10 @@ def test_run_access_report_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.run_access_report in client._transport._wrapped_methods + assert ( + client._transport.batch_get_access_bindings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -85550,24 +95316,132 @@ def test_run_access_report_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.run_access_report + client._transport.batch_get_access_bindings ] = mock_rpc request = {} - client.run_access_report(request) + client.batch_get_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.run_access_report(request) + client.batch_get_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 +def test_batch_get_access_bindings_rest_required_fields( + request_type=analytics_admin.BatchGetAccessBindingsRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "names" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_get_access_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "names" in jsonified_request + assert jsonified_request["names"] == request_init["names"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["names"] = "names_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_get_access_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("names",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "names" in jsonified_request + assert jsonified_request["names"] == "names_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.BatchGetAccessBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = analytics_admin.BatchGetAccessBindingsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.batch_get_access_bindings(request) + + expected_params = [ + ( + "names", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_get_access_bindings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_get_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("names",)) + & set( + ( + "parent", + "names", + ) + ) + ) + + @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_run_access_report_rest_interceptors(null_interceptor): +def test_batch_get_access_bindings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -85580,14 +95454,15 @@ def test_run_access_report_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_run_access_report" + transports.AnalyticsAdminServiceRestInterceptor, + "post_batch_get_access_bindings", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_run_access_report" + transports.AnalyticsAdminServiceRestInterceptor, "pre_batch_get_access_bindings" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.RunAccessReportRequest.pb( - analytics_admin.RunAccessReportRequest() + pb_message = analytics_admin.BatchGetAccessBindingsRequest.pb( + analytics_admin.BatchGetAccessBindingsRequest() ) transcode.return_value = { "method": "post", @@ -85599,19 +95474,21 @@ def test_run_access_report_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.RunAccessReportResponse.to_json( - analytics_admin.RunAccessReportResponse() + req.return_value._content = ( + analytics_admin.BatchGetAccessBindingsResponse.to_json( + analytics_admin.BatchGetAccessBindingsResponse() + ) ) - request = analytics_admin.RunAccessReportRequest() + request = analytics_admin.BatchGetAccessBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.RunAccessReportResponse() + post.return_value = analytics_admin.BatchGetAccessBindingsResponse() - client.run_access_report( + client.batch_get_access_bindings( request, metadata=[ ("key", "val"), @@ -85623,8 +95500,8 @@ def test_run_access_report_rest_interceptors(null_interceptor): post.assert_called_once() -def test_run_access_report_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.RunAccessReportRequest +def test_batch_get_access_bindings_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.BatchGetAccessBindingsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -85632,7 +95509,7 @@ def test_run_access_report_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"entity": "properties/sample1"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -85644,10 +95521,10 @@ def test_run_access_report_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.run_access_report(request) + client.batch_get_access_bindings(request) -def test_run_access_report_rest_error(): +def test_batch_get_access_bindings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -85656,11 +95533,11 @@ def test_run_access_report_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateAccessBindingRequest, + analytics_admin.BatchUpdateAccessBindingsRequest, dict, ], ) -def test_create_access_binding_rest(request_type): +def test_batch_update_access_bindings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -85668,109 +95545,31 @@ def test_create_access_binding_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "accounts/sample1"} - request_init["access_binding"] = { - "user": "user_value", - "name": "name_value", - "roles": ["roles_value1", "roles_value2"], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateAccessBindingRequest.meta.fields[ - "access_binding" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["access_binding"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["access_binding"][field])): - del request_init["access_binding"][field][i][subfield] - else: - del request_init["access_binding"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding( - name="name_value", - roles=["roles_value"], - user="user_value", - ) + return_value = analytics_admin.BatchUpdateAccessBindingsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) + return_value = analytics_admin.BatchUpdateAccessBindingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_access_binding(request) + response = client.batch_update_access_bindings(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) - assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) -def test_create_access_binding_rest_use_cached_wrapped_rpc(): +def test_batch_update_access_bindings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -85785,7 +95584,7 @@ def test_create_access_binding_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_access_binding + client._transport.batch_update_access_bindings in client._transport._wrapped_methods ) @@ -85795,24 +95594,24 @@ def test_create_access_binding_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_access_binding + client._transport.batch_update_access_bindings ] = mock_rpc request = {} - client.create_access_binding(request) + client.batch_update_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_access_binding(request) + client.batch_update_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_access_binding_rest_required_fields( - request_type=analytics_admin.CreateAccessBindingRequest, +def test_batch_update_access_bindings_rest_required_fields( + request_type=analytics_admin.BatchUpdateAccessBindingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -85828,7 +95627,7 @@ def test_create_access_binding_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_access_binding._get_unset_required_fields(jsonified_request) + ).batch_update_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -85837,7 +95636,7 @@ def test_create_access_binding_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_access_binding._get_unset_required_fields(jsonified_request) + ).batch_update_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -85851,7 +95650,7 @@ def test_create_access_binding_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding() + return_value = analytics_admin.BatchUpdateAccessBindingsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -85873,38 +95672,40 @@ def test_create_access_binding_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) + return_value = analytics_admin.BatchUpdateAccessBindingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_access_binding(request) + response = client.batch_update_access_bindings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_access_binding_rest_unset_required_fields(): +def test_batch_update_access_bindings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_access_binding._get_unset_required_fields({}) + unset_fields = transport.batch_update_access_bindings._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "parent", - "accessBinding", + "requests", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_access_binding_rest_interceptors(null_interceptor): +def test_batch_update_access_bindings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -85917,14 +95718,16 @@ def test_create_access_binding_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_access_binding" + transports.AnalyticsAdminServiceRestInterceptor, + "post_batch_update_access_bindings", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_access_binding" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_batch_update_access_bindings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateAccessBindingRequest.pb( - analytics_admin.CreateAccessBindingRequest() + pb_message = analytics_admin.BatchUpdateAccessBindingsRequest.pb( + analytics_admin.BatchUpdateAccessBindingsRequest() ) transcode.return_value = { "method": "post", @@ -85936,19 +95739,21 @@ def test_create_access_binding_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AccessBinding.to_json( - resources.AccessBinding() + req.return_value._content = ( + analytics_admin.BatchUpdateAccessBindingsResponse.to_json( + analytics_admin.BatchUpdateAccessBindingsResponse() + ) ) - request = analytics_admin.CreateAccessBindingRequest() + request = analytics_admin.BatchUpdateAccessBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AccessBinding() + post.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() - client.create_access_binding( + client.batch_update_access_bindings( request, metadata=[ ("key", "val"), @@ -85960,8 +95765,9 @@ def test_create_access_binding_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_access_binding_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateAccessBindingRequest +def test_batch_update_access_bindings_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.BatchUpdateAccessBindingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -85981,68 +95787,10 @@ def test_create_access_binding_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_access_binding(request) - - -def test_create_access_binding_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "accounts/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - access_binding=resources.AccessBinding(user="user_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_access_binding(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=accounts/*}/accessBindings" % client.transport._host, - args[1], - ) - - -def test_create_access_binding_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_access_binding( - analytics_admin.CreateAccessBindingRequest(), - parent="parent_value", - access_binding=resources.AccessBinding(user="user_value"), - ) + client.batch_update_access_bindings(request) -def test_create_access_binding_rest_error(): +def test_batch_update_access_bindings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -86051,47 +95799,39 @@ def test_create_access_binding_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAccessBindingRequest, + analytics_admin.BatchDeleteAccessBindingsRequest, dict, ], ) -def test_get_access_binding_rest(request_type): +def test_batch_delete_access_bindings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1/accessBindings/sample2"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding( - name="name_value", - roles=["roles_value"], - user="user_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_access_binding(request) + response = client.batch_delete_access_bindings(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) - assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert response is None -def test_get_access_binding_rest_use_cached_wrapped_rpc(): +def test_batch_delete_access_bindings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -86106,7 +95846,8 @@ def test_get_access_binding_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_access_binding in client._transport._wrapped_methods + client._transport.batch_delete_access_bindings + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -86115,29 +95856,29 @@ def test_get_access_binding_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_access_binding + client._transport.batch_delete_access_bindings ] = mock_rpc request = {} - client.get_access_binding(request) + client.batch_delete_access_bindings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_access_binding(request) + client.batch_delete_access_bindings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_access_binding_rest_required_fields( - request_type=analytics_admin.GetAccessBindingRequest, +def test_batch_delete_access_bindings_rest_required_fields( + request_type=analytics_admin.BatchDeleteAccessBindingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -86148,21 +95889,21 @@ def test_get_access_binding_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_access_binding._get_unset_required_fields(jsonified_request) + ).batch_delete_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_access_binding._get_unset_required_fields(jsonified_request) + ).batch_delete_access_bindings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -86171,7 +95912,7 @@ def test_get_access_binding_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -86183,39 +95924,45 @@ def test_get_access_binding_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_access_binding(request) + response = client.batch_delete_access_bindings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_access_binding_rest_unset_required_fields(): +def test_batch_delete_access_bindings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_access_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.batch_delete_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_access_binding_rest_interceptors(null_interceptor): +def test_batch_delete_access_bindings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -86228,14 +95975,12 @@ def test_get_access_binding_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_access_binding" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_access_binding" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_batch_delete_access_bindings", ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.GetAccessBindingRequest.pb( - analytics_admin.GetAccessBindingRequest() + pb_message = analytics_admin.BatchDeleteAccessBindingsRequest.pb( + analytics_admin.BatchDeleteAccessBindingsRequest() ) transcode.return_value = { "method": "post", @@ -86247,19 +95992,15 @@ def test_get_access_binding_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AccessBinding.to_json( - resources.AccessBinding() - ) - request = analytics_admin.GetAccessBindingRequest() + request = analytics_admin.BatchDeleteAccessBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AccessBinding() - client.get_access_binding( + client.batch_delete_access_bindings( request, metadata=[ ("key", "val"), @@ -86268,11 +96009,11 @@ def test_get_access_binding_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_get_access_binding_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetAccessBindingRequest +def test_batch_delete_access_bindings_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.BatchDeleteAccessBindingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -86280,7 +96021,7 @@ def test_get_access_binding_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1/accessBindings/sample2"} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -86292,66 +96033,10 @@ def test_get_access_binding_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_access_binding(request) - - -def test_get_access_binding_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "accounts/sample1/accessBindings/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_access_binding(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=accounts/*/accessBindings/*}" % client.transport._host, - args[1], - ) - - -def test_get_access_binding_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_access_binding( - analytics_admin.GetAccessBindingRequest(), - name="name_value", - ) + client.batch_delete_access_bindings(request) -def test_get_access_binding_rest_error(): +def test_batch_delete_access_bindings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -86360,123 +96045,52 @@ def test_get_access_binding_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateAccessBindingRequest, + analytics_admin.GetExpandedDataSetRequest, dict, ], ) -def test_update_access_binding_rest(request_type): +def test_get_expanded_data_set_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "access_binding": {"name": "accounts/sample1/accessBindings/sample2"} - } - request_init["access_binding"] = { - "user": "user_value", - "name": "accounts/sample1/accessBindings/sample2", - "roles": ["roles_value1", "roles_value2"], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateAccessBindingRequest.meta.fields[ - "access_binding" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["access_binding"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["access_binding"][field])): - del request_init["access_binding"][field][i][subfield] - else: - del request_init["access_binding"][field][subfield] + request_init = {"name": "properties/sample1/expandedDataSets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding( + return_value = expanded_data_set.ExpandedDataSet( name="name_value", - roles=["roles_value"], - user="user_value", + display_name="display_name_value", + description="description_value", + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) + return_value = expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_access_binding(request) + response = client.get_expanded_data_set(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AccessBinding) + assert isinstance(response, expanded_data_set.ExpandedDataSet) assert response.name == "name_value" - assert response.roles == ["roles_value"] + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] -def test_update_access_binding_rest_use_cached_wrapped_rpc(): +def test_get_expanded_data_set_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -86491,7 +96105,7 @@ def test_update_access_binding_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_access_binding + client._transport.get_expanded_data_set in client._transport._wrapped_methods ) @@ -86501,28 +96115,29 @@ def test_update_access_binding_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_access_binding + client._transport.get_expanded_data_set ] = mock_rpc request = {} - client.update_access_binding(request) + client.get_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_access_binding(request) + client.get_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_access_binding_rest_required_fields( - request_type=analytics_admin.UpdateAccessBindingRequest, +def test_get_expanded_data_set_rest_required_fields( + request_type=analytics_admin.GetExpandedDataSetRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -86533,17 +96148,21 @@ def test_update_access_binding_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_access_binding._get_unset_required_fields(jsonified_request) + ).get_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_access_binding._get_unset_required_fields(jsonified_request) + ).get_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -86552,7 +96171,7 @@ def test_update_access_binding_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding() + return_value = expanded_data_set.ExpandedDataSet() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -86564,40 +96183,39 @@ def test_update_access_binding_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) + return_value = expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_access_binding(request) + response = client.get_expanded_data_set(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_access_binding_rest_unset_required_fields(): +def test_get_expanded_data_set_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_access_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("accessBinding",))) + unset_fields = transport.get_expanded_data_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_access_binding_rest_interceptors(null_interceptor): +def test_get_expanded_data_set_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -86610,14 +96228,14 @@ def test_update_access_binding_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_access_binding" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_expanded_data_set" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_access_binding" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_expanded_data_set" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateAccessBindingRequest.pb( - analytics_admin.UpdateAccessBindingRequest() + pb_message = analytics_admin.GetExpandedDataSetRequest.pb( + analytics_admin.GetExpandedDataSetRequest() ) transcode.return_value = { "method": "post", @@ -86629,19 +96247,19 @@ def test_update_access_binding_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AccessBinding.to_json( - resources.AccessBinding() + req.return_value._content = expanded_data_set.ExpandedDataSet.to_json( + expanded_data_set.ExpandedDataSet() ) - request = analytics_admin.UpdateAccessBindingRequest() + request = analytics_admin.GetExpandedDataSetRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AccessBinding() + post.return_value = expanded_data_set.ExpandedDataSet() - client.update_access_binding( + client.get_expanded_data_set( request, metadata=[ ("key", "val"), @@ -86653,8 +96271,8 @@ def test_update_access_binding_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_access_binding_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateAccessBindingRequest +def test_get_expanded_data_set_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetExpandedDataSetRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -86662,9 +96280,7 @@ def test_update_access_binding_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "access_binding": {"name": "accounts/sample1/accessBindings/sample2"} - } + request_init = {"name": "properties/sample1/expandedDataSets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -86676,10 +96292,10 @@ def test_update_access_binding_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_access_binding(request) + client.get_expanded_data_set(request) -def test_update_access_binding_rest_flattened(): +def test_get_expanded_data_set_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -86688,16 +96304,14 @@ def test_update_access_binding_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AccessBinding() + return_value = expanded_data_set.ExpandedDataSet() # get arguments that satisfy an http rule for this method - sample_request = { - "access_binding": {"name": "accounts/sample1/accessBindings/sample2"} - } + sample_request = {"name": "properties/sample1/expandedDataSets/sample2"} # get truthy value for each flattened field mock_args = dict( - access_binding=resources.AccessBinding(user="user_value"), + name="name_value", ) mock_args.update(sample_request) @@ -86705,25 +96319,25 @@ def test_update_access_binding_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AccessBinding.pb(return_value) + return_value = expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_access_binding(**mock_args) + client.get_expanded_data_set(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{access_binding.name=accounts/*/accessBindings/*}" + "%s/v1alpha/{name=properties/*/expandedDataSets/*}" % client.transport._host, args[1], ) -def test_update_access_binding_rest_flattened_error(transport: str = "rest"): +def test_get_expanded_data_set_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -86732,13 +96346,13 @@ def test_update_access_binding_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_access_binding( - analytics_admin.UpdateAccessBindingRequest(), - access_binding=resources.AccessBinding(user="user_value"), + client.get_expanded_data_set( + analytics_admin.GetExpandedDataSetRequest(), + name="name_value", ) -def test_update_access_binding_rest_error(): +def test_get_expanded_data_set_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -86747,39 +96361,44 @@ def test_update_access_binding_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteAccessBindingRequest, + analytics_admin.ListExpandedDataSetsRequest, dict, ], ) -def test_delete_access_binding_rest(request_type): +def test_list_expanded_data_sets_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1/accessBindings/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListExpandedDataSetsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_access_binding(request) + response = client.list_expanded_data_sets(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListExpandedDataSetsPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_access_binding_rest_use_cached_wrapped_rpc(): +def test_list_expanded_data_sets_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -86794,7 +96413,7 @@ def test_delete_access_binding_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_access_binding + client._transport.list_expanded_data_sets in client._transport._wrapped_methods ) @@ -86804,29 +96423,29 @@ def test_delete_access_binding_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_access_binding + client._transport.list_expanded_data_sets ] = mock_rpc request = {} - client.delete_access_binding(request) + client.list_expanded_data_sets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_access_binding(request) + client.list_expanded_data_sets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_access_binding_rest_required_fields( - request_type=analytics_admin.DeleteAccessBindingRequest, +def test_list_expanded_data_sets_rest_required_fields( + request_type=analytics_admin.ListExpandedDataSetsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -86837,21 +96456,28 @@ def test_delete_access_binding_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_access_binding._get_unset_required_fields(jsonified_request) + ).list_expanded_data_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_access_binding._get_unset_required_fields(jsonified_request) + ).list_expanded_data_sets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -86860,7 +96486,7 @@ def test_delete_access_binding_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListExpandedDataSetsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -86872,36 +96498,47 @@ def test_delete_access_binding_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_access_binding(request) + response = client.list_expanded_data_sets(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_access_binding_rest_unset_required_fields(): +def test_list_expanded_data_sets_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_access_binding._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.list_expanded_data_sets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_access_binding_rest_interceptors(null_interceptor): +def test_list_expanded_data_sets_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -86914,11 +96551,14 @@ def test_delete_access_binding_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_access_binding" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_expanded_data_sets" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_expanded_data_sets" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteAccessBindingRequest.pb( - analytics_admin.DeleteAccessBindingRequest() + post.assert_not_called() + pb_message = analytics_admin.ListExpandedDataSetsRequest.pb( + analytics_admin.ListExpandedDataSetsRequest() ) transcode.return_value = { "method": "post", @@ -86930,15 +96570,21 @@ def test_delete_access_binding_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = ( + analytics_admin.ListExpandedDataSetsResponse.to_json( + analytics_admin.ListExpandedDataSetsResponse() + ) + ) - request = analytics_admin.DeleteAccessBindingRequest() + request = analytics_admin.ListExpandedDataSetsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = analytics_admin.ListExpandedDataSetsResponse() - client.delete_access_binding( + client.list_expanded_data_sets( request, metadata=[ ("key", "val"), @@ -86947,10 +96593,11 @@ def test_delete_access_binding_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_access_binding_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteAccessBindingRequest +def test_list_expanded_data_sets_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListExpandedDataSetsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -86958,7 +96605,7 @@ def test_delete_access_binding_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "accounts/sample1/accessBindings/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -86970,10 +96617,10 @@ def test_delete_access_binding_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_access_binding(request) + client.list_expanded_data_sets(request) -def test_delete_access_binding_rest_flattened(): +def test_list_expanded_data_sets_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -86982,98 +96629,259 @@ def test_delete_access_binding_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListExpandedDataSetsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "accounts/sample1/accessBindings/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_access_binding(**mock_args) + client.list_expanded_data_sets(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=accounts/*/accessBindings/*}" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/expandedDataSets" + % client.transport._host, args[1], ) -def test_delete_access_binding_rest_flattened_error(transport: str = "rest"): +def test_list_expanded_data_sets_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_expanded_data_sets( + analytics_admin.ListExpandedDataSetsRequest(), + parent="parent_value", + ) + + +def test_list_expanded_data_sets_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_access_binding( - analytics_admin.DeleteAccessBindingRequest(), - name="name_value", - ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + next_page_token="abc", + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], + next_page_token="def", + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + ], + next_page_token="ghi", + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListExpandedDataSetsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_expanded_data_sets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, expanded_data_set.ExpandedDataSet) for i in results) + + pages = list(client.list_expanded_data_sets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.CreateExpandedDataSetRequest, + dict, + ], +) +def test_create_expanded_data_set_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request_init["expanded_data_set"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "dimension_names": ["dimension_names_value1", "dimension_names_value2"], + "metric_names": ["metric_names_value1", "metric_names_value2"], + "dimension_filter_expression": { + "and_group": {"filter_expressions": {}}, + "not_expression": {}, + "filter": { + "string_filter": { + "match_type": 1, + "value": "value_value", + "case_sensitive": True, + }, + "in_list_filter": { + "values": ["values_value1", "values_value2"], + "case_sensitive": True, + }, + "field_name": "field_name_value", + }, + }, + "data_collection_start_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateExpandedDataSetRequest.meta.fields[ + "expanded_data_set" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields -def test_delete_access_binding_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + subfields_not_in_runtime = [] -@pytest.mark.parametrize( - "request_type", - [ - analytics_admin.ListAccessBindingsRequest, - dict, - ], -) -def test_list_access_bindings_rest(request_type): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["expanded_data_set"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value - # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["expanded_data_set"][field])): + del request_init["expanded_data_set"][field][i][subfield] + else: + del request_init["expanded_data_set"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAccessBindingsResponse( - next_page_token="next_page_token_value", + return_value = gaa_expanded_data_set.ExpandedDataSet( + name="name_value", + display_name="display_name_value", + description="description_value", + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAccessBindingsResponse.pb(return_value) + return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_access_bindings(request) + response = client.create_expanded_data_set(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccessBindingsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] -def test_list_access_bindings_rest_use_cached_wrapped_rpc(): +def test_create_expanded_data_set_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -87088,7 +96896,8 @@ def test_list_access_bindings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_access_bindings in client._transport._wrapped_methods + client._transport.create_expanded_data_set + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -87097,24 +96906,24 @@ def test_list_access_bindings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_access_bindings + client._transport.create_expanded_data_set ] = mock_rpc request = {} - client.list_access_bindings(request) + client.create_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_access_bindings(request) + client.create_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_access_bindings_rest_required_fields( - request_type=analytics_admin.ListAccessBindingsRequest, +def test_create_expanded_data_set_rest_required_fields( + request_type=analytics_admin.CreateExpandedDataSetRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -87130,7 +96939,7 @@ def test_list_access_bindings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_access_bindings._get_unset_required_fields(jsonified_request) + ).create_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -87139,14 +96948,7 @@ def test_list_access_bindings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_access_bindings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).create_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -87160,7 +96962,7 @@ def test_list_access_bindings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAccessBindingsResponse() + return_value = gaa_expanded_data_set.ExpandedDataSet() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -87172,47 +96974,48 @@ def test_list_access_bindings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAccessBindingsResponse.pb(return_value) + return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_access_bindings(request) + response = client.create_expanded_data_set(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_access_bindings_rest_unset_required_fields(): +def test_create_expanded_data_set_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_access_bindings._get_unset_required_fields({}) + unset_fields = transport.create_expanded_data_set._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "pageSize", - "pageToken", + "parent", + "expandedDataSet", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_access_bindings_rest_interceptors(null_interceptor): +def test_create_expanded_data_set_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -87225,14 +97028,14 @@ def test_list_access_bindings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_access_bindings" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_expanded_data_set" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_access_bindings" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_expanded_data_set" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListAccessBindingsRequest.pb( - analytics_admin.ListAccessBindingsRequest() + pb_message = analytics_admin.CreateExpandedDataSetRequest.pb( + analytics_admin.CreateExpandedDataSetRequest() ) transcode.return_value = { "method": "post", @@ -87244,19 +97047,19 @@ def test_list_access_bindings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListAccessBindingsResponse.to_json( - analytics_admin.ListAccessBindingsResponse() + req.return_value._content = gaa_expanded_data_set.ExpandedDataSet.to_json( + gaa_expanded_data_set.ExpandedDataSet() ) - request = analytics_admin.ListAccessBindingsRequest() + request = analytics_admin.CreateExpandedDataSetRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListAccessBindingsResponse() + post.return_value = gaa_expanded_data_set.ExpandedDataSet() - client.list_access_bindings( + client.create_expanded_data_set( request, metadata=[ ("key", "val"), @@ -87268,8 +97071,8 @@ def test_list_access_bindings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_access_bindings_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListAccessBindingsRequest +def test_create_expanded_data_set_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateExpandedDataSetRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -87277,7 +97080,7 @@ def test_list_access_bindings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -87289,10 +97092,10 @@ def test_list_access_bindings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_access_bindings(request) + client.create_expanded_data_set(request) -def test_list_access_bindings_rest_flattened(): +def test_create_expanded_data_set_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -87301,14 +97104,15 @@ def test_list_access_bindings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAccessBindingsResponse() + return_value = gaa_expanded_data_set.ExpandedDataSet() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "accounts/sample1"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), ) mock_args.update(sample_request) @@ -87316,24 +97120,25 @@ def test_list_access_bindings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAccessBindingsResponse.pb(return_value) + return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_access_bindings(**mock_args) + client.create_expanded_data_set(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=accounts/*}/accessBindings" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/expandedDataSets" + % client.transport._host, args[1], ) -def test_list_access_bindings_rest_flattened_error(transport: str = "rest"): +def test_create_expanded_data_set_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -87342,115 +97147,163 @@ def test_list_access_bindings_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_access_bindings( - analytics_admin.ListAccessBindingsRequest(), + client.create_expanded_data_set( + analytics_admin.CreateExpandedDataSetRequest(), parent="parent_value", + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), ) -def test_list_access_bindings_rest_pager(transport: str = "rest"): +def test_create_expanded_data_set_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - resources.AccessBinding(), - ], - next_page_token="abc", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[], - next_page_token="def", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAccessBindingsResponse( - access_bindings=[ - resources.AccessBinding(), - resources.AccessBinding(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListAccessBindingsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "accounts/sample1"} - - pager = client.list_access_bindings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.AccessBinding) for i in results) - - pages = list(client.list_access_bindings(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.BatchCreateAccessBindingsRequest, + analytics_admin.UpdateExpandedDataSetRequest, dict, ], ) -def test_batch_create_access_bindings_rest(request_type): +def test_update_expanded_data_set_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = { + "expanded_data_set": {"name": "properties/sample1/expandedDataSets/sample2"} + } + request_init["expanded_data_set"] = { + "name": "properties/sample1/expandedDataSets/sample2", + "display_name": "display_name_value", + "description": "description_value", + "dimension_names": ["dimension_names_value1", "dimension_names_value2"], + "metric_names": ["metric_names_value1", "metric_names_value2"], + "dimension_filter_expression": { + "and_group": {"filter_expressions": {}}, + "not_expression": {}, + "filter": { + "string_filter": { + "match_type": 1, + "value": "value_value", + "case_sensitive": True, + }, + "in_list_filter": { + "values": ["values_value1", "values_value2"], + "case_sensitive": True, + }, + "field_name": "field_name_value", + }, + }, + "data_collection_start_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateExpandedDataSetRequest.meta.fields[ + "expanded_data_set" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["expanded_data_set"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["expanded_data_set"][field])): + del request_init["expanded_data_set"][field][i][subfield] + else: + del request_init["expanded_data_set"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.BatchCreateAccessBindingsResponse() + return_value = gaa_expanded_data_set.ExpandedDataSet( + name="name_value", + display_name="display_name_value", + description="description_value", + dimension_names=["dimension_names_value"], + metric_names=["metric_names_value"], + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.BatchCreateAccessBindingsResponse.pb( - return_value - ) + return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_access_bindings(request) + response = client.update_expanded_data_set(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.dimension_names == ["dimension_names_value"] + assert response.metric_names == ["metric_names_value"] -def test_batch_create_access_bindings_rest_use_cached_wrapped_rpc(): +def test_update_expanded_data_set_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -87465,7 +97318,7 @@ def test_batch_create_access_bindings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_create_access_bindings + client._transport.update_expanded_data_set in client._transport._wrapped_methods ) @@ -87475,29 +97328,28 @@ def test_batch_create_access_bindings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_create_access_bindings + client._transport.update_expanded_data_set ] = mock_rpc request = {} - client.batch_create_access_bindings(request) + client.update_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_create_access_bindings(request) + client.update_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_batch_create_access_bindings_rest_required_fields( - request_type=analytics_admin.BatchCreateAccessBindingsRequest, +def test_update_expanded_data_set_rest_required_fields( + request_type=analytics_admin.UpdateExpandedDataSetRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -87508,21 +97360,19 @@ def test_batch_create_access_bindings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_access_bindings._get_unset_required_fields(jsonified_request) + ).update_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_access_bindings._get_unset_required_fields(jsonified_request) + ).update_expanded_data_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -87531,7 +97381,7 @@ def test_batch_create_access_bindings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.BatchCreateAccessBindingsResponse() + return_value = gaa_expanded_data_set.ExpandedDataSet() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -87543,7 +97393,7 @@ def test_batch_create_access_bindings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -87553,40 +97403,38 @@ def test_batch_create_access_bindings_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.BatchCreateAccessBindingsResponse.pb( - return_value - ) + return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_access_bindings(request) + response = client.update_expanded_data_set(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_create_access_bindings_rest_unset_required_fields(): +def test_update_expanded_data_set_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_create_access_bindings._get_unset_required_fields({}) + unset_fields = transport.update_expanded_data_set._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("updateMask",)) & set( ( - "parent", - "requests", + "expandedDataSet", + "updateMask", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_access_bindings_rest_interceptors(null_interceptor): +def test_update_expanded_data_set_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -87599,16 +97447,14 @@ def test_batch_create_access_bindings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_batch_create_access_bindings", + transports.AnalyticsAdminServiceRestInterceptor, "post_update_expanded_data_set" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_batch_create_access_bindings", + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_expanded_data_set" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.BatchCreateAccessBindingsRequest.pb( - analytics_admin.BatchCreateAccessBindingsRequest() + pb_message = analytics_admin.UpdateExpandedDataSetRequest.pb( + analytics_admin.UpdateExpandedDataSetRequest() ) transcode.return_value = { "method": "post", @@ -87620,21 +97466,19 @@ def test_batch_create_access_bindings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.BatchCreateAccessBindingsResponse.to_json( - analytics_admin.BatchCreateAccessBindingsResponse() - ) + req.return_value._content = gaa_expanded_data_set.ExpandedDataSet.to_json( + gaa_expanded_data_set.ExpandedDataSet() ) - request = analytics_admin.BatchCreateAccessBindingsRequest() + request = analytics_admin.UpdateExpandedDataSetRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.BatchCreateAccessBindingsResponse() + post.return_value = gaa_expanded_data_set.ExpandedDataSet() - client.batch_create_access_bindings( + client.update_expanded_data_set( request, metadata=[ ("key", "val"), @@ -87646,9 +97490,8 @@ def test_batch_create_access_bindings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_create_access_bindings_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.BatchCreateAccessBindingsRequest, +def test_update_expanded_data_set_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateExpandedDataSetRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -87656,22 +97499,85 @@ def test_batch_create_access_bindings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = { + "expanded_data_set": {"name": "properties/sample1/expandedDataSets/sample2"} + } request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_create_access_bindings(request) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_expanded_data_set(request) + + +def test_update_expanded_data_set_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gaa_expanded_data_set.ExpandedDataSet() + + # get arguments that satisfy an http rule for this method + sample_request = { + "expanded_data_set": {"name": "properties/sample1/expandedDataSets/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_expanded_data_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{expanded_data_set.name=properties/*/expandedDataSets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_expanded_data_set_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_expanded_data_set( + analytics_admin.UpdateExpandedDataSetRequest(), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_batch_create_access_bindings_rest_error(): +def test_update_expanded_data_set_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -87680,41 +97586,39 @@ def test_batch_create_access_bindings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.BatchGetAccessBindingsRequest, + analytics_admin.DeleteExpandedDataSetRequest, dict, ], ) -def test_batch_get_access_bindings_rest(request_type): +def test_delete_expanded_data_set_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = {"name": "properties/sample1/expandedDataSets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.BatchGetAccessBindingsResponse() + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.BatchGetAccessBindingsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_get_access_bindings(request) + response = client.delete_expanded_data_set(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) + assert response is None -def test_batch_get_access_bindings_rest_use_cached_wrapped_rpc(): +def test_delete_expanded_data_set_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -87729,7 +97633,7 @@ def test_batch_get_access_bindings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_get_access_bindings + client._transport.delete_expanded_data_set in client._transport._wrapped_methods ) @@ -87739,30 +97643,29 @@ def test_batch_get_access_bindings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_get_access_bindings + client._transport.delete_expanded_data_set ] = mock_rpc request = {} - client.batch_get_access_bindings(request) + client.delete_expanded_data_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_get_access_bindings(request) + client.delete_expanded_data_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_batch_get_access_bindings_rest_required_fields( - request_type=analytics_admin.BatchGetAccessBindingsRequest, +def test_delete_expanded_data_set_rest_required_fields( + request_type=analytics_admin.DeleteExpandedDataSetRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["names"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -87770,32 +97673,24 @@ def test_batch_get_access_bindings_rest_required_fields( ) # verify fields with default values are dropped - assert "names" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_get_access_bindings._get_unset_required_fields(jsonified_request) + ).delete_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "names" in jsonified_request - assert jsonified_request["names"] == request_init["names"] - jsonified_request["parent"] = "parent_value" - jsonified_request["names"] = "names_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_get_access_bindings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("names",)) + ).delete_expanded_data_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "names" in jsonified_request - assert jsonified_request["names"] == "names_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -87804,7 +97699,7 @@ def test_batch_get_access_bindings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.BatchGetAccessBindingsResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -87816,55 +97711,36 @@ def test_batch_get_access_bindings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = analytics_admin.BatchGetAccessBindingsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_get_access_bindings(request) + response = client.delete_expanded_data_set(request) - expected_params = [ - ( - "names", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_get_access_bindings_rest_unset_required_fields(): +def test_delete_expanded_data_set_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_get_access_bindings._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("names",)) - & set( - ( - "parent", - "names", - ) - ) - ) + unset_fields = transport.delete_expanded_data_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_get_access_bindings_rest_interceptors(null_interceptor): +def test_delete_expanded_data_set_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -87877,15 +97753,11 @@ def test_batch_get_access_bindings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_batch_get_access_bindings", - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_batch_get_access_bindings" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_expanded_data_set" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.BatchGetAccessBindingsRequest.pb( - analytics_admin.BatchGetAccessBindingsRequest() + pb_message = analytics_admin.DeleteExpandedDataSetRequest.pb( + analytics_admin.DeleteExpandedDataSetRequest() ) transcode.return_value = { "method": "post", @@ -87897,21 +97769,15 @@ def test_batch_get_access_bindings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.BatchGetAccessBindingsResponse.to_json( - analytics_admin.BatchGetAccessBindingsResponse() - ) - ) - request = analytics_admin.BatchGetAccessBindingsRequest() + request = analytics_admin.DeleteExpandedDataSetRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.BatchGetAccessBindingsResponse() - client.batch_get_access_bindings( + client.delete_expanded_data_set( request, metadata=[ ("key", "val"), @@ -87920,11 +97786,10 @@ def test_batch_get_access_bindings_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_batch_get_access_bindings_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.BatchGetAccessBindingsRequest +def test_delete_expanded_data_set_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteExpandedDataSetRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -87932,7 +97797,7 @@ def test_batch_get_access_bindings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = {"name": "properties/sample1/expandedDataSets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -87944,10 +97809,65 @@ def test_batch_get_access_bindings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_get_access_bindings(request) + client.delete_expanded_data_set(request) -def test_batch_get_access_bindings_rest_error(): +def test_delete_expanded_data_set_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/expandedDataSets/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_expanded_data_set(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/expandedDataSets/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_expanded_data_set_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_expanded_data_set( + analytics_admin.DeleteExpandedDataSetRequest(), + name="name_value", + ) + + +def test_delete_expanded_data_set_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -87956,43 +97876,52 @@ def test_batch_get_access_bindings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.BatchUpdateAccessBindingsRequest, + analytics_admin.GetChannelGroupRequest, dict, ], ) -def test_batch_update_access_bindings_rest(request_type): +def test_get_channel_group_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = {"name": "properties/sample1/channelGroups/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + return_value = channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.BatchUpdateAccessBindingsResponse.pb( - return_value - ) + return_value = channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_update_access_bindings(request) + response = client.get_channel_group(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) + assert isinstance(response, channel_group.ChannelGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True -def test_batch_update_access_bindings_rest_use_cached_wrapped_rpc(): +def test_get_channel_group_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -88006,10 +97935,7 @@ def test_batch_update_access_bindings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_update_access_bindings - in client._transport._wrapped_methods - ) + assert client._transport.get_channel_group in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -88017,29 +97943,29 @@ def test_batch_update_access_bindings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_update_access_bindings + client._transport.get_channel_group ] = mock_rpc request = {} - client.batch_update_access_bindings(request) + client.get_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_update_access_bindings(request) + client.get_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_batch_update_access_bindings_rest_required_fields( - request_type=analytics_admin.BatchUpdateAccessBindingsRequest, +def test_get_channel_group_rest_required_fields( + request_type=analytics_admin.GetChannelGroupRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -88050,21 +97976,21 @@ def test_batch_update_access_bindings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_update_access_bindings._get_unset_required_fields(jsonified_request) + ).get_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_update_access_bindings._get_unset_required_fields(jsonified_request) + ).get_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -88073,7 +97999,7 @@ def test_batch_update_access_bindings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + return_value = channel_group.ChannelGroup() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -88085,50 +98011,39 @@ def test_batch_update_access_bindings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.BatchUpdateAccessBindingsResponse.pb( - return_value - ) + return_value = channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_update_access_bindings(request) + response = client.get_channel_group(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_update_access_bindings_rest_unset_required_fields(): +def test_get_channel_group_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_update_access_bindings._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "requests", - ) - ) - ) + unset_fields = transport.get_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_update_access_bindings_rest_interceptors(null_interceptor): +def test_get_channel_group_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -88141,16 +98056,14 @@ def test_batch_update_access_bindings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_batch_update_access_bindings", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_channel_group" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_batch_update_access_bindings", + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_channel_group" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.BatchUpdateAccessBindingsRequest.pb( - analytics_admin.BatchUpdateAccessBindingsRequest() + pb_message = analytics_admin.GetChannelGroupRequest.pb( + analytics_admin.GetChannelGroupRequest() ) transcode.return_value = { "method": "post", @@ -88162,21 +98075,19 @@ def test_batch_update_access_bindings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.BatchUpdateAccessBindingsResponse.to_json( - analytics_admin.BatchUpdateAccessBindingsResponse() - ) + req.return_value._content = channel_group.ChannelGroup.to_json( + channel_group.ChannelGroup() ) - request = analytics_admin.BatchUpdateAccessBindingsRequest() + request = analytics_admin.GetChannelGroupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + post.return_value = channel_group.ChannelGroup() - client.batch_update_access_bindings( + client.get_channel_group( request, metadata=[ ("key", "val"), @@ -88188,9 +98099,8 @@ def test_batch_update_access_bindings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_update_access_bindings_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.BatchUpdateAccessBindingsRequest, +def test_get_channel_group_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetChannelGroupRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -88198,7 +98108,7 @@ def test_batch_update_access_bindings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = {"name": "properties/sample1/channelGroups/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -88210,10 +98120,66 @@ def test_batch_update_access_bindings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_update_access_bindings(request) + client.get_channel_group(request) -def test_batch_update_access_bindings_rest_error(): +def test_get_channel_group_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = channel_group.ChannelGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/channelGroups/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = channel_group.ChannelGroup.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_channel_group(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/channelGroups/*}" % client.transport._host, + args[1], + ) + + +def test_get_channel_group_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_channel_group( + analytics_admin.GetChannelGroupRequest(), + name="name_value", + ) + + +def test_get_channel_group_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -88222,39 +98188,44 @@ def test_batch_update_access_bindings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.BatchDeleteAccessBindingsRequest, + analytics_admin.ListChannelGroupsRequest, dict, ], ) -def test_batch_delete_access_bindings_rest(request_type): +def test_list_channel_groups_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListChannelGroupsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = analytics_admin.ListChannelGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_delete_access_bindings(request) + response = client.list_channel_groups(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListChannelGroupsPager) + assert response.next_page_token == "next_page_token_value" -def test_batch_delete_access_bindings_rest_use_cached_wrapped_rpc(): +def test_list_channel_groups_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -88269,8 +98240,7 @@ def test_batch_delete_access_bindings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_delete_access_bindings - in client._transport._wrapped_methods + client._transport.list_channel_groups in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -88279,24 +98249,24 @@ def test_batch_delete_access_bindings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_delete_access_bindings + client._transport.list_channel_groups ] = mock_rpc request = {} - client.batch_delete_access_bindings(request) + client.list_channel_groups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.batch_delete_access_bindings(request) + client.list_channel_groups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_batch_delete_access_bindings_rest_required_fields( - request_type=analytics_admin.BatchDeleteAccessBindingsRequest, +def test_list_channel_groups_rest_required_fields( + request_type=analytics_admin.ListChannelGroupsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -88312,7 +98282,7 @@ def test_batch_delete_access_bindings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_delete_access_bindings._get_unset_required_fields(jsonified_request) + ).list_channel_groups._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -88321,7 +98291,14 @@ def test_batch_delete_access_bindings_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_delete_access_bindings._get_unset_required_fields(jsonified_request) + ).list_channel_groups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -88335,7 +98312,7 @@ def test_batch_delete_access_bindings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.ListChannelGroupsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -88347,45 +98324,47 @@ def test_batch_delete_access_bindings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = analytics_admin.ListChannelGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_delete_access_bindings(request) + response = client.list_channel_groups(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_delete_access_bindings_rest_unset_required_fields(): +def test_list_channel_groups_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_delete_access_bindings._get_unset_required_fields({}) + unset_fields = transport.list_channel_groups._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "requests", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_delete_access_bindings_rest_interceptors(null_interceptor): +def test_list_channel_groups_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -88398,12 +98377,14 @@ def test_batch_delete_access_bindings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_batch_delete_access_bindings", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_channel_groups" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_channel_groups" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.BatchDeleteAccessBindingsRequest.pb( - analytics_admin.BatchDeleteAccessBindingsRequest() + post.assert_not_called() + pb_message = analytics_admin.ListChannelGroupsRequest.pb( + analytics_admin.ListChannelGroupsRequest() ) transcode.return_value = { "method": "post", @@ -88415,15 +98396,19 @@ def test_batch_delete_access_bindings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = analytics_admin.ListChannelGroupsResponse.to_json( + analytics_admin.ListChannelGroupsResponse() + ) - request = analytics_admin.BatchDeleteAccessBindingsRequest() + request = analytics_admin.ListChannelGroupsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = analytics_admin.ListChannelGroupsResponse() - client.batch_delete_access_bindings( + client.list_channel_groups( request, metadata=[ ("key", "val"), @@ -88431,89 +98416,293 @@ def test_batch_delete_access_bindings_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() + pre.assert_called_once() + post.assert_called_once() + + +def test_list_channel_groups_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListChannelGroupsRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_channel_groups(request) + + +def test_list_channel_groups_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListChannelGroupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListChannelGroupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_channel_groups(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=properties/*}/channelGroups" % client.transport._host, + args[1], + ) -def test_batch_delete_access_bindings_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.BatchDeleteAccessBindingsRequest, -): +def test_list_channel_groups_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "accounts/sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.batch_delete_access_bindings(request) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_channel_groups( + analytics_admin.ListChannelGroupsRequest(), + parent="parent_value", + ) -def test_batch_delete_access_bindings_rest_error(): +def test_list_channel_groups_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token="abc", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token="def", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token="ghi", + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListChannelGroupsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_channel_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel_group.ChannelGroup) for i in results) + + pages = list(client.list_channel_groups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetExpandedDataSetRequest, + analytics_admin.CreateChannelGroupRequest, dict, ], ) -def test_get_expanded_data_set_rest(request_type): +def test_create_channel_group_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/expandedDataSets/sample2"} + request_init = {"parent": "properties/sample1"} + request_init["channel_group"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "grouping_rule": [ + { + "display_name": "display_name_value", + "expression": { + "and_group": {"filter_expressions": {}}, + "or_group": {}, + "not_expression": {}, + "filter": { + "string_filter": {"match_type": 1, "value": "value_value"}, + "in_list_filter": { + "values": ["values_value1", "values_value2"] + }, + "field_name": "field_name_value", + }, + }, + } + ], + "system_defined": True, + "primary": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateChannelGroupRequest.meta.fields["channel_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["channel_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["channel_group"][field])): + del request_init["channel_group"][field][i][subfield] + else: + del request_init["channel_group"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = expanded_data_set.ExpandedDataSet( + return_value = gaa_channel_group.ChannelGroup( name="name_value", display_name="display_name_value", description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], + system_defined=True, + primary=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = expanded_data_set.ExpandedDataSet.pb(return_value) + return_value = gaa_channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_expanded_data_set(request) + response = client.create_channel_group(request) # Establish that the response is the type that we expect. - assert isinstance(response, expanded_data_set.ExpandedDataSet) + assert isinstance(response, gaa_channel_group.ChannelGroup) assert response.name == "name_value" assert response.display_name == "display_name_value" assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert response.system_defined is True + assert response.primary is True -def test_get_expanded_data_set_rest_use_cached_wrapped_rpc(): +def test_create_channel_group_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -88528,8 +98717,7 @@ def test_get_expanded_data_set_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_expanded_data_set - in client._transport._wrapped_methods + client._transport.create_channel_group in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -88538,29 +98726,29 @@ def test_get_expanded_data_set_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_expanded_data_set + client._transport.create_channel_group ] = mock_rpc request = {} - client.get_expanded_data_set(request) + client.create_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_expanded_data_set(request) + client.create_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_expanded_data_set_rest_required_fields( - request_type=analytics_admin.GetExpandedDataSetRequest, +def test_create_channel_group_rest_required_fields( + request_type=analytics_admin.CreateChannelGroupRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -88571,21 +98759,21 @@ def test_get_expanded_data_set_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_expanded_data_set._get_unset_required_fields(jsonified_request) + ).create_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_expanded_data_set._get_unset_required_fields(jsonified_request) + ).create_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -88594,7 +98782,7 @@ def test_get_expanded_data_set_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = expanded_data_set.ExpandedDataSet() + return_value = gaa_channel_group.ChannelGroup() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -88606,39 +98794,48 @@ def test_get_expanded_data_set_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = expanded_data_set.ExpandedDataSet.pb(return_value) + return_value = gaa_channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_expanded_data_set(request) + response = client.create_channel_group(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_expanded_data_set_rest_unset_required_fields(): +def test_create_channel_group_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_expanded_data_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "channelGroup", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_expanded_data_set_rest_interceptors(null_interceptor): +def test_create_channel_group_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -88651,14 +98848,14 @@ def test_get_expanded_data_set_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_expanded_data_set" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_channel_group" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_expanded_data_set" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_channel_group" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetExpandedDataSetRequest.pb( - analytics_admin.GetExpandedDataSetRequest() + pb_message = analytics_admin.CreateChannelGroupRequest.pb( + analytics_admin.CreateChannelGroupRequest() ) transcode.return_value = { "method": "post", @@ -88670,19 +98867,19 @@ def test_get_expanded_data_set_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = expanded_data_set.ExpandedDataSet.to_json( - expanded_data_set.ExpandedDataSet() + req.return_value._content = gaa_channel_group.ChannelGroup.to_json( + gaa_channel_group.ChannelGroup() ) - request = analytics_admin.GetExpandedDataSetRequest() + request = analytics_admin.CreateChannelGroupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = expanded_data_set.ExpandedDataSet() + post.return_value = gaa_channel_group.ChannelGroup() - client.get_expanded_data_set( + client.create_channel_group( request, metadata=[ ("key", "val"), @@ -88694,8 +98891,8 @@ def test_get_expanded_data_set_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_expanded_data_set_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetExpandedDataSetRequest +def test_create_channel_group_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateChannelGroupRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -88703,7 +98900,7 @@ def test_get_expanded_data_set_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/expandedDataSets/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -88715,10 +98912,10 @@ def test_get_expanded_data_set_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_expanded_data_set(request) + client.create_channel_group(request) -def test_get_expanded_data_set_rest_flattened(): +def test_create_channel_group_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -88727,14 +98924,15 @@ def test_get_expanded_data_set_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = expanded_data_set.ExpandedDataSet() + return_value = gaa_channel_group.ChannelGroup() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/expandedDataSets/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) mock_args.update(sample_request) @@ -88742,25 +98940,24 @@ def test_get_expanded_data_set_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = expanded_data_set.ExpandedDataSet.pb(return_value) + return_value = gaa_channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_expanded_data_set(**mock_args) + client.create_channel_group(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/expandedDataSets/*}" - % client.transport._host, + "%s/v1alpha/{parent=properties/*}/channelGroups" % client.transport._host, args[1], ) -def test_get_expanded_data_set_rest_flattened_error(transport: str = "rest"): +def test_create_channel_group_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -88769,13 +98966,14 @@ def test_get_expanded_data_set_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_expanded_data_set( - analytics_admin.GetExpandedDataSetRequest(), - name="name_value", + client.create_channel_group( + analytics_admin.CreateChannelGroupRequest(), + parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) -def test_get_expanded_data_set_rest_error(): +def test_create_channel_group_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -88784,44 +98982,145 @@ def test_get_expanded_data_set_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListExpandedDataSetsRequest, + analytics_admin.UpdateChannelGroupRequest, dict, ], ) -def test_list_expanded_data_sets_rest(request_type): +def test_update_channel_group_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "channel_group": {"name": "properties/sample1/channelGroups/sample2"} + } + request_init["channel_group"] = { + "name": "properties/sample1/channelGroups/sample2", + "display_name": "display_name_value", + "description": "description_value", + "grouping_rule": [ + { + "display_name": "display_name_value", + "expression": { + "and_group": {"filter_expressions": {}}, + "or_group": {}, + "not_expression": {}, + "filter": { + "string_filter": {"match_type": 1, "value": "value_value"}, + "in_list_filter": { + "values": ["values_value1", "values_value2"] + }, + "field_name": "field_name_value", + }, + }, + } + ], + "system_defined": True, + "primary": True, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateChannelGroupRequest.meta.fields["channel_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["channel_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["channel_group"][field])): + del request_init["channel_group"][field][i][subfield] + else: + del request_init["channel_group"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListExpandedDataSetsResponse( - next_page_token="next_page_token_value", + return_value = gaa_channel_group.ChannelGroup( + name="name_value", + display_name="display_name_value", + description="description_value", + system_defined=True, + primary=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + return_value = gaa_channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_expanded_data_sets(request) + response = client.update_channel_group(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExpandedDataSetsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.system_defined is True + assert response.primary is True -def test_list_expanded_data_sets_rest_use_cached_wrapped_rpc(): +def test_update_channel_group_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -88836,8 +99135,7 @@ def test_list_expanded_data_sets_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_expanded_data_sets - in client._transport._wrapped_methods + client._transport.update_channel_group in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -88846,29 +99144,28 @@ def test_list_expanded_data_sets_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_expanded_data_sets + client._transport.update_channel_group ] = mock_rpc request = {} - client.list_expanded_data_sets(request) + client.update_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_expanded_data_sets(request) + client.update_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_expanded_data_sets_rest_required_fields( - request_type=analytics_admin.ListExpandedDataSetsRequest, +def test_update_channel_group_rest_required_fields( + request_type=analytics_admin.UpdateChannelGroupRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -88879,28 +99176,19 @@ def test_list_expanded_data_sets_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_expanded_data_sets._get_unset_required_fields(jsonified_request) + ).update_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_expanded_data_sets._get_unset_required_fields(jsonified_request) + ).update_channel_group._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -88909,7 +99197,7 @@ def test_list_expanded_data_sets_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListExpandedDataSetsResponse() + return_value = gaa_channel_group.ChannelGroup() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -88921,47 +99209,48 @@ def test_list_expanded_data_sets_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + return_value = gaa_channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_expanded_data_sets(request) + response = client.update_channel_group(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_expanded_data_sets_rest_unset_required_fields(): +def test_update_channel_group_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_expanded_data_sets._get_unset_required_fields({}) + unset_fields = transport.update_channel_group._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(("updateMask",)) + & set( ( - "pageSize", - "pageToken", + "channelGroup", + "updateMask", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_expanded_data_sets_rest_interceptors(null_interceptor): +def test_update_channel_group_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -88974,14 +99263,14 @@ def test_list_expanded_data_sets_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_expanded_data_sets" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_channel_group" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_expanded_data_sets" + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_channel_group" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListExpandedDataSetsRequest.pb( - analytics_admin.ListExpandedDataSetsRequest() + pb_message = analytics_admin.UpdateChannelGroupRequest.pb( + analytics_admin.UpdateChannelGroupRequest() ) transcode.return_value = { "method": "post", @@ -88993,21 +99282,19 @@ def test_list_expanded_data_sets_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListExpandedDataSetsResponse.to_json( - analytics_admin.ListExpandedDataSetsResponse() - ) + req.return_value._content = gaa_channel_group.ChannelGroup.to_json( + gaa_channel_group.ChannelGroup() ) - request = analytics_admin.ListExpandedDataSetsRequest() + request = analytics_admin.UpdateChannelGroupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListExpandedDataSetsResponse() + post.return_value = gaa_channel_group.ChannelGroup() - client.list_expanded_data_sets( + client.update_channel_group( request, metadata=[ ("key", "val"), @@ -89019,8 +99306,8 @@ def test_list_expanded_data_sets_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_expanded_data_sets_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListExpandedDataSetsRequest +def test_update_channel_group_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateChannelGroupRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -89028,7 +99315,9 @@ def test_list_expanded_data_sets_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "channel_group": {"name": "properties/sample1/channelGroups/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -89040,10 +99329,10 @@ def test_list_expanded_data_sets_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_expanded_data_sets(request) + client.update_channel_group(request) -def test_list_expanded_data_sets_rest_flattened(): +def test_update_channel_group_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -89052,14 +99341,17 @@ def test_list_expanded_data_sets_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListExpandedDataSetsResponse() + return_value = gaa_channel_group.ChannelGroup() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = { + "channel_group": {"name": "properties/sample1/channelGroups/sample2"} + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -89067,25 +99359,25 @@ def test_list_expanded_data_sets_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + return_value = gaa_channel_group.ChannelGroup.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_expanded_data_sets(**mock_args) + client.update_channel_group(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/expandedDataSets" + "%s/v1alpha/{channel_group.name=properties/*/channelGroups/*}" % client.transport._host, args[1], ) -def test_list_expanded_data_sets_rest_flattened_error(transport: str = "rest"): +def test_update_channel_group_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -89094,217 +99386,55 @@ def test_list_expanded_data_sets_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_expanded_data_sets( - analytics_admin.ListExpandedDataSetsRequest(), - parent="parent_value", + client.update_channel_group( + analytics_admin.UpdateChannelGroupRequest(), + channel_group=gaa_channel_group.ChannelGroup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_expanded_data_sets_rest_pager(transport: str = "rest"): +def test_update_channel_group_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - ], - next_page_token="abc", - ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[], - next_page_token="def", - ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - ], - next_page_token="ghi", - ), - analytics_admin.ListExpandedDataSetsResponse( - expanded_data_sets=[ - expanded_data_set.ExpandedDataSet(), - expanded_data_set.ExpandedDataSet(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListExpandedDataSetsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_expanded_data_sets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, expanded_data_set.ExpandedDataSet) for i in results) - - pages = list(client.list_expanded_data_sets(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateExpandedDataSetRequest, + analytics_admin.DeleteChannelGroupRequest, dict, ], ) -def test_create_expanded_data_set_rest(request_type): +def test_delete_channel_group_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["expanded_data_set"] = { - "name": "name_value", - "display_name": "display_name_value", - "description": "description_value", - "dimension_names": ["dimension_names_value1", "dimension_names_value2"], - "metric_names": ["metric_names_value1", "metric_names_value2"], - "dimension_filter_expression": { - "and_group": {"filter_expressions": {}}, - "not_expression": {}, - "filter": { - "string_filter": { - "match_type": 1, - "value": "value_value", - "case_sensitive": True, - }, - "in_list_filter": { - "values": ["values_value1", "values_value2"], - "case_sensitive": True, - }, - "field_name": "field_name_value", - }, - }, - "data_collection_start_time": {"seconds": 751, "nanos": 543}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateExpandedDataSetRequest.meta.fields[ - "expanded_data_set" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["expanded_data_set"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["expanded_data_set"][field])): - del request_init["expanded_data_set"][field][i][subfield] - else: - del request_init["expanded_data_set"][field][subfield] + request_init = {"name": "properties/sample1/channelGroups/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_expanded_data_set(request) + response = client.delete_channel_group(request) # Establish that the response is the type that we expect. - assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert response is None -def test_create_expanded_data_set_rest_use_cached_wrapped_rpc(): +def test_delete_channel_group_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -89319,8 +99449,7 @@ def test_create_expanded_data_set_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_expanded_data_set - in client._transport._wrapped_methods + client._transport.delete_channel_group in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -89329,29 +99458,29 @@ def test_create_expanded_data_set_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_expanded_data_set + client._transport.delete_channel_group ] = mock_rpc request = {} - client.create_expanded_data_set(request) + client.delete_channel_group(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_expanded_data_set(request) + client.delete_channel_group(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_expanded_data_set_rest_required_fields( - request_type=analytics_admin.CreateExpandedDataSetRequest, +def test_delete_channel_group_rest_required_fields( + request_type=analytics_admin.DeleteChannelGroupRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -89362,21 +99491,21 @@ def test_create_expanded_data_set_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_expanded_data_set._get_unset_required_fields(jsonified_request) + ).delete_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_expanded_data_set._get_unset_required_fields(jsonified_request) + ).delete_channel_group._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -89385,7 +99514,7 @@ def test_create_expanded_data_set_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gaa_expanded_data_set.ExpandedDataSet() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -89397,48 +99526,36 @@ def test_create_expanded_data_set_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_expanded_data_set(request) + response = client.delete_channel_group(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_expanded_data_set_rest_unset_required_fields(): +def test_delete_channel_group_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_expanded_data_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "expandedDataSet", - ) - ) - ) + unset_fields = transport.delete_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_expanded_data_set_rest_interceptors(null_interceptor): +def test_delete_channel_group_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -89451,14 +99568,11 @@ def test_create_expanded_data_set_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_expanded_data_set" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_expanded_data_set" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_channel_group" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.CreateExpandedDataSetRequest.pb( - analytics_admin.CreateExpandedDataSetRequest() + pb_message = analytics_admin.DeleteChannelGroupRequest.pb( + analytics_admin.DeleteChannelGroupRequest() ) transcode.return_value = { "method": "post", @@ -89470,19 +99584,15 @@ def test_create_expanded_data_set_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gaa_expanded_data_set.ExpandedDataSet.to_json( - gaa_expanded_data_set.ExpandedDataSet() - ) - request = analytics_admin.CreateExpandedDataSetRequest() + request = analytics_admin.DeleteChannelGroupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gaa_expanded_data_set.ExpandedDataSet() - client.create_expanded_data_set( + client.delete_channel_group( request, metadata=[ ("key", "val"), @@ -89491,11 +99601,10 @@ def test_create_expanded_data_set_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_create_expanded_data_set_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateExpandedDataSetRequest +def test_delete_channel_group_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteChannelGroupRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -89503,7 +99612,7 @@ def test_create_expanded_data_set_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/channelGroups/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -89515,10 +99624,10 @@ def test_create_expanded_data_set_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_expanded_data_set(request) + client.delete_channel_group(request) -def test_create_expanded_data_set_rest_flattened(): +def test_delete_channel_group_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -89527,41 +99636,37 @@ def test_create_expanded_data_set_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_expanded_data_set.ExpandedDataSet() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"name": "properties/sample1/channelGroups/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_expanded_data_set(**mock_args) + client.delete_channel_group(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/expandedDataSets" - % client.transport._host, + "%s/v1alpha/{name=properties/*/channelGroups/*}" % client.transport._host, args[1], ) -def test_create_expanded_data_set_rest_flattened_error(transport: str = "rest"): +def test_delete_channel_group_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -89570,14 +99675,13 @@ def test_create_expanded_data_set_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_expanded_data_set( - analytics_admin.CreateExpandedDataSetRequest(), - parent="parent_value", - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), + client.delete_channel_group( + analytics_admin.DeleteChannelGroupRequest(), + name="name_value", ) -def test_create_expanded_data_set_rest_error(): +def test_delete_channel_group_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -89586,147 +99690,45 @@ def test_create_expanded_data_set_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateExpandedDataSetRequest, + analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict, ], ) -def test_update_expanded_data_set_rest(request_type): +def test_set_automated_ga4_configuration_opt_out_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "expanded_data_set": {"name": "properties/sample1/expandedDataSets/sample2"} - } - request_init["expanded_data_set"] = { - "name": "properties/sample1/expandedDataSets/sample2", - "display_name": "display_name_value", - "description": "description_value", - "dimension_names": ["dimension_names_value1", "dimension_names_value2"], - "metric_names": ["metric_names_value1", "metric_names_value2"], - "dimension_filter_expression": { - "and_group": {"filter_expressions": {}}, - "not_expression": {}, - "filter": { - "string_filter": { - "match_type": 1, - "value": "value_value", - "case_sensitive": True, - }, - "in_list_filter": { - "values": ["values_value1", "values_value2"], - "case_sensitive": True, - }, - "field_name": "field_name_value", - }, - }, - "data_collection_start_time": {"seconds": 751, "nanos": 543}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateExpandedDataSetRequest.meta.fields[ - "expanded_data_set" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["expanded_data_set"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["expanded_data_set"][field])): - del request_init["expanded_data_set"][field][i][subfield] - else: - del request_init["expanded_data_set"][field][subfield] + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_expanded_data_set.ExpandedDataSet( - name="name_value", - display_name="display_name_value", - description="description_value", - dimension_names=["dimension_names_value"], - metric_names=["metric_names_value"], - ) + return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_expanded_data_set(request) + response = client.set_automated_ga4_configuration_opt_out(request) # Establish that the response is the type that we expect. - assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.dimension_names == ["dimension_names_value"] - assert response.metric_names == ["metric_names_value"] + assert isinstance( + response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse + ) -def test_update_expanded_data_set_rest_use_cached_wrapped_rpc(): +def test_set_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -89741,7 +99743,7 @@ def test_update_expanded_data_set_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_expanded_data_set + client._transport.set_automated_ga4_configuration_opt_out in client._transport._wrapped_methods ) @@ -89751,28 +99753,29 @@ def test_update_expanded_data_set_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_expanded_data_set + client._transport.set_automated_ga4_configuration_opt_out ] = mock_rpc request = {} - client.update_expanded_data_set(request) + client.set_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_expanded_data_set(request) + client.set_automated_ga4_configuration_opt_out(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_expanded_data_set_rest_required_fields( - request_type=analytics_admin.UpdateExpandedDataSetRequest, +def test_set_automated_ga4_configuration_opt_out_rest_required_fields( + request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["property"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -89783,19 +99786,25 @@ def test_update_expanded_data_set_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_expanded_data_set._get_unset_required_fields(jsonified_request) + ).set_automated_ga4_configuration_opt_out._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["property"] = "property_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_expanded_data_set._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + ).set_automated_ga4_configuration_opt_out._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == "property_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -89804,7 +99813,7 @@ def test_update_expanded_data_set_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gaa_expanded_data_set.ExpandedDataSet() + return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -89816,7 +99825,7 @@ def test_update_expanded_data_set_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -89826,38 +99835,36 @@ def test_update_expanded_data_set_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + return_value = ( + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_expanded_data_set(request) + response = client.set_automated_ga4_configuration_opt_out(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_expanded_data_set_rest_unset_required_fields(): +def test_set_automated_ga4_configuration_opt_out_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_expanded_data_set._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "expandedDataSet", - "updateMask", - ) - ) + unset_fields = ( + transport.set_automated_ga4_configuration_opt_out._get_unset_required_fields({}) ) + assert set(unset_fields) == (set(()) & set(("property",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_expanded_data_set_rest_interceptors(null_interceptor): +def test_set_automated_ga4_configuration_opt_out_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -89870,14 +99877,16 @@ def test_update_expanded_data_set_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_expanded_data_set" + transports.AnalyticsAdminServiceRestInterceptor, + "post_set_automated_ga4_configuration_opt_out", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_expanded_data_set" + transports.AnalyticsAdminServiceRestInterceptor, + "pre_set_automated_ga4_configuration_opt_out", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateExpandedDataSetRequest.pb( - analytics_admin.UpdateExpandedDataSetRequest() + pb_message = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest.pb( + analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() ) transcode.return_value = { "method": "post", @@ -89889,19 +99898,21 @@ def test_update_expanded_data_set_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gaa_expanded_data_set.ExpandedDataSet.to_json( - gaa_expanded_data_set.ExpandedDataSet() + req.return_value._content = ( + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.to_json( + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + ) ) - request = analytics_admin.UpdateExpandedDataSetRequest() + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gaa_expanded_data_set.ExpandedDataSet() + post.return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() - client.update_expanded_data_set( + client.set_automated_ga4_configuration_opt_out( request, metadata=[ ("key", "val"), @@ -89913,8 +99924,9 @@ def test_update_expanded_data_set_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_expanded_data_set_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateExpandedDataSetRequest +def test_set_automated_ga4_configuration_opt_out_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -89922,9 +99934,7 @@ def test_update_expanded_data_set_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "expanded_data_set": {"name": "properties/sample1/expandedDataSets/sample2"} - } + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -89936,71 +99946,10 @@ def test_update_expanded_data_set_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_expanded_data_set(request) - - -def test_update_expanded_data_set_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = gaa_expanded_data_set.ExpandedDataSet() - - # get arguments that satisfy an http rule for this method - sample_request = { - "expanded_data_set": {"name": "properties/sample1/expandedDataSets/sample2"} - } - - # get truthy value for each flattened field - mock_args = dict( - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_expanded_data_set(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{expanded_data_set.name=properties/*/expandedDataSets/*}" - % client.transport._host, - args[1], - ) - - -def test_update_expanded_data_set_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_expanded_data_set( - analytics_admin.UpdateExpandedDataSetRequest(), - expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + client.set_automated_ga4_configuration_opt_out(request) -def test_update_expanded_data_set_rest_error(): +def test_set_automated_ga4_configuration_opt_out_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -90009,39 +99958,48 @@ def test_update_expanded_data_set_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteExpandedDataSetRequest, + analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict, ], ) -def test_delete_expanded_data_set_rest(request_type): +def test_fetch_automated_ga4_configuration_opt_out_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/expandedDataSets/sample2"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_expanded_data_set(request) + response = client.fetch_automated_ga4_configuration_opt_out(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance( + response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse + ) + assert response.opt_out is True -def test_delete_expanded_data_set_rest_use_cached_wrapped_rpc(): +def test_fetch_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -90056,7 +100014,7 @@ def test_delete_expanded_data_set_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_expanded_data_set + client._transport.fetch_automated_ga4_configuration_opt_out in client._transport._wrapped_methods ) @@ -90066,29 +100024,29 @@ def test_delete_expanded_data_set_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_expanded_data_set + client._transport.fetch_automated_ga4_configuration_opt_out ] = mock_rpc request = {} - client.delete_expanded_data_set(request) + client.fetch_automated_ga4_configuration_opt_out(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_expanded_data_set(request) + client.fetch_automated_ga4_configuration_opt_out(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_expanded_data_set_rest_required_fields( - request_type=analytics_admin.DeleteExpandedDataSetRequest, +def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields( + request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["property"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -90099,21 +100057,25 @@ def test_delete_expanded_data_set_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_expanded_data_set._get_unset_required_fields(jsonified_request) + ).fetch_automated_ga4_configuration_opt_out._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["property"] = "property_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_expanded_data_set._get_unset_required_fields(jsonified_request) + ).fetch_automated_ga4_configuration_opt_out._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "property" in jsonified_request + assert jsonified_request["property"] == "property_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -90122,7 +100084,7 @@ def test_delete_expanded_data_set_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -90134,36 +100096,48 @@ def test_delete_expanded_data_set_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = ( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_expanded_data_set(request) + response = client.fetch_automated_ga4_configuration_opt_out(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_expanded_data_set_rest_unset_required_fields(): +def test_fetch_automated_ga4_configuration_opt_out_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_expanded_data_set._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = ( + transport.fetch_automated_ga4_configuration_opt_out._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("property",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_expanded_data_set_rest_interceptors(null_interceptor): +def test_fetch_automated_ga4_configuration_opt_out_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -90176,11 +100150,16 @@ def test_delete_expanded_data_set_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_expanded_data_set" + transports.AnalyticsAdminServiceRestInterceptor, + "post_fetch_automated_ga4_configuration_opt_out", + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, + "pre_fetch_automated_ga4_configuration_opt_out", ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteExpandedDataSetRequest.pb( - analytics_admin.DeleteExpandedDataSetRequest() + post.assert_not_called() + pb_message = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest.pb( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() ) transcode.return_value = { "method": "post", @@ -90192,15 +100171,23 @@ def test_delete_expanded_data_set_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = ( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.to_json( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() + ) + ) - request = analytics_admin.DeleteExpandedDataSetRequest() + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = ( + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() + ) - client.delete_expanded_data_set( + client.fetch_automated_ga4_configuration_opt_out( request, metadata=[ ("key", "val"), @@ -90209,10 +100196,12 @@ def test_delete_expanded_data_set_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_expanded_data_set_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteExpandedDataSetRequest +def test_fetch_automated_ga4_configuration_opt_out_rest_bad_request( + transport: str = "rest", + request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -90220,7 +100209,7 @@ def test_delete_expanded_data_set_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/expandedDataSets/sample2"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -90232,65 +100221,10 @@ def test_delete_expanded_data_set_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_expanded_data_set(request) - - -def test_delete_expanded_data_set_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/expandedDataSets/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = "" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_expanded_data_set(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=properties/*/expandedDataSets/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_expanded_data_set_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_expanded_data_set( - analytics_admin.DeleteExpandedDataSetRequest(), - name="name_value", - ) + client.fetch_automated_ga4_configuration_opt_out(request) -def test_delete_expanded_data_set_rest_error(): +def test_fetch_automated_ga4_configuration_opt_out_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -90299,50 +100233,139 @@ def test_delete_expanded_data_set_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetChannelGroupRequest, + analytics_admin.CreateBigQueryLinkRequest, dict, ], ) -def test_get_channel_group_rest(request_type): +def test_create_big_query_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/channelGroups/sample2"} + request_init = {"parent": "properties/sample1"} + request_init["bigquery_link"] = { + "name": "name_value", + "project": "project_value", + "create_time": {"seconds": 751, "nanos": 543}, + "daily_export_enabled": True, + "streaming_export_enabled": True, + "fresh_daily_export_enabled": True, + "include_advertising_id": True, + "export_streams": ["export_streams_value1", "export_streams_value2"], + "excluded_events": ["excluded_events_value1", "excluded_events_value2"], + "dataset_location": "dataset_location_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateBigQueryLinkRequest.meta.fields["bigquery_link"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["bigquery_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["bigquery_link"][field])): + del request_init["bigquery_link"][field][i][subfield] + else: + del request_init["bigquery_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = channel_group.ChannelGroup( + return_value = resources.BigQueryLink( name="name_value", - display_name="display_name_value", - description="description_value", - system_defined=True, + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = channel_group.ChannelGroup.pb(return_value) + return_value = resources.BigQueryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_channel_group(request) + response = client.create_big_query_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, channel_group.ChannelGroup) + assert isinstance(response, resources.BigQueryLink) assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.system_defined is True + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" -def test_get_channel_group_rest_use_cached_wrapped_rpc(): +def test_create_big_query_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -90356,7 +100379,10 @@ def test_get_channel_group_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_channel_group in client._transport._wrapped_methods + assert ( + client._transport.create_big_query_link + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -90364,29 +100390,29 @@ def test_get_channel_group_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_channel_group + client._transport.create_big_query_link ] = mock_rpc request = {} - client.get_channel_group(request) + client.create_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_channel_group(request) + client.create_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_channel_group_rest_required_fields( - request_type=analytics_admin.GetChannelGroupRequest, +def test_create_big_query_link_rest_required_fields( + request_type=analytics_admin.CreateBigQueryLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -90397,21 +100423,21 @@ def test_get_channel_group_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_channel_group._get_unset_required_fields(jsonified_request) + ).create_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_channel_group._get_unset_required_fields(jsonified_request) + ).create_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -90420,7 +100446,7 @@ def test_get_channel_group_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = channel_group.ChannelGroup() + return_value = resources.BigQueryLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -90432,39 +100458,48 @@ def test_get_channel_group_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = channel_group.ChannelGroup.pb(return_value) + return_value = resources.BigQueryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_channel_group(request) + response = client.create_big_query_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_channel_group_rest_unset_required_fields(): +def test_create_big_query_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_channel_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "bigqueryLink", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_channel_group_rest_interceptors(null_interceptor): +def test_create_big_query_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -90477,14 +100512,14 @@ def test_get_channel_group_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_channel_group" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_big_query_link" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_channel_group" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_big_query_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetChannelGroupRequest.pb( - analytics_admin.GetChannelGroupRequest() + pb_message = analytics_admin.CreateBigQueryLinkRequest.pb( + analytics_admin.CreateBigQueryLinkRequest() ) transcode.return_value = { "method": "post", @@ -90496,19 +100531,19 @@ def test_get_channel_group_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = channel_group.ChannelGroup.to_json( - channel_group.ChannelGroup() + req.return_value._content = resources.BigQueryLink.to_json( + resources.BigQueryLink() ) - request = analytics_admin.GetChannelGroupRequest() + request = analytics_admin.CreateBigQueryLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = channel_group.ChannelGroup() + post.return_value = resources.BigQueryLink() - client.get_channel_group( + client.create_big_query_link( request, metadata=[ ("key", "val"), @@ -90520,8 +100555,8 @@ def test_get_channel_group_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_channel_group_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetChannelGroupRequest +def test_create_big_query_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateBigQueryLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -90529,7 +100564,7 @@ def test_get_channel_group_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/channelGroups/sample2"} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -90541,10 +100576,10 @@ def test_get_channel_group_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_channel_group(request) + client.create_big_query_link(request) -def test_get_channel_group_rest_flattened(): +def test_create_big_query_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -90553,14 +100588,15 @@ def test_get_channel_group_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = channel_group.ChannelGroup() + return_value = resources.BigQueryLink() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/channelGroups/sample2"} + sample_request = {"parent": "properties/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + bigquery_link=resources.BigQueryLink(name="name_value"), ) mock_args.update(sample_request) @@ -90568,24 +100604,24 @@ def test_get_channel_group_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = channel_group.ChannelGroup.pb(return_value) + return_value = resources.BigQueryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_channel_group(**mock_args) + client.create_big_query_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/channelGroups/*}" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/bigQueryLinks" % client.transport._host, args[1], ) -def test_get_channel_group_rest_flattened_error(transport: str = "rest"): +def test_create_big_query_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -90594,13 +100630,14 @@ def test_get_channel_group_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_channel_group( - analytics_admin.GetChannelGroupRequest(), - name="name_value", + client.create_big_query_link( + analytics_admin.CreateBigQueryLinkRequest(), + parent="parent_value", + bigquery_link=resources.BigQueryLink(name="name_value"), ) -def test_get_channel_group_rest_error(): +def test_create_big_query_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -90609,44 +100646,60 @@ def test_get_channel_group_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListChannelGroupsRequest, + analytics_admin.GetBigQueryLinkRequest, dict, ], ) -def test_list_channel_groups_rest(request_type): +def test_get_big_query_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/bigQueryLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListChannelGroupsResponse( - next_page_token="next_page_token_value", + return_value = resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListChannelGroupsResponse.pb(return_value) + return_value = resources.BigQueryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_channel_groups(request) + response = client.get_big_query_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListChannelGroupsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.BigQueryLink) + assert response.name == "name_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" -def test_list_channel_groups_rest_use_cached_wrapped_rpc(): +def test_get_big_query_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -90661,7 +100714,7 @@ def test_list_channel_groups_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_channel_groups in client._transport._wrapped_methods + client._transport.get_big_query_link in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -90670,29 +100723,29 @@ def test_list_channel_groups_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_channel_groups + client._transport.get_big_query_link ] = mock_rpc request = {} - client.list_channel_groups(request) + client.get_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_channel_groups(request) + client.get_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_channel_groups_rest_required_fields( - request_type=analytics_admin.ListChannelGroupsRequest, +def test_get_big_query_link_rest_required_fields( + request_type=analytics_admin.GetBigQueryLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -90703,28 +100756,21 @@ def test_list_channel_groups_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_channel_groups._get_unset_required_fields(jsonified_request) + ).get_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_channel_groups._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).get_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -90733,7 +100779,7 @@ def test_list_channel_groups_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListChannelGroupsResponse() + return_value = resources.BigQueryLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -90754,38 +100800,30 @@ def test_list_channel_groups_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListChannelGroupsResponse.pb(return_value) + return_value = resources.BigQueryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_channel_groups(request) + response = client.get_big_query_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params - -def test_list_channel_groups_rest_unset_required_fields(): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_channel_groups._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) + +def test_get_big_query_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.get_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_channel_groups_rest_interceptors(null_interceptor): +def test_get_big_query_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -90798,14 +100836,14 @@ def test_list_channel_groups_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_channel_groups" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_big_query_link" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_channel_groups" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_big_query_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListChannelGroupsRequest.pb( - analytics_admin.ListChannelGroupsRequest() + pb_message = analytics_admin.GetBigQueryLinkRequest.pb( + analytics_admin.GetBigQueryLinkRequest() ) transcode.return_value = { "method": "post", @@ -90817,19 +100855,19 @@ def test_list_channel_groups_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListChannelGroupsResponse.to_json( - analytics_admin.ListChannelGroupsResponse() + req.return_value._content = resources.BigQueryLink.to_json( + resources.BigQueryLink() ) - request = analytics_admin.ListChannelGroupsRequest() + request = analytics_admin.GetBigQueryLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListChannelGroupsResponse() + post.return_value = resources.BigQueryLink() - client.list_channel_groups( + client.get_big_query_link( request, metadata=[ ("key", "val"), @@ -90841,8 +100879,8 @@ def test_list_channel_groups_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_channel_groups_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListChannelGroupsRequest +def test_get_big_query_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetBigQueryLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -90850,7 +100888,7 @@ def test_list_channel_groups_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"name": "properties/sample1/bigQueryLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -90862,10 +100900,10 @@ def test_list_channel_groups_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_channel_groups(request) + client.get_big_query_link(request) -def test_list_channel_groups_rest_flattened(): +def test_get_big_query_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -90874,14 +100912,14 @@ def test_list_channel_groups_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListChannelGroupsResponse() + return_value = resources.BigQueryLink() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"name": "properties/sample1/bigQueryLinks/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -90889,24 +100927,24 @@ def test_list_channel_groups_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListChannelGroupsResponse.pb(return_value) + return_value = resources.BigQueryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_channel_groups(**mock_args) + client.get_big_query_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/channelGroups" % client.transport._host, + "%s/v1alpha/{name=properties/*/bigQueryLinks/*}" % client.transport._host, args[1], ) -def test_list_channel_groups_rest_flattened_error(transport: str = "rest"): +def test_get_big_query_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -90915,83 +100953,26 @@ def test_list_channel_groups_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_channel_groups( - analytics_admin.ListChannelGroupsRequest(), - parent="parent_value", + client.get_big_query_link( + analytics_admin.GetBigQueryLinkRequest(), + name="name_value", ) -def test_list_channel_groups_rest_pager(transport: str = "rest"): +def test_get_big_query_link_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - ], - next_page_token="abc", - ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[], - next_page_token="def", - ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - ], - next_page_token="ghi", - ), - analytics_admin.ListChannelGroupsResponse( - channel_groups=[ - channel_group.ChannelGroup(), - channel_group.ChannelGroup(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListChannelGroupsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_channel_groups(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, channel_group.ChannelGroup) for i in results) - - pages = list(client.list_channel_groups(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateChannelGroupRequest, + analytics_admin.ListBigQueryLinksRequest, dict, ], ) -def test_create_channel_group_rest(request_type): +def test_list_big_query_links_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -90999,128 +100980,32 @@ def test_create_channel_group_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "properties/sample1"} - request_init["channel_group"] = { - "name": "name_value", - "display_name": "display_name_value", - "description": "description_value", - "grouping_rule": [ - { - "display_name": "display_name_value", - "expression": { - "and_group": {"filter_expressions": {}}, - "or_group": {}, - "not_expression": {}, - "filter": { - "string_filter": {"match_type": 1, "value": "value_value"}, - "in_list_filter": { - "values": ["values_value1", "values_value2"] - }, - "field_name": "field_name_value", - }, - }, - } - ], - "system_defined": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateChannelGroupRequest.meta.fields["channel_group"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["channel_group"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["channel_group"][field])): - del request_init["channel_group"][field][i][subfield] - else: - del request_init["channel_group"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_channel_group.ChannelGroup( - name="name_value", - display_name="display_name_value", - description="description_value", - system_defined=True, + return_value = analytics_admin.ListBigQueryLinksResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_channel_group.ChannelGroup.pb(return_value) + return_value = analytics_admin.ListBigQueryLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_channel_group(request) + response = client.list_big_query_links(request) # Establish that the response is the type that we expect. - assert isinstance(response, gaa_channel_group.ChannelGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.system_defined is True + assert isinstance(response, pagers.ListBigQueryLinksPager) + assert response.next_page_token == "next_page_token_value" -def test_create_channel_group_rest_use_cached_wrapped_rpc(): +def test_list_big_query_links_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -91135,7 +101020,7 @@ def test_create_channel_group_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_channel_group in client._transport._wrapped_methods + client._transport.list_big_query_links in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -91144,24 +101029,24 @@ def test_create_channel_group_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_channel_group + client._transport.list_big_query_links ] = mock_rpc request = {} - client.create_channel_group(request) + client.list_big_query_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_channel_group(request) + client.list_big_query_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_channel_group_rest_required_fields( - request_type=analytics_admin.CreateChannelGroupRequest, +def test_list_big_query_links_rest_required_fields( + request_type=analytics_admin.ListBigQueryLinksRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -91177,7 +101062,7 @@ def test_create_channel_group_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_channel_group._get_unset_required_fields(jsonified_request) + ).list_big_query_links._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -91186,7 +101071,14 @@ def test_create_channel_group_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_channel_group._get_unset_required_fields(jsonified_request) + ).list_big_query_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -91200,7 +101092,7 @@ def test_create_channel_group_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gaa_channel_group.ChannelGroup() + return_value = analytics_admin.ListBigQueryLinksResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -91212,48 +101104,47 @@ def test_create_channel_group_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_channel_group.ChannelGroup.pb(return_value) + return_value = analytics_admin.ListBigQueryLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_channel_group(request) + response = client.list_big_query_links(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_channel_group_rest_unset_required_fields(): +def test_list_big_query_links_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_channel_group._get_unset_required_fields({}) + unset_fields = transport.list_big_query_links._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "channelGroup", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_channel_group_rest_interceptors(null_interceptor): +def test_list_big_query_links_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -91266,14 +101157,14 @@ def test_create_channel_group_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_channel_group" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_big_query_links" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_channel_group" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_big_query_links" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateChannelGroupRequest.pb( - analytics_admin.CreateChannelGroupRequest() + pb_message = analytics_admin.ListBigQueryLinksRequest.pb( + analytics_admin.ListBigQueryLinksRequest() ) transcode.return_value = { "method": "post", @@ -91285,19 +101176,19 @@ def test_create_channel_group_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gaa_channel_group.ChannelGroup.to_json( - gaa_channel_group.ChannelGroup() + req.return_value._content = analytics_admin.ListBigQueryLinksResponse.to_json( + analytics_admin.ListBigQueryLinksResponse() ) - request = analytics_admin.CreateChannelGroupRequest() + request = analytics_admin.ListBigQueryLinksRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gaa_channel_group.ChannelGroup() + post.return_value = analytics_admin.ListBigQueryLinksResponse() - client.create_channel_group( + client.list_big_query_links( request, metadata=[ ("key", "val"), @@ -91309,8 +101200,8 @@ def test_create_channel_group_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_channel_group_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateChannelGroupRequest +def test_list_big_query_links_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListBigQueryLinksRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -91330,10 +101221,10 @@ def test_create_channel_group_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_channel_group(request) + client.list_big_query_links(request) -def test_create_channel_group_rest_flattened(): +def test_list_big_query_links_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -91342,7 +101233,7 @@ def test_create_channel_group_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_channel_group.ChannelGroup() + return_value = analytics_admin.ListBigQueryLinksResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1"} @@ -91350,7 +101241,6 @@ def test_create_channel_group_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) mock_args.update(sample_request) @@ -91358,24 +101248,24 @@ def test_create_channel_group_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = gaa_channel_group.ChannelGroup.pb(return_value) + return_value = analytics_admin.ListBigQueryLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_channel_group(**mock_args) + client.list_big_query_links(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/channelGroups" % client.transport._host, + "%s/v1alpha/{parent=properties/*}/bigQueryLinks" % client.transport._host, args[1], ) -def test_create_channel_group_rest_flattened_error(transport: str = "rest"): +def test_list_big_query_links_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -91384,158 +101274,111 @@ def test_create_channel_group_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_channel_group( - analytics_admin.CreateChannelGroupRequest(), + client.list_big_query_links( + analytics_admin.ListBigQueryLinksRequest(), parent="parent_value", - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), ) -def test_create_channel_group_rest_error(): +def test_list_big_query_links_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token="def", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListBigQueryLinksResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1"} + + pager = client.list_big_query_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.BigQueryLink) for i in results) + + pages = list(client.list_big_query_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateChannelGroupRequest, + analytics_admin.DeleteBigQueryLinkRequest, dict, ], ) -def test_update_channel_group_rest(request_type): +def test_delete_big_query_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "channel_group": {"name": "properties/sample1/channelGroups/sample2"} - } - request_init["channel_group"] = { - "name": "properties/sample1/channelGroups/sample2", - "display_name": "display_name_value", - "description": "description_value", - "grouping_rule": [ - { - "display_name": "display_name_value", - "expression": { - "and_group": {"filter_expressions": {}}, - "or_group": {}, - "not_expression": {}, - "filter": { - "string_filter": {"match_type": 1, "value": "value_value"}, - "in_list_filter": { - "values": ["values_value1", "values_value2"] - }, - "field_name": "field_name_value", - }, - }, - } - ], - "system_defined": True, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateChannelGroupRequest.meta.fields["channel_group"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["channel_group"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["channel_group"][field])): - del request_init["channel_group"][field][i][subfield] - else: - del request_init["channel_group"][field][subfield] + request_init = {"name": "properties/sample1/bigQueryLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_channel_group.ChannelGroup( - name="name_value", - display_name="display_name_value", - description="description_value", - system_defined=True, - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gaa_channel_group.ChannelGroup.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_channel_group(request) + response = client.delete_big_query_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, gaa_channel_group.ChannelGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.system_defined is True + assert response is None -def test_update_channel_group_rest_use_cached_wrapped_rpc(): +def test_delete_big_query_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -91550,7 +101393,8 @@ def test_update_channel_group_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_channel_group in client._transport._wrapped_methods + client._transport.delete_big_query_link + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -91559,28 +101403,29 @@ def test_update_channel_group_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_channel_group + client._transport.delete_big_query_link ] = mock_rpc request = {} - client.update_channel_group(request) + client.delete_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_channel_group(request) + client.delete_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_channel_group_rest_required_fields( - request_type=analytics_admin.UpdateChannelGroupRequest, +def test_delete_big_query_link_rest_required_fields( + request_type=analytics_admin.DeleteBigQueryLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -91591,19 +101436,21 @@ def test_update_channel_group_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_channel_group._get_unset_required_fields(jsonified_request) + ).delete_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_channel_group._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -91612,7 +101459,7 @@ def test_update_channel_group_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = gaa_channel_group.ChannelGroup() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -91624,48 +101471,36 @@ def test_update_channel_group_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = gaa_channel_group.ChannelGroup.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_channel_group(request) + response = client.delete_big_query_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_channel_group_rest_unset_required_fields(): +def test_delete_big_query_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_channel_group._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "channelGroup", - "updateMask", - ) - ) - ) + unset_fields = transport.delete_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_channel_group_rest_interceptors(null_interceptor): +def test_delete_big_query_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -91678,14 +101513,11 @@ def test_update_channel_group_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_channel_group" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_channel_group" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_big_query_link" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.UpdateChannelGroupRequest.pb( - analytics_admin.UpdateChannelGroupRequest() + pb_message = analytics_admin.DeleteBigQueryLinkRequest.pb( + analytics_admin.DeleteBigQueryLinkRequest() ) transcode.return_value = { "method": "post", @@ -91697,19 +101529,15 @@ def test_update_channel_group_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gaa_channel_group.ChannelGroup.to_json( - gaa_channel_group.ChannelGroup() - ) - request = analytics_admin.UpdateChannelGroupRequest() + request = analytics_admin.DeleteBigQueryLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = gaa_channel_group.ChannelGroup() - client.update_channel_group( + client.delete_big_query_link( request, metadata=[ ("key", "val"), @@ -91718,11 +101546,10 @@ def test_update_channel_group_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_update_channel_group_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateChannelGroupRequest +def test_delete_big_query_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteBigQueryLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -91730,9 +101557,7 @@ def test_update_channel_group_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "channel_group": {"name": "properties/sample1/channelGroups/sample2"} - } + request_init = {"name": "properties/sample1/bigQueryLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -91744,10 +101569,10 @@ def test_update_channel_group_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_channel_group(request) + client.delete_big_query_link(request) -def test_update_channel_group_rest_flattened(): +def test_delete_big_query_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -91756,43 +101581,37 @@ def test_update_channel_group_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gaa_channel_group.ChannelGroup() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = { - "channel_group": {"name": "properties/sample1/channelGroups/sample2"} - } + sample_request = {"name": "properties/sample1/bigQueryLinks/sample2"} # get truthy value for each flattened field mock_args = dict( - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = gaa_channel_group.ChannelGroup.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_channel_group(**mock_args) + client.delete_big_query_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{channel_group.name=properties/*/channelGroups/*}" - % client.transport._host, + "%s/v1alpha/{name=properties/*/bigQueryLinks/*}" % client.transport._host, args[1], ) -def test_update_channel_group_rest_flattened_error(transport: str = "rest"): +def test_delete_big_query_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -91801,14 +101620,13 @@ def test_update_channel_group_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_channel_group( - analytics_admin.UpdateChannelGroupRequest(), - channel_group=gaa_channel_group.ChannelGroup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_big_query_link( + analytics_admin.DeleteBigQueryLinkRequest(), + name="name_value", ) -def test_update_channel_group_rest_error(): +def test_delete_big_query_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -91817,39 +101635,141 @@ def test_update_channel_group_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteChannelGroupRequest, + analytics_admin.UpdateBigQueryLinkRequest, dict, ], ) -def test_delete_channel_group_rest(request_type): +def test_update_big_query_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/channelGroups/sample2"} + request_init = { + "bigquery_link": {"name": "properties/sample1/bigQueryLinks/sample2"} + } + request_init["bigquery_link"] = { + "name": "properties/sample1/bigQueryLinks/sample2", + "project": "project_value", + "create_time": {"seconds": 751, "nanos": 543}, + "daily_export_enabled": True, + "streaming_export_enabled": True, + "fresh_daily_export_enabled": True, + "include_advertising_id": True, + "export_streams": ["export_streams_value1", "export_streams_value2"], + "excluded_events": ["excluded_events_value1", "excluded_events_value2"], + "dataset_location": "dataset_location_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateBigQueryLinkRequest.meta.fields["bigquery_link"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["bigquery_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["bigquery_link"][field])): + del request_init["bigquery_link"][field][i][subfield] + else: + del request_init["bigquery_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.BigQueryLink( + name="name_value", + project="project_value", + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=["export_streams_value"], + excluded_events=["excluded_events_value"], + dataset_location="dataset_location_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.BigQueryLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_channel_group(request) + response = client.update_big_query_link(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.BigQueryLink) + assert response.name == "name_value" + assert response.project == "project_value" + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ["export_streams_value"] + assert response.excluded_events == ["excluded_events_value"] + assert response.dataset_location == "dataset_location_value" -def test_delete_channel_group_rest_use_cached_wrapped_rpc(): +def test_update_big_query_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -91864,7 +101784,8 @@ def test_delete_channel_group_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_channel_group in client._transport._wrapped_methods + client._transport.update_big_query_link + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -91873,29 +101794,28 @@ def test_delete_channel_group_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_channel_group + client._transport.update_big_query_link ] = mock_rpc request = {} - client.delete_channel_group(request) + client.update_big_query_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_channel_group(request) + client.update_big_query_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_channel_group_rest_required_fields( - request_type=analytics_admin.DeleteChannelGroupRequest, +def test_update_big_query_link_rest_required_fields( + request_type=analytics_admin.UpdateBigQueryLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -91906,21 +101826,19 @@ def test_delete_channel_group_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_channel_group._get_unset_required_fields(jsonified_request) + ).update_big_query_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_channel_group._get_unset_required_fields(jsonified_request) + ).update_big_query_link._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -91929,7 +101847,7 @@ def test_delete_channel_group_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.BigQueryLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -91941,36 +101859,48 @@ def test_delete_channel_group_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.BigQueryLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_channel_group(request) + response = client.update_big_query_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_channel_group_rest_unset_required_fields(): +def test_update_big_query_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_channel_group._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "bigqueryLink", + "updateMask", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_channel_group_rest_interceptors(null_interceptor): +def test_update_big_query_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -91983,11 +101913,14 @@ def test_delete_channel_group_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_channel_group" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_big_query_link" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_big_query_link" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteChannelGroupRequest.pb( - analytics_admin.DeleteChannelGroupRequest() + post.assert_not_called() + pb_message = analytics_admin.UpdateBigQueryLinkRequest.pb( + analytics_admin.UpdateBigQueryLinkRequest() ) transcode.return_value = { "method": "post", @@ -91999,15 +101932,19 @@ def test_delete_channel_group_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.BigQueryLink.to_json( + resources.BigQueryLink() + ) - request = analytics_admin.DeleteChannelGroupRequest() + request = analytics_admin.UpdateBigQueryLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.BigQueryLink() - client.delete_channel_group( + client.update_big_query_link( request, metadata=[ ("key", "val"), @@ -92016,10 +101953,11 @@ def test_delete_channel_group_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_channel_group_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteChannelGroupRequest +def test_update_big_query_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateBigQueryLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92027,7 +101965,9 @@ def test_delete_channel_group_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/channelGroups/sample2"} + request_init = { + "bigquery_link": {"name": "properties/sample1/bigQueryLinks/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -92039,10 +101979,10 @@ def test_delete_channel_group_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_channel_group(request) + client.update_big_query_link(request) -def test_delete_channel_group_rest_flattened(): +def test_update_big_query_link_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -92051,37 +101991,43 @@ def test_delete_channel_group_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.BigQueryLink() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/channelGroups/sample2"} + sample_request = { + "bigquery_link": {"name": "properties/sample1/bigQueryLinks/sample2"} + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + bigquery_link=resources.BigQueryLink(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.BigQueryLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_channel_group(**mock_args) + client.update_big_query_link(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/channelGroups/*}" % client.transport._host, + "%s/v1alpha/{bigquery_link.name=properties/*/bigQueryLinks/*}" + % client.transport._host, args[1], ) -def test_delete_channel_group_rest_flattened_error(transport: str = "rest"): +def test_update_big_query_link_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -92090,13 +102036,14 @@ def test_delete_channel_group_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_channel_group( - analytics_admin.DeleteChannelGroupRequest(), - name="name_value", + client.update_big_query_link( + analytics_admin.UpdateBigQueryLinkRequest(), + bigquery_link=resources.BigQueryLink(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_channel_group_rest_error(): +def test_update_big_query_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -92105,45 +102052,66 @@ def test_delete_channel_group_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, + analytics_admin.GetEnhancedMeasurementSettingsRequest, dict, ], ) -def test_set_automated_ga4_configuration_opt_out_rest(request_type): +def test_get_enhanced_measurement_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + return_value = resources.EnhancedMeasurementSettings( + name="name_value", + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb( - return_value - ) + return_value = resources.EnhancedMeasurementSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_automated_ga4_configuration_opt_out(request) + response = client.get_enhanced_measurement_settings(request) # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse - ) + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == "name_value" + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == "search_query_parameter_value" + assert response.uri_query_parameter == "uri_query_parameter_value" -def test_set_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): +def test_get_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -92158,7 +102126,7 @@ def test_set_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.set_automated_ga4_configuration_opt_out + client._transport.get_enhanced_measurement_settings in client._transport._wrapped_methods ) @@ -92168,29 +102136,29 @@ def test_set_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.set_automated_ga4_configuration_opt_out + client._transport.get_enhanced_measurement_settings ] = mock_rpc request = {} - client.set_automated_ga4_configuration_opt_out(request) + client.get_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.set_automated_ga4_configuration_opt_out(request) + client.get_enhanced_measurement_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_set_automated_ga4_configuration_opt_out_rest_required_fields( - request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, +def test_get_enhanced_measurement_settings_rest_required_fields( + request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["property"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -92201,25 +102169,21 @@ def test_set_automated_ga4_configuration_opt_out_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_automated_ga4_configuration_opt_out._get_unset_required_fields( - jsonified_request - ) + ).get_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["property"] = "property_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).set_automated_ga4_configuration_opt_out._get_unset_required_fields( - jsonified_request - ) + ).get_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "property" in jsonified_request - assert jsonified_request["property"] == "property_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92228,7 +102192,7 @@ def test_set_automated_ga4_configuration_opt_out_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + return_value = resources.EnhancedMeasurementSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -92240,46 +102204,41 @@ def test_set_automated_ga4_configuration_opt_out_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb( - return_value - ) - ) + return_value = resources.EnhancedMeasurementSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.set_automated_ga4_configuration_opt_out(request) + response = client.get_enhanced_measurement_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_set_automated_ga4_configuration_opt_out_rest_unset_required_fields(): +def test_get_enhanced_measurement_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = ( - transport.set_automated_ga4_configuration_opt_out._get_unset_required_fields({}) + transport.get_enhanced_measurement_settings._get_unset_required_fields({}) ) - assert set(unset_fields) == (set(()) & set(("property",))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_automated_ga4_configuration_opt_out_rest_interceptors(null_interceptor): +def test_get_enhanced_measurement_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -92293,15 +102252,15 @@ def test_set_automated_ga4_configuration_opt_out_rest_interceptors(null_intercep path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_set_automated_ga4_configuration_opt_out", + "post_get_enhanced_measurement_settings", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_set_automated_ga4_configuration_opt_out", + "pre_get_enhanced_measurement_settings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest.pb( - analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + pb_message = analytics_admin.GetEnhancedMeasurementSettingsRequest.pb( + analytics_admin.GetEnhancedMeasurementSettingsRequest() ) transcode.return_value = { "method": "post", @@ -92313,21 +102272,19 @@ def test_set_automated_ga4_configuration_opt_out_rest_interceptors(null_intercep req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.to_json( - analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() - ) + req.return_value._content = resources.EnhancedMeasurementSettings.to_json( + resources.EnhancedMeasurementSettings() ) - request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + post.return_value = resources.EnhancedMeasurementSettings() - client.set_automated_ga4_configuration_opt_out( + client.get_enhanced_measurement_settings( request, metadata=[ ("key", "val"), @@ -92339,9 +102296,9 @@ def test_set_automated_ga4_configuration_opt_out_rest_interceptors(null_intercep post.assert_called_once() -def test_set_automated_ga4_configuration_opt_out_rest_bad_request( +def test_get_enhanced_measurement_settings_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, + request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92349,7 +102306,9 @@ def test_set_automated_ga4_configuration_opt_out_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -92361,10 +102320,71 @@ def test_set_automated_ga4_configuration_opt_out_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.set_automated_ga4_configuration_opt_out(request) + client.get_enhanced_measurement_settings(request) -def test_set_automated_ga4_configuration_opt_out_rest_error(): +def test_get_enhanced_measurement_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.EnhancedMeasurementSettings() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.EnhancedMeasurementSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_enhanced_measurement_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/dataStreams/*/enhancedMeasurementSettings}" + % client.transport._host, + args[1], + ) + + +def test_get_enhanced_measurement_settings_rest_flattened_error( + transport: str = "rest", +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_enhanced_measurement_settings( + analytics_admin.GetEnhancedMeasurementSettingsRequest(), + name="name_value", + ) + + +def test_get_enhanced_measurement_settings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -92373,48 +102393,156 @@ def test_set_automated_ga4_configuration_opt_out_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, + analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict, ], ) -def test_fetch_automated_ga4_configuration_opt_out_rest(request_type): +def test_update_enhanced_measurement_settings_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {} + # send a request that will satisfy transcoding + request_init = { + "enhanced_measurement_settings": { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" + } + } + request_init["enhanced_measurement_settings"] = { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings", + "stream_enabled": True, + "scrolls_enabled": True, + "outbound_clicks_enabled": True, + "site_search_enabled": True, + "video_engagement_enabled": True, + "file_downloads_enabled": True, + "page_changes_enabled": True, + "form_interactions_enabled": True, + "search_query_parameter": "search_query_parameter_value", + "uri_query_parameter": "uri_query_parameter_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.meta.fields[ + "enhanced_measurement_settings" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "enhanced_measurement_settings" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["enhanced_measurement_settings"][field]) + ): + del request_init["enhanced_measurement_settings"][field][i][ + subfield + ] + else: + del request_init["enhanced_measurement_settings"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( - opt_out=True, + return_value = resources.EnhancedMeasurementSettings( + name="name_value", + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter="search_query_parameter_value", + uri_query_parameter="uri_query_parameter_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb( - return_value - ) + return_value = resources.EnhancedMeasurementSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_automated_ga4_configuration_opt_out(request) + response = client.update_enhanced_measurement_settings(request) # Establish that the response is the type that we expect. - assert isinstance( - response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse - ) - assert response.opt_out is True + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == "name_value" + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == "search_query_parameter_value" + assert response.uri_query_parameter == "uri_query_parameter_value" -def test_fetch_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): +def test_update_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -92429,7 +102557,7 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc() # Ensure method has been cached assert ( - client._transport.fetch_automated_ga4_configuration_opt_out + client._transport.update_enhanced_measurement_settings in client._transport._wrapped_methods ) @@ -92439,29 +102567,28 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc() "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_automated_ga4_configuration_opt_out + client._transport.update_enhanced_measurement_settings ] = mock_rpc request = {} - client.fetch_automated_ga4_configuration_opt_out(request) + client.update_enhanced_measurement_settings(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_automated_ga4_configuration_opt_out(request) + client.update_enhanced_measurement_settings(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields( - request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, +def test_update_enhanced_measurement_settings_rest_required_fields( + request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["property"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -92472,25 +102599,19 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_automated_ga4_configuration_opt_out._get_unset_required_fields( - jsonified_request - ) + ).update_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["property"] = "property_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_automated_ga4_configuration_opt_out._get_unset_required_fields( - jsonified_request - ) + ).update_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "property" in jsonified_request - assert jsonified_request["property"] == "property_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92499,7 +102620,7 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() + return_value = resources.EnhancedMeasurementSettings() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -92511,7 +102632,7 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -92521,38 +102642,40 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb( - return_value - ) - ) + return_value = resources.EnhancedMeasurementSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_automated_ga4_configuration_opt_out(request) + response = client.update_enhanced_measurement_settings(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_fetch_automated_ga4_configuration_opt_out_rest_unset_required_fields(): +def test_update_enhanced_measurement_settings_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = ( - transport.fetch_automated_ga4_configuration_opt_out._get_unset_required_fields( - {} + transport.update_enhanced_measurement_settings._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "enhancedMeasurementSettings", + "updateMask", + ) ) ) - assert set(unset_fields) == (set(()) & set(("property",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_automated_ga4_configuration_opt_out_rest_interceptors(null_interceptor): +def test_update_enhanced_measurement_settings_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -92566,15 +102689,15 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_interceptors(null_interc path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_fetch_automated_ga4_configuration_opt_out", + "post_update_enhanced_measurement_settings", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_fetch_automated_ga4_configuration_opt_out", + "pre_update_enhanced_measurement_settings", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest.pb( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + pb_message = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.pb( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest() ) transcode.return_value = { "method": "post", @@ -92586,23 +102709,19 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_interceptors(null_interc req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.to_json( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() - ) + req.return_value._content = resources.EnhancedMeasurementSettings.to_json( + resources.EnhancedMeasurementSettings() ) - request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = ( - analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() - ) + post.return_value = resources.EnhancedMeasurementSettings() - client.fetch_automated_ga4_configuration_opt_out( + client.update_enhanced_measurement_settings( request, metadata=[ ("key", "val"), @@ -92614,9 +102733,9 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_interceptors(null_interc post.assert_called_once() -def test_fetch_automated_ga4_configuration_opt_out_rest_bad_request( +def test_update_enhanced_measurement_settings_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, + request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92624,7 +102743,11 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = { + "enhanced_measurement_settings": { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -92636,10 +102759,79 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.fetch_automated_ga4_configuration_opt_out(request) + client.update_enhanced_measurement_settings(request) -def test_fetch_automated_ga4_configuration_opt_out_rest_error(): +def test_update_enhanced_measurement_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.EnhancedMeasurementSettings() + + # get arguments that satisfy an http rule for this method + sample_request = { + "enhanced_measurement_settings": { + "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" + } + } + + # get truthy value for each flattened field + mock_args = dict( + enhanced_measurement_settings=resources.EnhancedMeasurementSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.EnhancedMeasurementSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_enhanced_measurement_settings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{enhanced_measurement_settings.name=properties/*/dataStreams/*/enhancedMeasurementSettings}" + % client.transport._host, + args[1], + ) + + +def test_update_enhanced_measurement_settings_rest_flattened_error( + transport: str = "rest", +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_enhanced_measurement_settings( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), + enhanced_measurement_settings=resources.EnhancedMeasurementSettings( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_enhanced_measurement_settings_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -92648,58 +102840,41 @@ def test_fetch_automated_ga4_configuration_opt_out_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetBigQueryLinkRequest, + analytics_admin.CreateConnectedSiteTagRequest, dict, ], ) -def test_get_big_query_link_rest(request_type): +def test_create_connected_site_tag_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/bigQueryLinks/sample2"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.BigQueryLink( - name="name_value", - project="project_value", - daily_export_enabled=True, - streaming_export_enabled=True, - fresh_daily_export_enabled=True, - include_advertising_id=True, - export_streams=["export_streams_value"], - excluded_events=["excluded_events_value"], - ) + return_value = analytics_admin.CreateConnectedSiteTagResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.BigQueryLink.pb(return_value) + return_value = analytics_admin.CreateConnectedSiteTagResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_big_query_link(request) + response = client.create_connected_site_tag(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.BigQueryLink) - assert response.name == "name_value" - assert response.project == "project_value" - assert response.daily_export_enabled is True - assert response.streaming_export_enabled is True - assert response.fresh_daily_export_enabled is True - assert response.include_advertising_id is True - assert response.export_streams == ["export_streams_value"] - assert response.excluded_events == ["excluded_events_value"] + assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) -def test_get_big_query_link_rest_use_cached_wrapped_rpc(): +def test_create_connected_site_tag_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -92714,7 +102889,8 @@ def test_get_big_query_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_big_query_link in client._transport._wrapped_methods + client._transport.create_connected_site_tag + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -92723,29 +102899,28 @@ def test_get_big_query_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_big_query_link + client._transport.create_connected_site_tag ] = mock_rpc request = {} - client.get_big_query_link(request) + client.create_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_big_query_link(request) + client.create_connected_site_tag(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_big_query_link_rest_required_fields( - request_type=analytics_admin.GetBigQueryLinkRequest, +def test_create_connected_site_tag_rest_required_fields( + request_type=analytics_admin.CreateConnectedSiteTagRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -92756,21 +102931,17 @@ def test_get_big_query_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_big_query_link._get_unset_required_fields(jsonified_request) + ).create_connected_site_tag._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_big_query_link._get_unset_required_fields(jsonified_request) + ).create_connected_site_tag._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92779,7 +102950,7 @@ def test_get_big_query_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.BigQueryLink() + return_value = analytics_admin.CreateConnectedSiteTagResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -92791,39 +102962,42 @@ def test_get_big_query_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.BigQueryLink.pb(return_value) + return_value = analytics_admin.CreateConnectedSiteTagResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_big_query_link(request) + response = client.create_connected_site_tag(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_big_query_link_rest_unset_required_fields(): +def test_create_connected_site_tag_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_big_query_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_connected_site_tag._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("connectedSiteTag",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_big_query_link_rest_interceptors(null_interceptor): +def test_create_connected_site_tag_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -92836,14 +103010,15 @@ def test_get_big_query_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_big_query_link" + transports.AnalyticsAdminServiceRestInterceptor, + "post_create_connected_site_tag", ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_big_query_link" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_connected_site_tag" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetBigQueryLinkRequest.pb( - analytics_admin.GetBigQueryLinkRequest() + pb_message = analytics_admin.CreateConnectedSiteTagRequest.pb( + analytics_admin.CreateConnectedSiteTagRequest() ) transcode.return_value = { "method": "post", @@ -92855,19 +103030,21 @@ def test_get_big_query_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.BigQueryLink.to_json( - resources.BigQueryLink() + req.return_value._content = ( + analytics_admin.CreateConnectedSiteTagResponse.to_json( + analytics_admin.CreateConnectedSiteTagResponse() + ) ) - request = analytics_admin.GetBigQueryLinkRequest() + request = analytics_admin.CreateConnectedSiteTagRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.BigQueryLink() + post.return_value = analytics_admin.CreateConnectedSiteTagResponse() - client.get_big_query_link( + client.create_connected_site_tag( request, metadata=[ ("key", "val"), @@ -92879,8 +103056,8 @@ def test_get_big_query_link_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_big_query_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetBigQueryLinkRequest +def test_create_connected_site_tag_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateConnectedSiteTagRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -92888,7 +103065,7 @@ def test_get_big_query_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/bigQueryLinks/sample2"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -92900,66 +103077,10 @@ def test_get_big_query_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_big_query_link(request) - - -def test_get_big_query_link_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.BigQueryLink() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/bigQueryLinks/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.BigQueryLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_big_query_link(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=properties/*/bigQueryLinks/*}" % client.transport._host, - args[1], - ) - - -def test_get_big_query_link_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_big_query_link( - analytics_admin.GetBigQueryLinkRequest(), - name="name_value", - ) + client.create_connected_site_tag(request) -def test_get_big_query_link_rest_error(): +def test_create_connected_site_tag_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -92968,44 +103089,39 @@ def test_get_big_query_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListBigQueryLinksRequest, + analytics_admin.DeleteConnectedSiteTagRequest, dict, ], ) -def test_list_big_query_links_rest(request_type): +def test_delete_connected_site_tag_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListBigQueryLinksResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListBigQueryLinksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_big_query_links(request) + response = client.delete_connected_site_tag(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBigQueryLinksPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_big_query_links_rest_use_cached_wrapped_rpc(): +def test_delete_connected_site_tag_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -93020,7 +103136,8 @@ def test_list_big_query_links_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_big_query_links in client._transport._wrapped_methods + client._transport.delete_connected_site_tag + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -93029,122 +103146,24 @@ def test_list_big_query_links_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_big_query_links + client._transport.delete_connected_site_tag ] = mock_rpc request = {} - client.list_big_query_links(request) + client.delete_connected_site_tag(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_big_query_links(request) + client.delete_connected_site_tag(request) # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_big_query_links_rest_required_fields( - request_type=analytics_admin.ListBigQueryLinksRequest, -): - transport_class = transports.AnalyticsAdminServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_big_query_links._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_big_query_links._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListBigQueryLinksResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = analytics_admin.ListBigQueryLinksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.list_big_query_links(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_list_big_query_links_rest_unset_required_fields(): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.list_big_query_links._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_big_query_links_rest_interceptors(null_interceptor): +def test_delete_connected_site_tag_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -93157,14 +103176,11 @@ def test_list_big_query_links_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_big_query_links" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_big_query_links" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_connected_site_tag" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ListBigQueryLinksRequest.pb( - analytics_admin.ListBigQueryLinksRequest() + pb_message = analytics_admin.DeleteConnectedSiteTagRequest.pb( + analytics_admin.DeleteConnectedSiteTagRequest() ) transcode.return_value = { "method": "post", @@ -93176,19 +103192,15 @@ def test_list_big_query_links_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListBigQueryLinksResponse.to_json( - analytics_admin.ListBigQueryLinksResponse() - ) - request = analytics_admin.ListBigQueryLinksRequest() + request = analytics_admin.DeleteConnectedSiteTagRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListBigQueryLinksResponse() - client.list_big_query_links( + client.delete_connected_site_tag( request, metadata=[ ("key", "val"), @@ -93197,11 +103209,10 @@ def test_list_big_query_links_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_list_big_query_links_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListBigQueryLinksRequest +def test_delete_connected_site_tag_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteConnectedSiteTagRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -93209,7 +103220,7 @@ def test_list_big_query_links_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -93221,191 +103232,53 @@ def test_list_big_query_links_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_big_query_links(request) - - -def test_list_big_query_links_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListBigQueryLinksResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListBigQueryLinksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.list_big_query_links(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/bigQueryLinks" % client.transport._host, - args[1], - ) - - -def test_list_big_query_links_rest_flattened_error(transport: str = "rest"): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_big_query_links( - analytics_admin.ListBigQueryLinksRequest(), - parent="parent_value", - ) + client.delete_connected_site_tag(request) -def test_list_big_query_links_rest_pager(transport: str = "rest"): +def test_delete_connected_site_tag_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[], - next_page_token="def", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListBigQueryLinksResponse( - bigquery_links=[ - resources.BigQueryLink(), - resources.BigQueryLink(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListBigQueryLinksResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_big_query_links(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.BigQueryLink) for i in results) - - pages = list(client.list_big_query_links(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetEnhancedMeasurementSettingsRequest, + analytics_admin.ListConnectedSiteTagsRequest, dict, ], ) -def test_get_enhanced_measurement_settings_rest(request_type): +def test_list_connected_site_tags_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" - } + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.EnhancedMeasurementSettings( - name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", - ) + return_value = analytics_admin.ListConnectedSiteTagsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.EnhancedMeasurementSettings.pb(return_value) + return_value = analytics_admin.ListConnectedSiteTagsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_enhanced_measurement_settings(request) + response = client.list_connected_site_tags(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.EnhancedMeasurementSettings) - assert response.name == "name_value" - assert response.stream_enabled is True - assert response.scrolls_enabled is True - assert response.outbound_clicks_enabled is True - assert response.site_search_enabled is True - assert response.video_engagement_enabled is True - assert response.file_downloads_enabled is True - assert response.page_changes_enabled is True - assert response.form_interactions_enabled is True - assert response.search_query_parameter == "search_query_parameter_value" - assert response.uri_query_parameter == "uri_query_parameter_value" + assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) -def test_get_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): +def test_list_connected_site_tags_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -93420,7 +103293,7 @@ def test_get_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_enhanced_measurement_settings + client._transport.list_connected_site_tags in client._transport._wrapped_methods ) @@ -93430,109 +103303,24 @@ def test_get_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_enhanced_measurement_settings + client._transport.list_connected_site_tags ] = mock_rpc request = {} - client.get_enhanced_measurement_settings(request) + client.list_connected_site_tags(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_enhanced_measurement_settings(request) + client.list_connected_site_tags(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_enhanced_measurement_settings_rest_required_fields( - request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest, -): - transport_class = transports.AnalyticsAdminServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.EnhancedMeasurementSettings() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.EnhancedMeasurementSettings.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.get_enhanced_measurement_settings(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_get_enhanced_measurement_settings_rest_unset_required_fields(): - transport = transports.AnalyticsAdminServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = ( - transport.get_enhanced_measurement_settings._get_unset_required_fields({}) - ) - assert set(unset_fields) == (set(()) & set(("name",))) - - @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_enhanced_measurement_settings_rest_interceptors(null_interceptor): +def test_list_connected_site_tags_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -93545,16 +103333,14 @@ def test_get_enhanced_measurement_settings_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_get_enhanced_measurement_settings", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_connected_site_tags" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_get_enhanced_measurement_settings", + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_connected_site_tags" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetEnhancedMeasurementSettingsRequest.pb( - analytics_admin.GetEnhancedMeasurementSettingsRequest() + pb_message = analytics_admin.ListConnectedSiteTagsRequest.pb( + analytics_admin.ListConnectedSiteTagsRequest() ) transcode.return_value = { "method": "post", @@ -93566,19 +103352,21 @@ def test_get_enhanced_measurement_settings_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.EnhancedMeasurementSettings.to_json( - resources.EnhancedMeasurementSettings() + req.return_value._content = ( + analytics_admin.ListConnectedSiteTagsResponse.to_json( + analytics_admin.ListConnectedSiteTagsResponse() + ) ) - request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + request = analytics_admin.ListConnectedSiteTagsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.EnhancedMeasurementSettings() + post.return_value = analytics_admin.ListConnectedSiteTagsResponse() - client.get_enhanced_measurement_settings( + client.list_connected_site_tags( request, metadata=[ ("key", "val"), @@ -93590,9 +103378,8 @@ def test_get_enhanced_measurement_settings_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_enhanced_measurement_settings_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest, +def test_list_connected_site_tags_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListConnectedSiteTagsRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -93600,9 +103387,7 @@ def test_get_enhanced_measurement_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" - } + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -93614,71 +103399,10 @@ def test_get_enhanced_measurement_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_enhanced_measurement_settings(request) - - -def test_get_enhanced_measurement_settings_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.EnhancedMeasurementSettings() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.EnhancedMeasurementSettings.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_enhanced_measurement_settings(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/enhancedMeasurementSettings}" - % client.transport._host, - args[1], - ) - - -def test_get_enhanced_measurement_settings_rest_flattened_error( - transport: str = "rest", -): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_enhanced_measurement_settings( - analytics_admin.GetEnhancedMeasurementSettingsRequest(), - name="name_value", - ) + client.list_connected_site_tags(request) -def test_get_enhanced_measurement_settings_rest_error(): +def test_list_connected_site_tags_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -93687,156 +103411,46 @@ def test_get_enhanced_measurement_settings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateEnhancedMeasurementSettingsRequest, + analytics_admin.FetchConnectedGa4PropertyRequest, dict, ], ) -def test_update_enhanced_measurement_settings_rest(request_type): +def test_fetch_connected_ga4_property_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "enhanced_measurement_settings": { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" - } - } - request_init["enhanced_measurement_settings"] = { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings", - "stream_enabled": True, - "scrolls_enabled": True, - "outbound_clicks_enabled": True, - "site_search_enabled": True, - "video_engagement_enabled": True, - "file_downloads_enabled": True, - "page_changes_enabled": True, - "form_interactions_enabled": True, - "search_query_parameter": "search_query_parameter_value", - "uri_query_parameter": "uri_query_parameter_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.meta.fields[ - "enhanced_measurement_settings" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "enhanced_measurement_settings" - ].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range( - 0, len(request_init["enhanced_measurement_settings"][field]) - ): - del request_init["enhanced_measurement_settings"][field][i][ - subfield - ] - else: - del request_init["enhanced_measurement_settings"][field][subfield] + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.EnhancedMeasurementSettings( - name="name_value", - stream_enabled=True, - scrolls_enabled=True, - outbound_clicks_enabled=True, - site_search_enabled=True, - video_engagement_enabled=True, - file_downloads_enabled=True, - page_changes_enabled=True, - form_interactions_enabled=True, - search_query_parameter="search_query_parameter_value", - uri_query_parameter="uri_query_parameter_value", + return_value = analytics_admin.FetchConnectedGa4PropertyResponse( + property="property_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.EnhancedMeasurementSettings.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.update_enhanced_measurement_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.EnhancedMeasurementSettings) - assert response.name == "name_value" - assert response.stream_enabled is True - assert response.scrolls_enabled is True - assert response.outbound_clicks_enabled is True - assert response.site_search_enabled is True - assert response.video_engagement_enabled is True - assert response.file_downloads_enabled is True - assert response.page_changes_enabled is True - assert response.form_interactions_enabled is True - assert response.search_query_parameter == "search_query_parameter_value" - assert response.uri_query_parameter == "uri_query_parameter_value" + return_value = analytics_admin.FetchConnectedGa4PropertyResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.fetch_connected_ga4_property(request) -def test_update_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) + assert response.property == "property_value" + + +def test_fetch_connected_ga4_property_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -93851,7 +103465,7 @@ def test_update_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_enhanced_measurement_settings + client._transport.fetch_connected_ga4_property in client._transport._wrapped_methods ) @@ -93861,28 +103475,29 @@ def test_update_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_enhanced_measurement_settings + client._transport.fetch_connected_ga4_property ] = mock_rpc request = {} - client.update_enhanced_measurement_settings(request) + client.fetch_connected_ga4_property(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_enhanced_measurement_settings(request) + client.fetch_connected_ga4_property(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_enhanced_measurement_settings_rest_required_fields( - request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest, +def test_fetch_connected_ga4_property_rest_required_fields( + request_type=analytics_admin.FetchConnectedGa4PropertyRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["property"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -93890,22 +103505,29 @@ def test_update_enhanced_measurement_settings_rest_required_fields( ) # verify fields with default values are dropped + assert "property" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) + ).fetch_connected_ga4_property._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "property" in jsonified_request + assert jsonified_request["property"] == request_init["property"] + + jsonified_request["property"] = "property_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_enhanced_measurement_settings._get_unset_required_fields(jsonified_request) + ).fetch_connected_ga4_property._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set(("property",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == "property_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -93914,7 +103536,7 @@ def test_update_enhanced_measurement_settings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.EnhancedMeasurementSettings() + return_value = analytics_admin.FetchConnectedGa4PropertyResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -93926,50 +103548,47 @@ def test_update_enhanced_measurement_settings_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.EnhancedMeasurementSettings.pb(return_value) + return_value = analytics_admin.FetchConnectedGa4PropertyResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_enhanced_measurement_settings(request) + response = client.fetch_connected_ga4_property(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "property", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_enhanced_measurement_settings_rest_unset_required_fields(): +def test_fetch_connected_ga4_property_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.update_enhanced_measurement_settings._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set(("updateMask",)) - & set( - ( - "enhancedMeasurementSettings", - "updateMask", - ) - ) - ) + unset_fields = transport.fetch_connected_ga4_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(("property",)) & set(("property",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_enhanced_measurement_settings_rest_interceptors(null_interceptor): +def test_fetch_connected_ga4_property_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -93983,15 +103602,15 @@ def test_update_enhanced_measurement_settings_rest_interceptors(null_interceptor path_template, "transcode" ) as transcode, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "post_update_enhanced_measurement_settings", + "post_fetch_connected_ga4_property", ) as post, mock.patch.object( transports.AnalyticsAdminServiceRestInterceptor, - "pre_update_enhanced_measurement_settings", + "pre_fetch_connected_ga4_property", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.pb( - analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + pb_message = analytics_admin.FetchConnectedGa4PropertyRequest.pb( + analytics_admin.FetchConnectedGa4PropertyRequest() ) transcode.return_value = { "method": "post", @@ -94003,19 +103622,21 @@ def test_update_enhanced_measurement_settings_rest_interceptors(null_interceptor req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.EnhancedMeasurementSettings.to_json( - resources.EnhancedMeasurementSettings() + req.return_value._content = ( + analytics_admin.FetchConnectedGa4PropertyResponse.to_json( + analytics_admin.FetchConnectedGa4PropertyResponse() + ) ) - request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + request = analytics_admin.FetchConnectedGa4PropertyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.EnhancedMeasurementSettings() + post.return_value = analytics_admin.FetchConnectedGa4PropertyResponse() - client.update_enhanced_measurement_settings( + client.fetch_connected_ga4_property( request, metadata=[ ("key", "val"), @@ -94027,9 +103648,9 @@ def test_update_enhanced_measurement_settings_rest_interceptors(null_interceptor post.assert_called_once() -def test_update_enhanced_measurement_settings_rest_bad_request( +def test_fetch_connected_ga4_property_rest_bad_request( transport: str = "rest", - request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest, + request_type=analytics_admin.FetchConnectedGa4PropertyRequest, ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -94037,11 +103658,7 @@ def test_update_enhanced_measurement_settings_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "enhanced_measurement_settings": { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" - } - } + request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -94053,79 +103670,10 @@ def test_update_enhanced_measurement_settings_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_enhanced_measurement_settings(request) - - -def test_update_enhanced_measurement_settings_rest_flattened(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.EnhancedMeasurementSettings() - - # get arguments that satisfy an http rule for this method - sample_request = { - "enhanced_measurement_settings": { - "name": "properties/sample1/dataStreams/sample2/enhancedMeasurementSettings" - } - } - - # get truthy value for each flattened field - mock_args = dict( - enhanced_measurement_settings=resources.EnhancedMeasurementSettings( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.EnhancedMeasurementSettings.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.update_enhanced_measurement_settings(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{enhanced_measurement_settings.name=properties/*/dataStreams/*/enhancedMeasurementSettings}" - % client.transport._host, - args[1], - ) - - -def test_update_enhanced_measurement_settings_rest_flattened_error( - transport: str = "rest", -): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_enhanced_measurement_settings( - analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), - enhanced_measurement_settings=resources.EnhancedMeasurementSettings( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) + client.fetch_connected_ga4_property(request) -def test_update_enhanced_measurement_settings_rest_error(): +def test_fetch_connected_ga4_property_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -94134,41 +103682,46 @@ def test_update_enhanced_measurement_settings_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateConnectedSiteTagRequest, + analytics_admin.GetAdSenseLinkRequest, dict, ], ) -def test_create_connected_site_tag_rest(request_type): +def test_get_ad_sense_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/adSenseLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.CreateConnectedSiteTagResponse() + return_value = resources.AdSenseLink( + name="name_value", + ad_client_code="ad_client_code_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.CreateConnectedSiteTagResponse.pb(return_value) + return_value = resources.AdSenseLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_connected_site_tag(request) + response = client.get_ad_sense_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) + assert isinstance(response, resources.AdSenseLink) + assert response.name == "name_value" + assert response.ad_client_code == "ad_client_code_value" -def test_create_connected_site_tag_rest_use_cached_wrapped_rpc(): +def test_get_ad_sense_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -94182,10 +103735,7 @@ def test_create_connected_site_tag_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_connected_site_tag - in client._transport._wrapped_methods - ) + assert client._transport.get_ad_sense_link in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -94193,28 +103743,29 @@ def test_create_connected_site_tag_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_connected_site_tag + client._transport.get_ad_sense_link ] = mock_rpc request = {} - client.create_connected_site_tag(request) + client.get_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_connected_site_tag(request) + client.get_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_connected_site_tag_rest_required_fields( - request_type=analytics_admin.CreateConnectedSiteTagRequest, +def test_get_ad_sense_link_rest_required_fields( + request_type=analytics_admin.GetAdSenseLinkRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -94225,17 +103776,21 @@ def test_create_connected_site_tag_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_connected_site_tag._get_unset_required_fields(jsonified_request) + ).get_ad_sense_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_connected_site_tag._get_unset_required_fields(jsonified_request) + ).get_ad_sense_link._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -94244,7 +103799,7 @@ def test_create_connected_site_tag_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.CreateConnectedSiteTagResponse() + return_value = resources.AdSenseLink() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -94256,42 +103811,39 @@ def test_create_connected_site_tag_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.CreateConnectedSiteTagResponse.pb( - return_value - ) + return_value = resources.AdSenseLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_connected_site_tag(request) + response = client.get_ad_sense_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_connected_site_tag_rest_unset_required_fields(): +def test_get_ad_sense_link_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_connected_site_tag._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("connectedSiteTag",))) + unset_fields = transport.get_ad_sense_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_connected_site_tag_rest_interceptors(null_interceptor): +def test_get_ad_sense_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -94304,15 +103856,14 @@ def test_create_connected_site_tag_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_create_connected_site_tag", + transports.AnalyticsAdminServiceRestInterceptor, "post_get_ad_sense_link" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_connected_site_tag" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_ad_sense_link" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateConnectedSiteTagRequest.pb( - analytics_admin.CreateConnectedSiteTagRequest() + pb_message = analytics_admin.GetAdSenseLinkRequest.pb( + analytics_admin.GetAdSenseLinkRequest() ) transcode.return_value = { "method": "post", @@ -94324,21 +103875,19 @@ def test_create_connected_site_tag_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.CreateConnectedSiteTagResponse.to_json( - analytics_admin.CreateConnectedSiteTagResponse() - ) + req.return_value._content = resources.AdSenseLink.to_json( + resources.AdSenseLink() ) - request = analytics_admin.CreateConnectedSiteTagRequest() + request = analytics_admin.GetAdSenseLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.CreateConnectedSiteTagResponse() + post.return_value = resources.AdSenseLink() - client.create_connected_site_tag( + client.get_ad_sense_link( request, metadata=[ ("key", "val"), @@ -94350,8 +103899,8 @@ def test_create_connected_site_tag_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_connected_site_tag_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateConnectedSiteTagRequest +def test_get_ad_sense_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetAdSenseLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -94359,7 +103908,7 @@ def test_create_connected_site_tag_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/adSenseLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -94371,10 +103920,66 @@ def test_create_connected_site_tag_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_connected_site_tag(request) + client.get_ad_sense_link(request) -def test_create_connected_site_tag_rest_error(): +def test_get_ad_sense_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AdSenseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/adSenseLinks/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AdSenseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_ad_sense_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/adSenseLinks/*}" % client.transport._host, + args[1], + ) + + +def test_get_ad_sense_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_ad_sense_link( + analytics_admin.GetAdSenseLinkRequest(), + name="name_value", + ) + + +def test_get_ad_sense_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -94383,39 +103988,117 @@ def test_create_connected_site_tag_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteConnectedSiteTagRequest, + analytics_admin.CreateAdSenseLinkRequest, dict, ], ) -def test_delete_connected_site_tag_rest(request_type): +def test_create_ad_sense_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "properties/sample1"} + request_init["adsense_link"] = { + "name": "name_value", + "ad_client_code": "ad_client_code_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateAdSenseLinkRequest.meta.fields["adsense_link"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["adsense_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["adsense_link"][field])): + del request_init["adsense_link"][field][i][subfield] + else: + del request_init["adsense_link"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = resources.AdSenseLink( + name="name_value", + ad_client_code="ad_client_code_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = resources.AdSenseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_connected_site_tag(request) + response = client.create_ad_sense_link(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.AdSenseLink) + assert response.name == "name_value" + assert response.ad_client_code == "ad_client_code_value" -def test_delete_connected_site_tag_rest_use_cached_wrapped_rpc(): +def test_create_ad_sense_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -94428,36 +104111,127 @@ def test_delete_connected_site_tag_rest_use_cached_wrapped_rpc(): assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - # Ensure method has been cached - assert ( - client._transport.delete_connected_site_tag - in client._transport._wrapped_methods - ) + # Ensure method has been cached + assert ( + client._transport.create_ad_sense_link in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_ad_sense_link + ] = mock_rpc + + request = {} + client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_ad_sense_link_rest_required_fields( + request_type=analytics_admin.CreateAdSenseLinkRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_ad_sense_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_ad_sense_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AdSenseLink() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.AdSenseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[ - client._transport.delete_connected_site_tag - ] = mock_rpc + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - request = {} - client.delete_connected_site_tag(request) + response = client.create_ad_sense_link(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - client.delete_connected_site_tag(request) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +def test_create_ad_sense_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_ad_sense_link._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "adsenseLink", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_connected_site_tag_rest_interceptors(null_interceptor): +def test_create_ad_sense_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -94470,11 +104244,14 @@ def test_delete_connected_site_tag_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_connected_site_tag" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_ad_sense_link" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_ad_sense_link" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteConnectedSiteTagRequest.pb( - analytics_admin.DeleteConnectedSiteTagRequest() + post.assert_not_called() + pb_message = analytics_admin.CreateAdSenseLinkRequest.pb( + analytics_admin.CreateAdSenseLinkRequest() ) transcode.return_value = { "method": "post", @@ -94486,15 +104263,19 @@ def test_delete_connected_site_tag_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = resources.AdSenseLink.to_json( + resources.AdSenseLink() + ) - request = analytics_admin.DeleteConnectedSiteTagRequest() + request = analytics_admin.CreateAdSenseLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.AdSenseLink() - client.delete_connected_site_tag( + client.create_ad_sense_link( request, metadata=[ ("key", "val"), @@ -94503,10 +104284,11 @@ def test_delete_connected_site_tag_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_connected_site_tag_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteConnectedSiteTagRequest +def test_create_ad_sense_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateAdSenseLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -94514,7 +104296,7 @@ def test_delete_connected_site_tag_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -94526,10 +104308,68 @@ def test_delete_connected_site_tag_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_connected_site_tag(request) + client.create_ad_sense_link(request) -def test_delete_connected_site_tag_rest_error(): +def test_create_ad_sense_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.AdSenseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + adsense_link=resources.AdSenseLink(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AdSenseLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_ad_sense_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=properties/*}/adSenseLinks" % client.transport._host, + args[1], + ) + + +def test_create_ad_sense_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_ad_sense_link( + analytics_admin.CreateAdSenseLinkRequest(), + parent="parent_value", + adsense_link=resources.AdSenseLink(name="name_value"), + ) + + +def test_create_ad_sense_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -94538,41 +104378,39 @@ def test_delete_connected_site_tag_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListConnectedSiteTagsRequest, + analytics_admin.DeleteAdSenseLinkRequest, dict, ], ) -def test_list_connected_site_tags_rest(request_type): +def test_delete_ad_sense_link_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/adSenseLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListConnectedSiteTagsResponse() + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = analytics_admin.ListConnectedSiteTagsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_connected_site_tags(request) + response = client.delete_ad_sense_link(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) + assert response is None -def test_list_connected_site_tags_rest_use_cached_wrapped_rpc(): +def test_delete_ad_sense_link_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -94587,8 +104425,7 @@ def test_list_connected_site_tags_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_connected_site_tags - in client._transport._wrapped_methods + client._transport.delete_ad_sense_link in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -94597,24 +104434,104 @@ def test_list_connected_site_tags_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_connected_site_tags + client._transport.delete_ad_sense_link ] = mock_rpc request = {} - client.list_connected_site_tags(request) + client.delete_ad_sense_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_connected_site_tags(request) + client.delete_ad_sense_link(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 +def test_delete_ad_sense_link_rest_required_fields( + request_type=analytics_admin.DeleteAdSenseLinkRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_ad_sense_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_ad_sense_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_ad_sense_link(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_ad_sense_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_ad_sense_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_connected_site_tags_rest_interceptors(null_interceptor): +def test_delete_ad_sense_link_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -94627,14 +104544,11 @@ def test_list_connected_site_tags_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_connected_site_tags" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_connected_site_tags" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_ad_sense_link" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.ListConnectedSiteTagsRequest.pb( - analytics_admin.ListConnectedSiteTagsRequest() + pb_message = analytics_admin.DeleteAdSenseLinkRequest.pb( + analytics_admin.DeleteAdSenseLinkRequest() ) transcode.return_value = { "method": "post", @@ -94646,21 +104560,15 @@ def test_list_connected_site_tags_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListConnectedSiteTagsResponse.to_json( - analytics_admin.ListConnectedSiteTagsResponse() - ) - ) - request = analytics_admin.ListConnectedSiteTagsRequest() + request = analytics_admin.DeleteAdSenseLinkRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListConnectedSiteTagsResponse() - client.list_connected_site_tags( + client.delete_ad_sense_link( request, metadata=[ ("key", "val"), @@ -94669,11 +104577,10 @@ def test_list_connected_site_tags_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_list_connected_site_tags_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListConnectedSiteTagsRequest +def test_delete_ad_sense_link_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteAdSenseLinkRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -94681,7 +104588,7 @@ def test_list_connected_site_tags_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"name": "properties/sample1/adSenseLinks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -94693,10 +104600,64 @@ def test_list_connected_site_tags_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_connected_site_tags(request) + client.delete_ad_sense_link(request) -def test_list_connected_site_tags_rest_error(): +def test_delete_ad_sense_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "properties/sample1/adSenseLinks/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_ad_sense_link(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/adSenseLinks/*}" % client.transport._host, + args[1], + ) + + +def test_delete_ad_sense_link_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_ad_sense_link( + analytics_admin.DeleteAdSenseLinkRequest(), + name="name_value", + ) + + +def test_delete_ad_sense_link_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -94705,46 +104666,44 @@ def test_list_connected_site_tags_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.FetchConnectedGa4PropertyRequest, + analytics_admin.ListAdSenseLinksRequest, dict, ], ) -def test_fetch_connected_ga4_property_rest(request_type): +def test_list_ad_sense_links_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {} + request_init = {"parent": "properties/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.FetchConnectedGa4PropertyResponse( - property="property_value", + return_value = analytics_admin.ListAdSenseLinksResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.FetchConnectedGa4PropertyResponse.pb( - return_value - ) + return_value = analytics_admin.ListAdSenseLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_connected_ga4_property(request) + response = client.list_ad_sense_links(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) - assert response.property == "property_value" + assert isinstance(response, pagers.ListAdSenseLinksPager) + assert response.next_page_token == "next_page_token_value" -def test_fetch_connected_ga4_property_rest_use_cached_wrapped_rpc(): +def test_list_ad_sense_links_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -94759,8 +104718,7 @@ def test_fetch_connected_ga4_property_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_connected_ga4_property - in client._transport._wrapped_methods + client._transport.list_ad_sense_links in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -94769,29 +104727,29 @@ def test_fetch_connected_ga4_property_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_connected_ga4_property + client._transport.list_ad_sense_links ] = mock_rpc request = {} - client.fetch_connected_ga4_property(request) + client.list_ad_sense_links(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_connected_ga4_property(request) + client.list_ad_sense_links(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_fetch_connected_ga4_property_rest_required_fields( - request_type=analytics_admin.FetchConnectedGa4PropertyRequest, +def test_list_ad_sense_links_rest_required_fields( + request_type=analytics_admin.ListAdSenseLinksRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["property"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -94799,29 +104757,31 @@ def test_fetch_connected_ga4_property_rest_required_fields( ) # verify fields with default values are dropped - assert "property" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_connected_ga4_property._get_unset_required_fields(jsonified_request) + ).list_ad_sense_links._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "property" in jsonified_request - assert jsonified_request["property"] == request_init["property"] - jsonified_request["property"] = "property_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_connected_ga4_property._get_unset_required_fields(jsonified_request) + ).list_ad_sense_links._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("property",)) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "property" in jsonified_request - assert jsonified_request["property"] == "property_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -94830,7 +104790,7 @@ def test_fetch_connected_ga4_property_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.FetchConnectedGa4PropertyResponse() + return_value = analytics_admin.ListAdSenseLinksResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -94851,38 +104811,38 @@ def test_fetch_connected_ga4_property_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.FetchConnectedGa4PropertyResponse.pb( - return_value - ) + return_value = analytics_admin.ListAdSenseLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_connected_ga4_property(request) + response = client.list_ad_sense_links(request) - expected_params = [ - ( - "property", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_fetch_connected_ga4_property_rest_unset_required_fields(): +def test_list_ad_sense_links_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.fetch_connected_ga4_property._get_unset_required_fields({}) - assert set(unset_fields) == (set(("property",)) & set(("property",))) + unset_fields = transport.list_ad_sense_links._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_connected_ga4_property_rest_interceptors(null_interceptor): +def test_list_ad_sense_links_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -94895,16 +104855,14 @@ def test_fetch_connected_ga4_property_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "post_fetch_connected_ga4_property", + transports.AnalyticsAdminServiceRestInterceptor, "post_list_ad_sense_links" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, - "pre_fetch_connected_ga4_property", + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_ad_sense_links" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.FetchConnectedGa4PropertyRequest.pb( - analytics_admin.FetchConnectedGa4PropertyRequest() + pb_message = analytics_admin.ListAdSenseLinksRequest.pb( + analytics_admin.ListAdSenseLinksRequest() ) transcode.return_value = { "method": "post", @@ -94916,21 +104874,19 @@ def test_fetch_connected_ga4_property_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.FetchConnectedGa4PropertyResponse.to_json( - analytics_admin.FetchConnectedGa4PropertyResponse() - ) + req.return_value._content = analytics_admin.ListAdSenseLinksResponse.to_json( + analytics_admin.ListAdSenseLinksResponse() ) - request = analytics_admin.FetchConnectedGa4PropertyRequest() + request = analytics_admin.ListAdSenseLinksRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.FetchConnectedGa4PropertyResponse() + post.return_value = analytics_admin.ListAdSenseLinksResponse() - client.fetch_connected_ga4_property( + client.list_ad_sense_links( request, metadata=[ ("key", "val"), @@ -94938,84 +104894,200 @@ def test_fetch_connected_ga4_property_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() + pre.assert_called_once() + post.assert_called_once() + + +def test_list_ad_sense_links_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListAdSenseLinksRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_ad_sense_links(request) + + +def test_list_ad_sense_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListAdSenseLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "properties/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListAdSenseLinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_ad_sense_links(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=properties/*}/adSenseLinks" % client.transport._host, + args[1], + ) + + +def test_list_ad_sense_links_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_ad_sense_links( + analytics_admin.ListAdSenseLinksRequest(), + parent="parent_value", + ) -def test_fetch_connected_ga4_property_rest_bad_request( - transport: str = "rest", - request_type=analytics_admin.FetchConnectedGa4PropertyRequest, -): +def test_list_ad_sense_links_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token="abc", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token="def", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token="ghi", + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + ) + # Two responses for two calls + response = response + response - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.fetch_connected_ga4_property(request) + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListAdSenseLinksResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + sample_request = {"parent": "properties/sample1"} -def test_fetch_connected_ga4_property_rest_error(): - client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + pager = client.list_ad_sense_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AdSenseLink) for i in results) + + pages = list(client.list_ad_sense_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetAdSenseLinkRequest, + analytics_admin.GetEventCreateRuleRequest, dict, ], ) -def test_get_ad_sense_link_rest(request_type): +def test_get_event_create_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/adSenseLinks/sample2"} + request_init = { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AdSenseLink( + return_value = event_create_and_edit.EventCreateRule( name="name_value", - ad_client_code="ad_client_code_value", + destination_event="destination_event_value", + source_copy_parameters=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AdSenseLink.pb(return_value) + return_value = event_create_and_edit.EventCreateRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_ad_sense_link(request) + response = client.get_event_create_rule(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AdSenseLink) + assert isinstance(response, event_create_and_edit.EventCreateRule) assert response.name == "name_value" - assert response.ad_client_code == "ad_client_code_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True -def test_get_ad_sense_link_rest_use_cached_wrapped_rpc(): +def test_get_event_create_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -95029,7 +105101,10 @@ def test_get_ad_sense_link_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_ad_sense_link in client._transport._wrapped_methods + assert ( + client._transport.get_event_create_rule + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -95037,24 +105112,24 @@ def test_get_ad_sense_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_ad_sense_link + client._transport.get_event_create_rule ] = mock_rpc request = {} - client.get_ad_sense_link(request) + client.get_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_ad_sense_link(request) + client.get_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_ad_sense_link_rest_required_fields( - request_type=analytics_admin.GetAdSenseLinkRequest, +def test_get_event_create_rule_rest_required_fields( + request_type=analytics_admin.GetEventCreateRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -95070,7 +105145,7 @@ def test_get_ad_sense_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_ad_sense_link._get_unset_required_fields(jsonified_request) + ).get_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -95079,7 +105154,7 @@ def test_get_ad_sense_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_ad_sense_link._get_unset_required_fields(jsonified_request) + ).get_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -95093,7 +105168,7 @@ def test_get_ad_sense_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AdSenseLink() + return_value = event_create_and_edit.EventCreateRule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -95114,30 +105189,30 @@ def test_get_ad_sense_link_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AdSenseLink.pb(return_value) + return_value = event_create_and_edit.EventCreateRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_ad_sense_link(request) + response = client.get_event_create_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_ad_sense_link_rest_unset_required_fields(): +def test_get_event_create_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_ad_sense_link._get_unset_required_fields({}) + unset_fields = transport.get_event_create_rule._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_ad_sense_link_rest_interceptors(null_interceptor): +def test_get_event_create_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -95150,14 +105225,14 @@ def test_get_ad_sense_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_ad_sense_link" + transports.AnalyticsAdminServiceRestInterceptor, "post_get_event_create_rule" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_ad_sense_link" + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_event_create_rule" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.GetAdSenseLinkRequest.pb( - analytics_admin.GetAdSenseLinkRequest() + pb_message = analytics_admin.GetEventCreateRuleRequest.pb( + analytics_admin.GetEventCreateRuleRequest() ) transcode.return_value = { "method": "post", @@ -95169,19 +105244,19 @@ def test_get_ad_sense_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AdSenseLink.to_json( - resources.AdSenseLink() + req.return_value._content = event_create_and_edit.EventCreateRule.to_json( + event_create_and_edit.EventCreateRule() ) - request = analytics_admin.GetAdSenseLinkRequest() + request = analytics_admin.GetEventCreateRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AdSenseLink() + post.return_value = event_create_and_edit.EventCreateRule() - client.get_ad_sense_link( + client.get_event_create_rule( request, metadata=[ ("key", "val"), @@ -95193,8 +105268,8 @@ def test_get_ad_sense_link_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_ad_sense_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetAdSenseLinkRequest +def test_get_event_create_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetEventCreateRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -95202,7 +105277,9 @@ def test_get_ad_sense_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/adSenseLinks/sample2"} + request_init = { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -95214,10 +105291,10 @@ def test_get_ad_sense_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_ad_sense_link(request) + client.get_event_create_rule(request) -def test_get_ad_sense_link_rest_flattened(): +def test_get_event_create_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -95226,10 +105303,12 @@ def test_get_ad_sense_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AdSenseLink() + return_value = event_create_and_edit.EventCreateRule() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/adSenseLinks/sample2"} + sample_request = { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -95241,24 +105320,25 @@ def test_get_ad_sense_link_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AdSenseLink.pb(return_value) + return_value = event_create_and_edit.EventCreateRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_ad_sense_link(**mock_args) + client.get_event_create_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/adSenseLinks/*}" % client.transport._host, + "%s/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}" + % client.transport._host, args[1], ) -def test_get_ad_sense_link_rest_flattened_error(transport: str = "rest"): +def test_get_event_create_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -95267,13 +105347,13 @@ def test_get_ad_sense_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_ad_sense_link( - analytics_admin.GetAdSenseLinkRequest(), + client.get_event_create_rule( + analytics_admin.GetEventCreateRuleRequest(), name="name_value", ) -def test_get_ad_sense_link_rest_error(): +def test_get_event_create_rule_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -95282,117 +105362,44 @@ def test_get_ad_sense_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateAdSenseLinkRequest, + analytics_admin.ListEventCreateRulesRequest, dict, ], ) -def test_create_ad_sense_link_rest(request_type): +def test_list_event_create_rules_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} - request_init["adsense_link"] = { - "name": "name_value", - "ad_client_code": "ad_client_code_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateAdSenseLinkRequest.meta.fields["adsense_link"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["adsense_link"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["adsense_link"][field])): - del request_init["adsense_link"][field][i][subfield] - else: - del request_init["adsense_link"][field][subfield] + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AdSenseLink( - name="name_value", - ad_client_code="ad_client_code_value", + return_value = analytics_admin.ListEventCreateRulesResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AdSenseLink.pb(return_value) + return_value = analytics_admin.ListEventCreateRulesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_ad_sense_link(request) + response = client.list_event_create_rules(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.AdSenseLink) - assert response.name == "name_value" - assert response.ad_client_code == "ad_client_code_value" + assert isinstance(response, pagers.ListEventCreateRulesPager) + assert response.next_page_token == "next_page_token_value" -def test_create_ad_sense_link_rest_use_cached_wrapped_rpc(): +def test_list_event_create_rules_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -95407,7 +105414,8 @@ def test_create_ad_sense_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_ad_sense_link in client._transport._wrapped_methods + client._transport.list_event_create_rules + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -95416,24 +105424,24 @@ def test_create_ad_sense_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_ad_sense_link + client._transport.list_event_create_rules ] = mock_rpc request = {} - client.create_ad_sense_link(request) + client.list_event_create_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_ad_sense_link(request) + client.list_event_create_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_ad_sense_link_rest_required_fields( - request_type=analytics_admin.CreateAdSenseLinkRequest, +def test_list_event_create_rules_rest_required_fields( + request_type=analytics_admin.ListEventCreateRulesRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -95449,7 +105457,7 @@ def test_create_ad_sense_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_ad_sense_link._get_unset_required_fields(jsonified_request) + ).list_event_create_rules._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -95458,7 +105466,14 @@ def test_create_ad_sense_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_ad_sense_link._get_unset_required_fields(jsonified_request) + ).list_event_create_rules._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -95472,7 +105487,7 @@ def test_create_ad_sense_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.AdSenseLink() + return_value = analytics_admin.ListEventCreateRulesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -95484,48 +105499,47 @@ def test_create_ad_sense_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AdSenseLink.pb(return_value) + return_value = analytics_admin.ListEventCreateRulesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_ad_sense_link(request) + response = client.list_event_create_rules(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_ad_sense_link_rest_unset_required_fields(): +def test_list_event_create_rules_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_ad_sense_link._get_unset_required_fields({}) + unset_fields = transport.list_event_create_rules._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "adsenseLink", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_ad_sense_link_rest_interceptors(null_interceptor): +def test_list_event_create_rules_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -95538,14 +105552,14 @@ def test_create_ad_sense_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_ad_sense_link" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_event_create_rules" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_ad_sense_link" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_event_create_rules" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateAdSenseLinkRequest.pb( - analytics_admin.CreateAdSenseLinkRequest() + pb_message = analytics_admin.ListEventCreateRulesRequest.pb( + analytics_admin.ListEventCreateRulesRequest() ) transcode.return_value = { "method": "post", @@ -95557,19 +105571,21 @@ def test_create_ad_sense_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.AdSenseLink.to_json( - resources.AdSenseLink() + req.return_value._content = ( + analytics_admin.ListEventCreateRulesResponse.to_json( + analytics_admin.ListEventCreateRulesResponse() + ) ) - request = analytics_admin.CreateAdSenseLinkRequest() + request = analytics_admin.ListEventCreateRulesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.AdSenseLink() + post.return_value = analytics_admin.ListEventCreateRulesResponse() - client.create_ad_sense_link( + client.list_event_create_rules( request, metadata=[ ("key", "val"), @@ -95581,8 +105597,8 @@ def test_create_ad_sense_link_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_ad_sense_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateAdSenseLinkRequest +def test_list_event_create_rules_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListEventCreateRulesRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -95590,7 +105606,7 @@ def test_create_ad_sense_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -95602,10 +105618,10 @@ def test_create_ad_sense_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_ad_sense_link(request) + client.list_event_create_rules(request) -def test_create_ad_sense_link_rest_flattened(): +def test_list_event_create_rules_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -95614,15 +105630,14 @@ def test_create_ad_sense_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.AdSenseLink() + return_value = analytics_admin.ListEventCreateRulesResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - adsense_link=resources.AdSenseLink(name="name_value"), ) mock_args.update(sample_request) @@ -95630,24 +105645,25 @@ def test_create_ad_sense_link_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.AdSenseLink.pb(return_value) + return_value = analytics_admin.ListEventCreateRulesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_ad_sense_link(**mock_args) + client.list_event_create_rules(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/adSenseLinks" % client.transport._host, + "%s/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules" + % client.transport._host, args[1], ) -def test_create_ad_sense_link_rest_flattened_error(transport: str = "rest"): +def test_list_event_create_rules_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -95656,55 +105672,207 @@ def test_create_ad_sense_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_ad_sense_link( - analytics_admin.CreateAdSenseLinkRequest(), + client.list_event_create_rules( + analytics_admin.ListEventCreateRulesRequest(), parent="parent_value", - adsense_link=resources.AdSenseLink(name="name_value"), ) -def test_create_ad_sense_link_rest_error(): +def test_list_event_create_rules_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token="abc", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token="def", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token="ghi", + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + analytics_admin.ListEventCreateRulesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} + + pager = client.list_event_create_rules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, event_create_and_edit.EventCreateRule) for i in results + ) + + pages = list(client.list_event_create_rules(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteAdSenseLinkRequest, + analytics_admin.CreateEventCreateRuleRequest, dict, ], ) -def test_delete_ad_sense_link_rest(request_type): +def test_create_event_create_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/adSenseLinks/sample2"} + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request_init["event_create_rule"] = { + "name": "name_value", + "destination_event": "destination_event_value", + "event_conditions": [ + { + "field": "field_value", + "comparison_type": 1, + "value": "value_value", + "negated": True, + } + ], + "source_copy_parameters": True, + "parameter_mutations": [ + {"parameter": "parameter_value", "parameter_value": "parameter_value_value"} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateEventCreateRuleRequest.meta.fields[ + "event_create_rule" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event_create_rule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event_create_rule"][field])): + del request_init["event_create_rule"][field][i][subfield] + else: + del request_init["event_create_rule"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_ad_sense_link(request) + response = client.create_event_create_rule(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True -def test_delete_ad_sense_link_rest_use_cached_wrapped_rpc(): +def test_create_event_create_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -95719,7 +105887,8 @@ def test_delete_ad_sense_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_ad_sense_link in client._transport._wrapped_methods + client._transport.create_event_create_rule + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -95728,29 +105897,29 @@ def test_delete_ad_sense_link_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_ad_sense_link + client._transport.create_event_create_rule ] = mock_rpc request = {} - client.delete_ad_sense_link(request) + client.create_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_ad_sense_link(request) + client.create_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_ad_sense_link_rest_required_fields( - request_type=analytics_admin.DeleteAdSenseLinkRequest, +def test_create_event_create_rule_rest_required_fields( + request_type=analytics_admin.CreateEventCreateRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -95761,21 +105930,21 @@ def test_delete_ad_sense_link_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_ad_sense_link._get_unset_required_fields(jsonified_request) + ).create_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_ad_sense_link._get_unset_required_fields(jsonified_request) + ).create_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -95784,7 +105953,7 @@ def test_delete_ad_sense_link_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = event_create_and_edit.EventCreateRule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -95796,36 +105965,48 @@ def test_delete_ad_sense_link_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_ad_sense_link(request) + response = client.create_event_create_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_ad_sense_link_rest_unset_required_fields(): +def test_create_event_create_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_ad_sense_link._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_event_create_rule._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "eventCreateRule", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_ad_sense_link_rest_interceptors(null_interceptor): +def test_create_event_create_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -95838,11 +106019,14 @@ def test_delete_ad_sense_link_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_ad_sense_link" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_event_create_rule" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_event_create_rule" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteAdSenseLinkRequest.pb( - analytics_admin.DeleteAdSenseLinkRequest() + post.assert_not_called() + pb_message = analytics_admin.CreateEventCreateRuleRequest.pb( + analytics_admin.CreateEventCreateRuleRequest() ) transcode.return_value = { "method": "post", @@ -95854,15 +106038,19 @@ def test_delete_ad_sense_link_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = event_create_and_edit.EventCreateRule.to_json( + event_create_and_edit.EventCreateRule() + ) - request = analytics_admin.DeleteAdSenseLinkRequest() + request = analytics_admin.CreateEventCreateRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventCreateRule() - client.delete_ad_sense_link( + client.create_event_create_rule( request, metadata=[ ("key", "val"), @@ -95871,10 +106059,11 @@ def test_delete_ad_sense_link_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_ad_sense_link_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteAdSenseLinkRequest +def test_create_event_create_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateEventCreateRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -95882,7 +106071,7 @@ def test_delete_ad_sense_link_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "properties/sample1/adSenseLinks/sample2"} + request_init = {"parent": "properties/sample1/dataStreams/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -95894,10 +106083,10 @@ def test_delete_ad_sense_link_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_ad_sense_link(request) + client.create_event_create_rule(request) -def test_delete_ad_sense_link_rest_flattened(): +def test_create_event_create_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -95906,37 +106095,41 @@ def test_delete_ad_sense_link_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = event_create_and_edit.EventCreateRule() # get arguments that satisfy an http rule for this method - sample_request = {"name": "properties/sample1/adSenseLinks/sample2"} + sample_request = {"parent": "properties/sample1/dataStreams/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_ad_sense_link(**mock_args) + client.create_event_create_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/adSenseLinks/*}" % client.transport._host, + "%s/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules" + % client.transport._host, args[1], ) -def test_delete_ad_sense_link_rest_flattened_error(transport: str = "rest"): +def test_create_event_create_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -95945,13 +106138,14 @@ def test_delete_ad_sense_link_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_ad_sense_link( - analytics_admin.DeleteAdSenseLinkRequest(), - name="name_value", + client.create_event_create_rule( + analytics_admin.CreateEventCreateRuleRequest(), + parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), ) -def test_delete_ad_sense_link_rest_error(): +def test_create_event_create_rule_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -95960,44 +106154,137 @@ def test_delete_ad_sense_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListAdSenseLinksRequest, + analytics_admin.UpdateEventCreateRuleRequest, dict, ], ) -def test_list_ad_sense_links_rest(request_type): +def test_update_event_create_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "event_create_rule": { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + } + } + request_init["event_create_rule"] = { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3", + "destination_event": "destination_event_value", + "event_conditions": [ + { + "field": "field_value", + "comparison_type": 1, + "value": "value_value", + "negated": True, + } + ], + "source_copy_parameters": True, + "parameter_mutations": [ + {"parameter": "parameter_value", "parameter_value": "parameter_value_value"} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateEventCreateRuleRequest.meta.fields[ + "event_create_rule" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event_create_rule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event_create_rule"][field])): + del request_init["event_create_rule"][field][i][subfield] + else: + del request_init["event_create_rule"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAdSenseLinksResponse( - next_page_token="next_page_token_value", + return_value = event_create_and_edit.EventCreateRule( + name="name_value", + destination_event="destination_event_value", + source_copy_parameters=True, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAdSenseLinksResponse.pb(return_value) + return_value = event_create_and_edit.EventCreateRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_ad_sense_links(request) + response = client.update_event_create_rule(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAdSenseLinksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == "name_value" + assert response.destination_event == "destination_event_value" + assert response.source_copy_parameters is True -def test_list_ad_sense_links_rest_use_cached_wrapped_rpc(): +def test_update_event_create_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -96012,7 +106299,8 @@ def test_list_ad_sense_links_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_ad_sense_links in client._transport._wrapped_methods + client._transport.update_event_create_rule + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -96021,29 +106309,28 @@ def test_list_ad_sense_links_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_ad_sense_links + client._transport.update_event_create_rule ] = mock_rpc request = {} - client.list_ad_sense_links(request) + client.update_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_ad_sense_links(request) + client.update_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_ad_sense_links_rest_required_fields( - request_type=analytics_admin.ListAdSenseLinksRequest, +def test_update_event_create_rule_rest_required_fields( + request_type=analytics_admin.UpdateEventCreateRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -96054,28 +106341,19 @@ def test_list_ad_sense_links_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_ad_sense_links._get_unset_required_fields(jsonified_request) + ).update_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_ad_sense_links._get_unset_required_fields(jsonified_request) + ).update_event_create_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -96084,7 +106362,7 @@ def test_list_ad_sense_links_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAdSenseLinksResponse() + return_value = event_create_and_edit.EventCreateRule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -96096,47 +106374,48 @@ def test_list_ad_sense_links_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAdSenseLinksResponse.pb(return_value) + return_value = event_create_and_edit.EventCreateRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_ad_sense_links(request) + response = client.update_event_create_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_ad_sense_links_rest_unset_required_fields(): +def test_update_event_create_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_ad_sense_links._get_unset_required_fields({}) + unset_fields = transport.update_event_create_rule._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(("updateMask",)) + & set( ( - "pageSize", - "pageToken", + "eventCreateRule", + "updateMask", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_ad_sense_links_rest_interceptors(null_interceptor): +def test_update_event_create_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -96149,14 +106428,14 @@ def test_list_ad_sense_links_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_ad_sense_links" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_event_create_rule" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_ad_sense_links" + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_event_create_rule" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListAdSenseLinksRequest.pb( - analytics_admin.ListAdSenseLinksRequest() + pb_message = analytics_admin.UpdateEventCreateRuleRequest.pb( + analytics_admin.UpdateEventCreateRuleRequest() ) transcode.return_value = { "method": "post", @@ -96168,19 +106447,19 @@ def test_list_ad_sense_links_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.ListAdSenseLinksResponse.to_json( - analytics_admin.ListAdSenseLinksResponse() + req.return_value._content = event_create_and_edit.EventCreateRule.to_json( + event_create_and_edit.EventCreateRule() ) - request = analytics_admin.ListAdSenseLinksRequest() + request = analytics_admin.UpdateEventCreateRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListAdSenseLinksResponse() + post.return_value = event_create_and_edit.EventCreateRule() - client.list_ad_sense_links( + client.update_event_create_rule( request, metadata=[ ("key", "val"), @@ -96192,8 +106471,8 @@ def test_list_ad_sense_links_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_ad_sense_links_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListAdSenseLinksRequest +def test_update_event_create_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateEventCreateRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -96201,7 +106480,11 @@ def test_list_ad_sense_links_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "properties/sample1"} + request_init = { + "event_create_rule": { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -96213,10 +106496,10 @@ def test_list_ad_sense_links_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_ad_sense_links(request) + client.update_event_create_rule(request) -def test_list_ad_sense_links_rest_flattened(): +def test_update_event_create_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -96225,14 +106508,19 @@ def test_list_ad_sense_links_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListAdSenseLinksResponse() + return_value = event_create_and_edit.EventCreateRule() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "properties/sample1"} + sample_request = { + "event_create_rule": { + "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -96240,24 +106528,25 @@ def test_list_ad_sense_links_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListAdSenseLinksResponse.pb(return_value) + return_value = event_create_and_edit.EventCreateRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_ad_sense_links(**mock_args) + client.update_event_create_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*}/adSenseLinks" % client.transport._host, + "%s/v1alpha/{event_create_rule.name=properties/*/dataStreams/*/eventCreateRules/*}" + % client.transport._host, args[1], ) -def test_list_ad_sense_links_rest_flattened_error(transport: str = "rest"): +def test_update_event_create_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -96266,83 +106555,27 @@ def test_list_ad_sense_links_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_ad_sense_links( - analytics_admin.ListAdSenseLinksRequest(), - parent="parent_value", + client.update_event_create_rule( + analytics_admin.UpdateEventCreateRuleRequest(), + event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_ad_sense_links_rest_pager(transport: str = "rest"): +def test_update_event_create_rule_rest_error(): client = AnalyticsAdminServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - next_page_token="abc", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[], - next_page_token="def", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - ], - next_page_token="ghi", - ), - analytics_admin.ListAdSenseLinksResponse( - adsense_links=[ - resources.AdSenseLink(), - resources.AdSenseLink(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - analytics_admin.ListAdSenseLinksResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "properties/sample1"} - - pager = client.list_ad_sense_links(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.AdSenseLink) for i in results) - - pages = list(client.list_ad_sense_links(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - analytics_admin.GetEventCreateRuleRequest, + analytics_admin.DeleteEventCreateRuleRequest, dict, ], ) -def test_get_event_create_rule_rest(request_type): +def test_delete_event_create_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -96357,31 +106590,22 @@ def test_get_event_create_rule_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule( - name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_event_create_rule(request) + response = client.delete_event_create_rule(request) # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) - assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert response is None -def test_get_event_create_rule_rest_use_cached_wrapped_rpc(): +def test_delete_event_create_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -96396,7 +106620,7 @@ def test_get_event_create_rule_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_event_create_rule + client._transport.delete_event_create_rule in client._transport._wrapped_methods ) @@ -96406,24 +106630,24 @@ def test_get_event_create_rule_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_event_create_rule + client._transport.delete_event_create_rule ] = mock_rpc request = {} - client.get_event_create_rule(request) + client.delete_event_create_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_event_create_rule(request) + client.delete_event_create_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_event_create_rule_rest_required_fields( - request_type=analytics_admin.GetEventCreateRuleRequest, +def test_delete_event_create_rule_rest_required_fields( + request_type=analytics_admin.DeleteEventCreateRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -96439,7 +106663,7 @@ def test_get_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_event_create_rule._get_unset_required_fields(jsonified_request) + ).delete_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -96448,7 +106672,7 @@ def test_get_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_event_create_rule._get_unset_required_fields(jsonified_request) + ).delete_event_create_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -96462,7 +106686,7 @@ def test_get_event_create_rule_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -96474,39 +106698,36 @@ def test_get_event_create_rule_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_event_create_rule(request) + response = client.delete_event_create_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_event_create_rule_rest_unset_required_fields(): +def test_delete_event_create_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_event_create_rule._get_unset_required_fields({}) + unset_fields = transport.delete_event_create_rule._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_event_create_rule_rest_interceptors(null_interceptor): +def test_delete_event_create_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -96519,14 +106740,11 @@ def test_get_event_create_rule_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_get_event_create_rule" - ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_get_event_create_rule" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_event_create_rule" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = analytics_admin.GetEventCreateRuleRequest.pb( - analytics_admin.GetEventCreateRuleRequest() + pb_message = analytics_admin.DeleteEventCreateRuleRequest.pb( + analytics_admin.DeleteEventCreateRuleRequest() ) transcode.return_value = { "method": "post", @@ -96538,19 +106756,15 @@ def test_get_event_create_rule_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = event_create_and_edit.EventCreateRule.to_json( - event_create_and_edit.EventCreateRule() - ) - request = analytics_admin.GetEventCreateRuleRequest() + request = analytics_admin.DeleteEventCreateRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = event_create_and_edit.EventCreateRule() - client.get_event_create_rule( + client.delete_event_create_rule( request, metadata=[ ("key", "val"), @@ -96559,11 +106773,10 @@ def test_get_event_create_rule_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_get_event_create_rule_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.GetEventCreateRuleRequest +def test_delete_event_create_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteEventCreateRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -96585,10 +106798,10 @@ def test_get_event_create_rule_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_event_create_rule(request) + client.delete_event_create_rule(request) -def test_get_event_create_rule_rest_flattened(): +def test_delete_event_create_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -96597,7 +106810,7 @@ def test_get_event_create_rule_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { @@ -96610,29 +106823,344 @@ def test_get_event_create_rule_rest_flattened(): ) mock_args.update(sample_request) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_event_create_rule(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_event_create_rule_rest_flattened_error(transport: str = "rest"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event_create_rule( + analytics_admin.DeleteEventCreateRuleRequest(), + name="name_value", + ) + + +def test_delete_event_create_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.GetEventEditRuleRequest, + dict, + ], +) +def test_get_event_edit_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventEditRule( + name="name_value", + display_name="display_name_value", + processing_order=1720, + ) + # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.get_event_edit_rule(request) - client.get_event_create_rule(**mock_args) + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 + + +def test_get_event_edit_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_event_edit_rule in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_event_edit_rule + ] = mock_rpc + + request = {} + client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_event_edit_rule_rest_required_fields( + request_type=analytics_admin.GetEventEditRuleRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_event_edit_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_event_edit_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventEditRule() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_event_edit_rule(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_event_edit_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_event_edit_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_edit_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "post_get_event_edit_rule" + ) as post, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_get_event_edit_rule" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetEventEditRuleRequest.pb( + analytics_admin.GetEventEditRuleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = event_create_and_edit.EventEditRule.to_json( + event_create_and_edit.EventEditRule() + ) + + request = analytics_admin.GetEventEditRuleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventEditRule() + + client.get_event_edit_rule( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_edit_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.GetEventEditRuleRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_event_edit_rule(request) + + +def test_get_event_edit_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventEditRule() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_event_edit_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}" + "%s/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}" % client.transport._host, args[1], ) -def test_get_event_create_rule_rest_flattened_error(transport: str = "rest"): +def test_get_event_edit_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -96641,13 +107169,13 @@ def test_get_event_create_rule_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_event_create_rule( - analytics_admin.GetEventCreateRuleRequest(), + client.get_event_edit_rule( + analytics_admin.GetEventEditRuleRequest(), name="name_value", ) -def test_get_event_create_rule_rest_error(): +def test_get_event_edit_rule_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -96656,11 +107184,11 @@ def test_get_event_create_rule_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.ListEventCreateRulesRequest, + analytics_admin.ListEventEditRulesRequest, dict, ], ) -def test_list_event_create_rules_rest(request_type): +def test_list_event_edit_rules_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -96673,7 +107201,7 @@ def test_list_event_create_rules_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListEventCreateRulesResponse( + return_value = analytics_admin.ListEventEditRulesResponse( next_page_token="next_page_token_value", ) @@ -96681,19 +107209,19 @@ def test_list_event_create_rules_rest(request_type): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListEventCreateRulesResponse.pb(return_value) + return_value = analytics_admin.ListEventEditRulesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_event_create_rules(request) + response = client.list_event_edit_rules(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEventCreateRulesPager) + assert isinstance(response, pagers.ListEventEditRulesPager) assert response.next_page_token == "next_page_token_value" -def test_list_event_create_rules_rest_use_cached_wrapped_rpc(): +def test_list_event_edit_rules_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -96708,7 +107236,7 @@ def test_list_event_create_rules_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_event_create_rules + client._transport.list_event_edit_rules in client._transport._wrapped_methods ) @@ -96718,24 +107246,24 @@ def test_list_event_create_rules_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_event_create_rules + client._transport.list_event_edit_rules ] = mock_rpc request = {} - client.list_event_create_rules(request) + client.list_event_edit_rules(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_event_create_rules(request) + client.list_event_edit_rules(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_event_create_rules_rest_required_fields( - request_type=analytics_admin.ListEventCreateRulesRequest, +def test_list_event_edit_rules_rest_required_fields( + request_type=analytics_admin.ListEventEditRulesRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -96751,7 +107279,7 @@ def test_list_event_create_rules_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_event_create_rules._get_unset_required_fields(jsonified_request) + ).list_event_edit_rules._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -96760,7 +107288,7 @@ def test_list_event_create_rules_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_event_create_rules._get_unset_required_fields(jsonified_request) + ).list_event_edit_rules._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -96781,7 +107309,7 @@ def test_list_event_create_rules_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListEventCreateRulesResponse() + return_value = analytics_admin.ListEventEditRulesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -96802,25 +107330,25 @@ def test_list_event_create_rules_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListEventCreateRulesResponse.pb(return_value) + return_value = analytics_admin.ListEventEditRulesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_event_create_rules(request) + response = client.list_event_edit_rules(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_event_create_rules_rest_unset_required_fields(): +def test_list_event_edit_rules_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_event_create_rules._get_unset_required_fields({}) + unset_fields = transport.list_event_edit_rules._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -96833,7 +107361,7 @@ def test_list_event_create_rules_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_event_create_rules_rest_interceptors(null_interceptor): +def test_list_event_edit_rules_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -96846,14 +107374,14 @@ def test_list_event_create_rules_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_list_event_create_rules" + transports.AnalyticsAdminServiceRestInterceptor, "post_list_event_edit_rules" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_list_event_create_rules" + transports.AnalyticsAdminServiceRestInterceptor, "pre_list_event_edit_rules" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.ListEventCreateRulesRequest.pb( - analytics_admin.ListEventCreateRulesRequest() + pb_message = analytics_admin.ListEventEditRulesRequest.pb( + analytics_admin.ListEventEditRulesRequest() ) transcode.return_value = { "method": "post", @@ -96865,21 +107393,19 @@ def test_list_event_create_rules_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - analytics_admin.ListEventCreateRulesResponse.to_json( - analytics_admin.ListEventCreateRulesResponse() - ) + req.return_value._content = analytics_admin.ListEventEditRulesResponse.to_json( + analytics_admin.ListEventEditRulesResponse() ) - request = analytics_admin.ListEventCreateRulesRequest() + request = analytics_admin.ListEventEditRulesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.ListEventCreateRulesResponse() + post.return_value = analytics_admin.ListEventEditRulesResponse() - client.list_event_create_rules( + client.list_event_edit_rules( request, metadata=[ ("key", "val"), @@ -96891,8 +107417,8 @@ def test_list_event_create_rules_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_event_create_rules_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.ListEventCreateRulesRequest +def test_list_event_edit_rules_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ListEventEditRulesRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -96912,10 +107438,10 @@ def test_list_event_create_rules_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_event_create_rules(request) + client.list_event_edit_rules(request) -def test_list_event_create_rules_rest_flattened(): +def test_list_event_edit_rules_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -96924,7 +107450,7 @@ def test_list_event_create_rules_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.ListEventCreateRulesResponse() + return_value = analytics_admin.ListEventEditRulesResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1/dataStreams/sample2"} @@ -96939,25 +107465,25 @@ def test_list_event_create_rules_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.ListEventCreateRulesResponse.pb(return_value) + return_value = analytics_admin.ListEventEditRulesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_event_create_rules(**mock_args) + client.list_event_edit_rules(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules" + "%s/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules" % client.transport._host, args[1], ) -def test_list_event_create_rules_rest_flattened_error(transport: str = "rest"): +def test_list_event_edit_rules_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -96966,13 +107492,13 @@ def test_list_event_create_rules_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_event_create_rules( - analytics_admin.ListEventCreateRulesRequest(), + client.list_event_edit_rules( + analytics_admin.ListEventEditRulesRequest(), parent="parent_value", ) -def test_list_event_create_rules_rest_pager(transport: str = "rest"): +def test_list_event_edit_rules_rest_pager(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -96984,28 +107510,28 @@ def test_list_event_create_rules_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), ], next_page_token="abc", ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[], + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], next_page_token="def", ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), ], next_page_token="ghi", ), - analytics_admin.ListEventCreateRulesResponse( - event_create_rules=[ - event_create_and_edit.EventCreateRule(), - event_create_and_edit.EventCreateRule(), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), ], ), ) @@ -97014,7 +107540,7 @@ def test_list_event_create_rules_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - analytics_admin.ListEventCreateRulesResponse.to_json(x) for x in response + analytics_admin.ListEventEditRulesResponse.to_json(x) for x in response ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): @@ -97024,15 +107550,13 @@ def test_list_event_create_rules_rest_pager(transport: str = "rest"): sample_request = {"parent": "properties/sample1/dataStreams/sample2"} - pager = client.list_event_create_rules(request=sample_request) + pager = client.list_event_edit_rules(request=sample_request) results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, event_create_and_edit.EventCreateRule) for i in results - ) + assert all(isinstance(i, event_create_and_edit.EventEditRule) for i in results) - pages = list(client.list_event_create_rules(request=sample_request).pages) + pages = list(client.list_event_edit_rules(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -97040,11 +107564,11 @@ def test_list_event_create_rules_rest_pager(transport: str = "rest"): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateEventCreateRuleRequest, + analytics_admin.CreateEventEditRuleRequest, dict, ], ) -def test_create_event_create_rule_rest(request_type): +def test_create_event_edit_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -97052,9 +107576,9 @@ def test_create_event_create_rule_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "properties/sample1/dataStreams/sample2"} - request_init["event_create_rule"] = { + request_init["event_edit_rule"] = { "name": "name_value", - "destination_event": "destination_event_value", + "display_name": "display_name_value", "event_conditions": [ { "field": "field_value", @@ -97063,18 +107587,18 @@ def test_create_event_create_rule_rest(request_type): "negated": True, } ], - "source_copy_parameters": True, "parameter_mutations": [ {"parameter": "parameter_value", "parameter_value": "parameter_value_value"} ], + "processing_order": 1720, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.CreateEventCreateRuleRequest.meta.fields[ - "event_create_rule" + test_field = analytics_admin.CreateEventEditRuleRequest.meta.fields[ + "event_edit_rule" ] def get_message_fields(field): @@ -97103,7 +107627,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["event_create_rule"].items(): # pragma: NO COVER + for field, value in request_init["event_edit_rule"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -97133,40 +107657,40 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["event_create_rule"][field])): - del request_init["event_create_rule"][field][i][subfield] + for i in range(0, len(request_init["event_edit_rule"][field])): + del request_init["event_edit_rule"][field][i][subfield] else: - del request_init["event_create_rule"][field][subfield] + del request_init["event_edit_rule"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule( + return_value = event_create_and_edit.EventEditRule( name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, + display_name="display_name_value", + processing_order=1720, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_event_create_rule(request) + response = client.create_event_edit_rule(request) # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) + assert isinstance(response, event_create_and_edit.EventEditRule) assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 -def test_create_event_create_rule_rest_use_cached_wrapped_rpc(): +def test_create_event_edit_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -97181,7 +107705,7 @@ def test_create_event_create_rule_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_event_create_rule + client._transport.create_event_edit_rule in client._transport._wrapped_methods ) @@ -97191,24 +107715,24 @@ def test_create_event_create_rule_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_event_create_rule + client._transport.create_event_edit_rule ] = mock_rpc request = {} - client.create_event_create_rule(request) + client.create_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_event_create_rule(request) + client.create_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_event_create_rule_rest_required_fields( - request_type=analytics_admin.CreateEventCreateRuleRequest, +def test_create_event_edit_rule_rest_required_fields( + request_type=analytics_admin.CreateEventEditRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -97224,7 +107748,7 @@ def test_create_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_event_create_rule._get_unset_required_fields(jsonified_request) + ).create_event_edit_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -97233,7 +107757,7 @@ def test_create_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_event_create_rule._get_unset_required_fields(jsonified_request) + ).create_event_edit_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -97247,7 +107771,7 @@ def test_create_event_create_rule_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule() + return_value = event_create_and_edit.EventEditRule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -97269,38 +107793,38 @@ def test_create_event_create_rule_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_event_create_rule(request) + response = client.create_event_edit_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_event_create_rule_rest_unset_required_fields(): +def test_create_event_edit_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_event_create_rule._get_unset_required_fields({}) + unset_fields = transport.create_event_edit_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( "parent", - "eventCreateRule", + "eventEditRule", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_event_create_rule_rest_interceptors(null_interceptor): +def test_create_event_edit_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -97313,14 +107837,14 @@ def test_create_event_create_rule_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_event_create_rule" + transports.AnalyticsAdminServiceRestInterceptor, "post_create_event_edit_rule" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_event_create_rule" + transports.AnalyticsAdminServiceRestInterceptor, "pre_create_event_edit_rule" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateEventCreateRuleRequest.pb( - analytics_admin.CreateEventCreateRuleRequest() + pb_message = analytics_admin.CreateEventEditRuleRequest.pb( + analytics_admin.CreateEventEditRuleRequest() ) transcode.return_value = { "method": "post", @@ -97332,19 +107856,19 @@ def test_create_event_create_rule_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = event_create_and_edit.EventCreateRule.to_json( - event_create_and_edit.EventCreateRule() + req.return_value._content = event_create_and_edit.EventEditRule.to_json( + event_create_and_edit.EventEditRule() ) - request = analytics_admin.CreateEventCreateRuleRequest() + request = analytics_admin.CreateEventEditRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = event_create_and_edit.EventCreateRule() + post.return_value = event_create_and_edit.EventEditRule() - client.create_event_create_rule( + client.create_event_edit_rule( request, metadata=[ ("key", "val"), @@ -97356,8 +107880,8 @@ def test_create_event_create_rule_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_event_create_rule_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateEventCreateRuleRequest +def test_create_event_edit_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.CreateEventEditRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -97377,10 +107901,10 @@ def test_create_event_create_rule_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_event_create_rule(request) + client.create_event_edit_rule(request) -def test_create_event_create_rule_rest_flattened(): +def test_create_event_edit_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -97389,7 +107913,7 @@ def test_create_event_create_rule_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule() + return_value = event_create_and_edit.EventEditRule() # get arguments that satisfy an http rule for this method sample_request = {"parent": "properties/sample1/dataStreams/sample2"} @@ -97397,7 +107921,7 @@ def test_create_event_create_rule_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), ) mock_args.update(sample_request) @@ -97405,25 +107929,25 @@ def test_create_event_create_rule_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_event_create_rule(**mock_args) + client.create_event_edit_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules" + "%s/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules" % client.transport._host, args[1], ) -def test_create_event_create_rule_rest_flattened_error(transport: str = "rest"): +def test_create_event_edit_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -97432,14 +107956,14 @@ def test_create_event_create_rule_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_event_create_rule( - analytics_admin.CreateEventCreateRuleRequest(), + client.create_event_edit_rule( + analytics_admin.CreateEventEditRuleRequest(), parent="parent_value", - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), ) -def test_create_event_create_rule_rest_error(): +def test_create_event_edit_rule_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -97448,11 +107972,11 @@ def test_create_event_create_rule_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.UpdateEventCreateRuleRequest, + analytics_admin.UpdateEventEditRuleRequest, dict, ], ) -def test_update_event_create_rule_rest(request_type): +def test_update_event_edit_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -97460,13 +107984,13 @@ def test_update_event_create_rule_rest(request_type): # send a request that will satisfy transcoding request_init = { - "event_create_rule": { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + "event_edit_rule": { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" } } - request_init["event_create_rule"] = { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3", - "destination_event": "destination_event_value", + request_init["event_edit_rule"] = { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3", + "display_name": "display_name_value", "event_conditions": [ { "field": "field_value", @@ -97475,18 +107999,18 @@ def test_update_event_create_rule_rest(request_type): "negated": True, } ], - "source_copy_parameters": True, "parameter_mutations": [ {"parameter": "parameter_value", "parameter_value": "parameter_value_value"} ], + "processing_order": 1720, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = analytics_admin.UpdateEventCreateRuleRequest.meta.fields[ - "event_create_rule" + test_field = analytics_admin.UpdateEventEditRuleRequest.meta.fields[ + "event_edit_rule" ] def get_message_fields(field): @@ -97515,7 +108039,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["event_create_rule"].items(): # pragma: NO COVER + for field, value in request_init["event_edit_rule"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -97545,40 +108069,40 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["event_create_rule"][field])): - del request_init["event_create_rule"][field][i][subfield] + for i in range(0, len(request_init["event_edit_rule"][field])): + del request_init["event_edit_rule"][field][i][subfield] else: - del request_init["event_create_rule"][field][subfield] + del request_init["event_edit_rule"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule( + return_value = event_create_and_edit.EventEditRule( name="name_value", - destination_event="destination_event_value", - source_copy_parameters=True, + display_name="display_name_value", + processing_order=1720, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_event_create_rule(request) + response = client.update_event_edit_rule(request) # Establish that the response is the type that we expect. - assert isinstance(response, event_create_and_edit.EventCreateRule) + assert isinstance(response, event_create_and_edit.EventEditRule) assert response.name == "name_value" - assert response.destination_event == "destination_event_value" - assert response.source_copy_parameters is True + assert response.display_name == "display_name_value" + assert response.processing_order == 1720 -def test_update_event_create_rule_rest_use_cached_wrapped_rpc(): +def test_update_event_edit_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -97593,7 +108117,7 @@ def test_update_event_create_rule_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_event_create_rule + client._transport.update_event_edit_rule in client._transport._wrapped_methods ) @@ -97603,24 +108127,24 @@ def test_update_event_create_rule_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_event_create_rule + client._transport.update_event_edit_rule ] = mock_rpc request = {} - client.update_event_create_rule(request) + client.update_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_event_create_rule(request) + client.update_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_event_create_rule_rest_required_fields( - request_type=analytics_admin.UpdateEventCreateRuleRequest, +def test_update_event_edit_rule_rest_required_fields( + request_type=analytics_admin.UpdateEventEditRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -97635,14 +108159,14 @@ def test_update_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_event_create_rule._get_unset_required_fields(jsonified_request) + ).update_event_edit_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_event_create_rule._get_unset_required_fields(jsonified_request) + ).update_event_edit_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) @@ -97656,7 +108180,7 @@ def test_update_event_create_rule_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule() + return_value = event_create_and_edit.EventEditRule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -97678,30 +108202,30 @@ def test_update_event_create_rule_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_event_create_rule(request) + response = client.update_event_edit_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_event_create_rule_rest_unset_required_fields(): +def test_update_event_edit_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_event_create_rule._get_unset_required_fields({}) + unset_fields = transport.update_event_edit_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("updateMask",)) & set( ( - "eventCreateRule", + "eventEditRule", "updateMask", ) ) @@ -97709,7 +108233,7 @@ def test_update_event_create_rule_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_event_create_rule_rest_interceptors(null_interceptor): +def test_update_event_edit_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -97722,14 +108246,14 @@ def test_update_event_create_rule_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_update_event_create_rule" + transports.AnalyticsAdminServiceRestInterceptor, "post_update_event_edit_rule" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_update_event_create_rule" + transports.AnalyticsAdminServiceRestInterceptor, "pre_update_event_edit_rule" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.UpdateEventCreateRuleRequest.pb( - analytics_admin.UpdateEventCreateRuleRequest() + pb_message = analytics_admin.UpdateEventEditRuleRequest.pb( + analytics_admin.UpdateEventEditRuleRequest() ) transcode.return_value = { "method": "post", @@ -97741,19 +108265,19 @@ def test_update_event_create_rule_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = event_create_and_edit.EventCreateRule.to_json( - event_create_and_edit.EventCreateRule() + req.return_value._content = event_create_and_edit.EventEditRule.to_json( + event_create_and_edit.EventEditRule() ) - request = analytics_admin.UpdateEventCreateRuleRequest() + request = analytics_admin.UpdateEventEditRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = event_create_and_edit.EventCreateRule() + post.return_value = event_create_and_edit.EventEditRule() - client.update_event_create_rule( + client.update_event_edit_rule( request, metadata=[ ("key", "val"), @@ -97765,8 +108289,8 @@ def test_update_event_create_rule_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_event_create_rule_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.UpdateEventCreateRuleRequest +def test_update_event_edit_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.UpdateEventEditRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -97775,8 +108299,8 @@ def test_update_event_create_rule_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "event_create_rule": { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + "event_edit_rule": { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" } } request = request_type(**request_init) @@ -97790,10 +108314,10 @@ def test_update_event_create_rule_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_event_create_rule(request) + client.update_event_edit_rule(request) -def test_update_event_create_rule_rest_flattened(): +def test_update_event_edit_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -97802,18 +108326,18 @@ def test_update_event_create_rule_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = event_create_and_edit.EventCreateRule() + return_value = event_create_and_edit.EventEditRule() # get arguments that satisfy an http rule for this method sample_request = { - "event_create_rule": { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + "event_edit_rule": { + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" } } # get truthy value for each flattened field mock_args = dict( - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -97822,25 +108346,25 @@ def test_update_event_create_rule_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = event_create_and_edit.EventCreateRule.pb(return_value) + return_value = event_create_and_edit.EventEditRule.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_event_create_rule(**mock_args) + client.update_event_edit_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{event_create_rule.name=properties/*/dataStreams/*/eventCreateRules/*}" + "%s/v1alpha/{event_edit_rule.name=properties/*/dataStreams/*/eventEditRules/*}" % client.transport._host, args[1], ) -def test_update_event_create_rule_rest_flattened_error(transport: str = "rest"): +def test_update_event_edit_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -97849,14 +108373,14 @@ def test_update_event_create_rule_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_event_create_rule( - analytics_admin.UpdateEventCreateRuleRequest(), - event_create_rule=event_create_and_edit.EventCreateRule(name="name_value"), + client.update_event_edit_rule( + analytics_admin.UpdateEventEditRuleRequest(), + event_edit_rule=event_create_and_edit.EventEditRule(name="name_value"), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_event_create_rule_rest_error(): +def test_update_event_edit_rule_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -97865,11 +108389,11 @@ def test_update_event_create_rule_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.DeleteEventCreateRuleRequest, + analytics_admin.DeleteEventEditRuleRequest, dict, ], ) -def test_delete_event_create_rule_rest(request_type): +def test_delete_event_edit_rule_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -97877,7 +108401,7 @@ def test_delete_event_create_rule_rest(request_type): # send a request that will satisfy transcoding request_init = { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" } request = request_type(**request_init) @@ -97893,13 +108417,13 @@ def test_delete_event_create_rule_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_event_create_rule(request) + response = client.delete_event_edit_rule(request) # Establish that the response is the type that we expect. assert response is None -def test_delete_event_create_rule_rest_use_cached_wrapped_rpc(): +def test_delete_event_edit_rule_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -97914,7 +108438,7 @@ def test_delete_event_create_rule_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_event_create_rule + client._transport.delete_event_edit_rule in client._transport._wrapped_methods ) @@ -97924,24 +108448,24 @@ def test_delete_event_create_rule_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_event_create_rule + client._transport.delete_event_edit_rule ] = mock_rpc request = {} - client.delete_event_create_rule(request) + client.delete_event_edit_rule(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_event_create_rule(request) + client.delete_event_edit_rule(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_event_create_rule_rest_required_fields( - request_type=analytics_admin.DeleteEventCreateRuleRequest, +def test_delete_event_edit_rule_rest_required_fields( + request_type=analytics_admin.DeleteEventEditRuleRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport @@ -97957,7 +108481,7 @@ def test_delete_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_event_create_rule._get_unset_required_fields(jsonified_request) + ).delete_event_edit_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -97966,7 +108490,7 @@ def test_delete_event_create_rule_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_event_create_rule._get_unset_required_fields(jsonified_request) + ).delete_event_edit_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -98004,24 +108528,24 @@ def test_delete_event_create_rule_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_event_create_rule(request) + response = client.delete_event_edit_rule(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_event_create_rule_rest_unset_required_fields(): +def test_delete_event_edit_rule_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_event_create_rule._get_unset_required_fields({}) + unset_fields = transport.delete_event_edit_rule._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_event_create_rule_rest_interceptors(null_interceptor): +def test_delete_event_edit_rule_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -98034,11 +108558,11 @@ def test_delete_event_create_rule_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_event_create_rule" + transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_event_edit_rule" ) as pre: pre.assert_not_called() - pb_message = analytics_admin.DeleteEventCreateRuleRequest.pb( - analytics_admin.DeleteEventCreateRuleRequest() + pb_message = analytics_admin.DeleteEventEditRuleRequest.pb( + analytics_admin.DeleteEventEditRuleRequest() ) transcode.return_value = { "method": "post", @@ -98051,14 +108575,14 @@ def test_delete_event_create_rule_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - request = analytics_admin.DeleteEventCreateRuleRequest() + request = analytics_admin.DeleteEventEditRuleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_event_create_rule( + client.delete_event_edit_rule( request, metadata=[ ("key", "val"), @@ -98069,8 +108593,8 @@ def test_delete_event_create_rule_rest_interceptors(null_interceptor): pre.assert_called_once() -def test_delete_event_create_rule_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.DeleteEventCreateRuleRequest +def test_delete_event_edit_rule_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.DeleteEventEditRuleRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -98079,7 +108603,7 @@ def test_delete_event_create_rule_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" } request = request_type(**request_init) @@ -98092,10 +108616,10 @@ def test_delete_event_create_rule_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_event_create_rule(request) + client.delete_event_edit_rule(request) -def test_delete_event_create_rule_rest_flattened(): +def test_delete_event_edit_rule_rest_flattened(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -98108,7 +108632,7 @@ def test_delete_event_create_rule_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "properties/sample1/dataStreams/sample2/eventCreateRules/sample3" + "name": "properties/sample1/dataStreams/sample2/eventEditRules/sample3" } # get truthy value for each flattened field @@ -98124,20 +108648,20 @@ def test_delete_event_create_rule_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_event_create_rule(**mock_args) + client.delete_event_edit_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}" + "%s/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}" % client.transport._host, args[1], ) -def test_delete_event_create_rule_rest_flattened_error(transport: str = "rest"): +def test_delete_event_edit_rule_rest_flattened_error(transport: str = "rest"): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -98146,13 +108670,261 @@ def test_delete_event_create_rule_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_event_create_rule( - analytics_admin.DeleteEventCreateRuleRequest(), + client.delete_event_edit_rule( + analytics_admin.DeleteEventEditRuleRequest(), name="name_value", ) -def test_delete_event_create_rule_rest_error(): +def test_delete_event_edit_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + analytics_admin.ReorderEventEditRulesRequest, + dict, + ], +) +def test_reorder_event_edit_rules_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.reorder_event_edit_rules(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_reorder_event_edit_rules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.reorder_event_edit_rules + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.reorder_event_edit_rules + ] = mock_rpc + + request = {} + client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.reorder_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_reorder_event_edit_rules_rest_required_fields( + request_type=analytics_admin.ReorderEventEditRulesRequest, +): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["event_edit_rules"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reorder_event_edit_rules._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["eventEditRules"] = "event_edit_rules_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reorder_event_edit_rules._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "eventEditRules" in jsonified_request + assert jsonified_request["eventEditRules"] == "event_edit_rules_value" + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.reorder_event_edit_rules(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_reorder_event_edit_rules_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.reorder_event_edit_rules._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "eventEditRules", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reorder_event_edit_rules_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AnalyticsAdminServiceRestInterceptor, "pre_reorder_event_edit_rules" + ) as pre: + pre.assert_not_called() + pb_message = analytics_admin.ReorderEventEditRulesRequest.pb( + analytics_admin.ReorderEventEditRulesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = analytics_admin.ReorderEventEditRulesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.reorder_event_edit_rules( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_reorder_event_edit_rules_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ReorderEventEditRulesRequest +): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "properties/sample1/dataStreams/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.reorder_event_edit_rules(request) + + +def test_reorder_event_edit_rules_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -102428,11 +113200,11 @@ def test_delete_rollup_property_source_link_rest_error(): @pytest.mark.parametrize( "request_type", [ - analytics_admin.CreateSubpropertyRequest, + analytics_admin.ProvisionSubpropertyRequest, dict, ], ) -def test_create_subproperty_rest(request_type): +def test_provision_subproperty_rest(request_type): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -102445,24 +113217,24 @@ def test_create_subproperty_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = analytics_admin.CreateSubpropertyResponse() + return_value = analytics_admin.ProvisionSubpropertyResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.CreateSubpropertyResponse.pb(return_value) + return_value = analytics_admin.ProvisionSubpropertyResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_subproperty(request) + response = client.provision_subproperty(request) # Establish that the response is the type that we expect. - assert isinstance(response, analytics_admin.CreateSubpropertyResponse) + assert isinstance(response, analytics_admin.ProvisionSubpropertyResponse) -def test_create_subproperty_rest_use_cached_wrapped_rpc(): +def test_provision_subproperty_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -102477,7 +113249,8 @@ def test_create_subproperty_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_subproperty in client._transport._wrapped_methods + client._transport.provision_subproperty + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -102486,29 +113259,28 @@ def test_create_subproperty_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_subproperty + client._transport.provision_subproperty ] = mock_rpc request = {} - client.create_subproperty(request) + client.provision_subproperty(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_subproperty(request) + client.provision_subproperty(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_subproperty_rest_required_fields( - request_type=analytics_admin.CreateSubpropertyRequest, +def test_provision_subproperty_rest_required_fields( + request_type=analytics_admin.ProvisionSubpropertyRequest, ): transport_class = transports.AnalyticsAdminServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -102519,21 +113291,17 @@ def test_create_subproperty_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_subproperty._get_unset_required_fields(jsonified_request) + ).provision_subproperty._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_subproperty._get_unset_required_fields(jsonified_request) + ).provision_subproperty._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -102542,7 +113310,7 @@ def test_create_subproperty_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = analytics_admin.CreateSubpropertyResponse() + return_value = analytics_admin.ProvisionSubpropertyResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -102564,38 +113332,30 @@ def test_create_subproperty_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = analytics_admin.CreateSubpropertyResponse.pb(return_value) + return_value = analytics_admin.ProvisionSubpropertyResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_subproperty(request) + response = client.provision_subproperty(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_subproperty_rest_unset_required_fields(): +def test_provision_subproperty_rest_unset_required_fields(): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_subproperty._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "subproperty", - ) - ) - ) + unset_fields = transport.provision_subproperty._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("subproperty",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_subproperty_rest_interceptors(null_interceptor): +def test_provision_subproperty_rest_interceptors(null_interceptor): transport = transports.AnalyticsAdminServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -102608,14 +113368,14 @@ def test_create_subproperty_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "post_create_subproperty" + transports.AnalyticsAdminServiceRestInterceptor, "post_provision_subproperty" ) as post, mock.patch.object( - transports.AnalyticsAdminServiceRestInterceptor, "pre_create_subproperty" + transports.AnalyticsAdminServiceRestInterceptor, "pre_provision_subproperty" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = analytics_admin.CreateSubpropertyRequest.pb( - analytics_admin.CreateSubpropertyRequest() + pb_message = analytics_admin.ProvisionSubpropertyRequest.pb( + analytics_admin.ProvisionSubpropertyRequest() ) transcode.return_value = { "method": "post", @@ -102627,19 +113387,21 @@ def test_create_subproperty_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = analytics_admin.CreateSubpropertyResponse.to_json( - analytics_admin.CreateSubpropertyResponse() + req.return_value._content = ( + analytics_admin.ProvisionSubpropertyResponse.to_json( + analytics_admin.ProvisionSubpropertyResponse() + ) ) - request = analytics_admin.CreateSubpropertyRequest() + request = analytics_admin.ProvisionSubpropertyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = analytics_admin.CreateSubpropertyResponse() + post.return_value = analytics_admin.ProvisionSubpropertyResponse() - client.create_subproperty( + client.provision_subproperty( request, metadata=[ ("key", "val"), @@ -102651,8 +113413,8 @@ def test_create_subproperty_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_subproperty_rest_bad_request( - transport: str = "rest", request_type=analytics_admin.CreateSubpropertyRequest +def test_provision_subproperty_rest_bad_request( + transport: str = "rest", request_type=analytics_admin.ProvisionSubpropertyRequest ): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -102672,10 +113434,10 @@ def test_create_subproperty_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_subproperty(request) + client.provision_subproperty(request) -def test_create_subproperty_rest_error(): +def test_provision_subproperty_rest_error(): client = AnalyticsAdminServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -104740,6 +115502,11 @@ def test_analytics_admin_service_base_transport(): "get_conversion_event", "delete_conversion_event", "list_conversion_events", + "create_key_event", + "update_key_event", + "get_key_event", + "delete_key_event", + "list_key_events", "get_display_video360_advertiser_link", "list_display_video360_advertiser_links", "create_display_video360_advertiser_link", @@ -104802,8 +115569,11 @@ def test_analytics_admin_service_base_transport(): "delete_channel_group", "set_automated_ga4_configuration_opt_out", "fetch_automated_ga4_configuration_opt_out", + "create_big_query_link", "get_big_query_link", "list_big_query_links", + "delete_big_query_link", + "update_big_query_link", "get_enhanced_measurement_settings", "update_enhanced_measurement_settings", "create_connected_site_tag", @@ -104819,6 +115589,12 @@ def test_analytics_admin_service_base_transport(): "create_event_create_rule", "update_event_create_rule", "delete_event_create_rule", + "get_event_edit_rule", + "list_event_edit_rules", + "create_event_edit_rule", + "update_event_edit_rule", + "delete_event_edit_rule", + "reorder_event_edit_rules", "update_data_redaction_settings", "get_data_redaction_settings", "get_calculated_metric", @@ -104831,7 +115607,7 @@ def test_analytics_admin_service_base_transport(): "list_rollup_property_source_links", "create_rollup_property_source_link", "delete_rollup_property_source_link", - "create_subproperty", + "provision_subproperty", "create_subproperty_event_filter", "get_subproperty_event_filter", "list_subproperty_event_filters", @@ -105236,6 +116012,21 @@ def test_analytics_admin_service_client_transport_session_collision(transport_na session1 = client1.transport.list_conversion_events._session session2 = client2.transport.list_conversion_events._session assert session1 != session2 + session1 = client1.transport.create_key_event._session + session2 = client2.transport.create_key_event._session + assert session1 != session2 + session1 = client1.transport.update_key_event._session + session2 = client2.transport.update_key_event._session + assert session1 != session2 + session1 = client1.transport.get_key_event._session + session2 = client2.transport.get_key_event._session + assert session1 != session2 + session1 = client1.transport.delete_key_event._session + session2 = client2.transport.delete_key_event._session + assert session1 != session2 + session1 = client1.transport.list_key_events._session + session2 = client2.transport.list_key_events._session + assert session1 != session2 session1 = client1.transport.get_display_video360_advertiser_link._session session2 = client2.transport.get_display_video360_advertiser_link._session assert session1 != session2 @@ -105442,12 +116233,21 @@ def test_analytics_admin_service_client_transport_session_collision(transport_na session1 = client1.transport.fetch_automated_ga4_configuration_opt_out._session session2 = client2.transport.fetch_automated_ga4_configuration_opt_out._session assert session1 != session2 + session1 = client1.transport.create_big_query_link._session + session2 = client2.transport.create_big_query_link._session + assert session1 != session2 session1 = client1.transport.get_big_query_link._session session2 = client2.transport.get_big_query_link._session assert session1 != session2 session1 = client1.transport.list_big_query_links._session session2 = client2.transport.list_big_query_links._session assert session1 != session2 + session1 = client1.transport.delete_big_query_link._session + session2 = client2.transport.delete_big_query_link._session + assert session1 != session2 + session1 = client1.transport.update_big_query_link._session + session2 = client2.transport.update_big_query_link._session + assert session1 != session2 session1 = client1.transport.get_enhanced_measurement_settings._session session2 = client2.transport.get_enhanced_measurement_settings._session assert session1 != session2 @@ -105493,6 +116293,24 @@ def test_analytics_admin_service_client_transport_session_collision(transport_na session1 = client1.transport.delete_event_create_rule._session session2 = client2.transport.delete_event_create_rule._session assert session1 != session2 + session1 = client1.transport.get_event_edit_rule._session + session2 = client2.transport.get_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.list_event_edit_rules._session + session2 = client2.transport.list_event_edit_rules._session + assert session1 != session2 + session1 = client1.transport.create_event_edit_rule._session + session2 = client2.transport.create_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.update_event_edit_rule._session + session2 = client2.transport.update_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.delete_event_edit_rule._session + session2 = client2.transport.delete_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.reorder_event_edit_rules._session + session2 = client2.transport.reorder_event_edit_rules._session + assert session1 != session2 session1 = client1.transport.update_data_redaction_settings._session session2 = client2.transport.update_data_redaction_settings._session assert session1 != session2 @@ -105529,8 +116347,8 @@ def test_analytics_admin_service_client_transport_session_collision(transport_na session1 = client1.transport.delete_rollup_property_source_link._session session2 = client2.transport.delete_rollup_property_source_link._session assert session1 != session2 - session1 = client1.transport.create_subproperty._session - session2 = client2.transport.create_subproperty._session + session1 = client1.transport.provision_subproperty._session + session2 = client2.transport.provision_subproperty._session assert session1 != session2 session1 = client1.transport.create_subproperty_event_filter._session session2 = client2.transport.create_subproperty_event_filter._session @@ -106147,9 +116965,37 @@ def test_parse_event_create_rule_path(): assert expected == actual -def test_expanded_data_set_path(): +def test_event_edit_rule_path(): property = "squid" - expanded_data_set = "clam" + data_stream = "clam" + event_edit_rule = "whelk" + expected = "properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule}".format( + property=property, + data_stream=data_stream, + event_edit_rule=event_edit_rule, + ) + actual = AnalyticsAdminServiceClient.event_edit_rule_path( + property, data_stream, event_edit_rule + ) + assert expected == actual + + +def test_parse_event_edit_rule_path(): + expected = { + "property": "octopus", + "data_stream": "oyster", + "event_edit_rule": "nudibranch", + } + path = AnalyticsAdminServiceClient.event_edit_rule_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_event_edit_rule_path(path) + assert expected == actual + + +def test_expanded_data_set_path(): + property = "cuttlefish" + expanded_data_set = "mussel" expected = "properties/{property}/expandedDataSets/{expanded_data_set}".format( property=property, expanded_data_set=expanded_data_set, @@ -106162,8 +117008,8 @@ def test_expanded_data_set_path(): def test_parse_expanded_data_set_path(): expected = { - "property": "whelk", - "expanded_data_set": "octopus", + "property": "winkle", + "expanded_data_set": "nautilus", } path = AnalyticsAdminServiceClient.expanded_data_set_path(**expected) @@ -106173,8 +117019,8 @@ def test_parse_expanded_data_set_path(): def test_firebase_link_path(): - property = "oyster" - firebase_link = "nudibranch" + property = "scallop" + firebase_link = "abalone" expected = "properties/{property}/firebaseLinks/{firebase_link}".format( property=property, firebase_link=firebase_link, @@ -106185,8 +117031,8 @@ def test_firebase_link_path(): def test_parse_firebase_link_path(): expected = { - "property": "cuttlefish", - "firebase_link": "mussel", + "property": "squid", + "firebase_link": "clam", } path = AnalyticsAdminServiceClient.firebase_link_path(**expected) @@ -106196,8 +117042,8 @@ def test_parse_firebase_link_path(): def test_global_site_tag_path(): - property = "winkle" - data_stream = "nautilus" + property = "whelk" + data_stream = "octopus" expected = "properties/{property}/dataStreams/{data_stream}/globalSiteTag".format( property=property, data_stream=data_stream, @@ -106208,8 +117054,8 @@ def test_global_site_tag_path(): def test_parse_global_site_tag_path(): expected = { - "property": "scallop", - "data_stream": "abalone", + "property": "oyster", + "data_stream": "nudibranch", } path = AnalyticsAdminServiceClient.global_site_tag_path(**expected) @@ -106219,8 +117065,8 @@ def test_parse_global_site_tag_path(): def test_google_ads_link_path(): - property = "squid" - google_ads_link = "clam" + property = "cuttlefish" + google_ads_link = "mussel" expected = "properties/{property}/googleAdsLinks/{google_ads_link}".format( property=property, google_ads_link=google_ads_link, @@ -106231,8 +117077,8 @@ def test_google_ads_link_path(): def test_parse_google_ads_link_path(): expected = { - "property": "whelk", - "google_ads_link": "octopus", + "property": "winkle", + "google_ads_link": "nautilus", } path = AnalyticsAdminServiceClient.google_ads_link_path(**expected) @@ -106242,7 +117088,7 @@ def test_parse_google_ads_link_path(): def test_google_signals_settings_path(): - property = "oyster" + property = "scallop" expected = "properties/{property}/googleSignalsSettings".format( property=property, ) @@ -106252,7 +117098,7 @@ def test_google_signals_settings_path(): def test_parse_google_signals_settings_path(): expected = { - "property": "nudibranch", + "property": "abalone", } path = AnalyticsAdminServiceClient.google_signals_settings_path(**expected) @@ -106261,10 +117107,33 @@ def test_parse_google_signals_settings_path(): assert expected == actual +def test_key_event_path(): + property = "squid" + key_event = "clam" + expected = "properties/{property}/keyEvents/{key_event}".format( + property=property, + key_event=key_event, + ) + actual = AnalyticsAdminServiceClient.key_event_path(property, key_event) + assert expected == actual + + +def test_parse_key_event_path(): + expected = { + "property": "whelk", + "key_event": "octopus", + } + path = AnalyticsAdminServiceClient.key_event_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_key_event_path(path) + assert expected == actual + + def test_measurement_protocol_secret_path(): - property = "cuttlefish" - data_stream = "mussel" - measurement_protocol_secret = "winkle" + property = "oyster" + data_stream = "nudibranch" + measurement_protocol_secret = "cuttlefish" expected = "properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}".format( property=property, data_stream=data_stream, @@ -106278,9 +117147,9 @@ def test_measurement_protocol_secret_path(): def test_parse_measurement_protocol_secret_path(): expected = { - "property": "nautilus", - "data_stream": "scallop", - "measurement_protocol_secret": "abalone", + "property": "mussel", + "data_stream": "winkle", + "measurement_protocol_secret": "nautilus", } path = AnalyticsAdminServiceClient.measurement_protocol_secret_path(**expected) @@ -106289,6 +117158,26 @@ def test_parse_measurement_protocol_secret_path(): assert expected == actual +def test_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = AnalyticsAdminServiceClient.organization_path(organization) + assert expected == actual + + +def test_parse_organization_path(): + expected = { + "organization": "abalone", + } + path = AnalyticsAdminServiceClient.organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_organization_path(path) + assert expected == actual + + def test_property_path(): property = "squid" expected = "properties/{property}".format( diff --git a/packages/google-analytics-data/google/analytics/data/__init__.py b/packages/google-analytics-data/google/analytics/data/__init__.py index 9dfd7e4d3a94..ef41c399ec91 100644 --- a/packages/google-analytics-data/google/analytics/data/__init__.py +++ b/packages/google-analytics-data/google/analytics/data/__init__.py @@ -56,6 +56,8 @@ CohortReportSettings, CohortSpec, CohortsRange, + Comparison, + ComparisonMetadata, Compatibility, DateRange, Dimension, @@ -120,6 +122,8 @@ "CohortReportSettings", "CohortSpec", "CohortsRange", + "Comparison", + "ComparisonMetadata", "DateRange", "Dimension", "DimensionCompatibility", diff --git a/packages/google-analytics-data/google/analytics/data/gapic_version.py b/packages/google-analytics-data/google/analytics/data/gapic_version.py index d18984dd1f08..558c8aab67c5 100644 --- a/packages/google-analytics-data/google/analytics/data/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.18.10" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py index d18984dd1f08..558c8aab67c5 100644 --- a/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.18.10" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/__init__.py b/packages/google-analytics-data/google/analytics/data_v1beta/__init__.py index 4c5105050e54..d77ca6b13486 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/__init__.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/__init__.py @@ -54,6 +54,8 @@ CohortReportSettings, CohortSpec, CohortsRange, + Comparison, + ComparisonMetadata, Compatibility, DateRange, Dimension, @@ -104,6 +106,8 @@ "CohortReportSettings", "CohortSpec", "CohortsRange", + "Comparison", + "ComparisonMetadata", "Compatibility", "CreateAudienceExportRequest", "DateRange", diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py b/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py index d18984dd1f08..558c8aab67c5 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.18.10" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/types/__init__.py b/packages/google-analytics-data/google/analytics/data_v1beta/types/__init__.py index d3564da440c2..33d6267b83a9 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/types/__init__.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/types/__init__.py @@ -45,6 +45,8 @@ CohortReportSettings, CohortSpec, CohortsRange, + Comparison, + ComparisonMetadata, Compatibility, DateRange, Dimension, @@ -107,6 +109,8 @@ "CohortReportSettings", "CohortSpec", "CohortsRange", + "Comparison", + "ComparisonMetadata", "DateRange", "Dimension", "DimensionCompatibility", diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/types/analytics_data_api.py b/packages/google-analytics-data/google/analytics/data_v1beta/types/analytics_data_api.py index 6676ecceeb45..5374bfdb0fe5 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/types/analytics_data_api.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/types/analytics_data_api.py @@ -157,6 +157,8 @@ class Metadata(proto.Message): The dimension descriptions. metrics (MutableSequence[google.analytics.data_v1beta.types.MetricMetadata]): The metric descriptions. + comparisons (MutableSequence[google.analytics.data_v1beta.types.ComparisonMetadata]): + The comparison descriptions. """ name: str = proto.Field( @@ -173,6 +175,11 @@ class Metadata(proto.Message): number=2, message=data.MetricMetadata, ) + comparisons: MutableSequence[data.ComparisonMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=data.ComparisonMetadata, + ) class RunReportRequest(proto.Message): @@ -269,6 +276,11 @@ class RunReportRequest(proto.Message): Toggles whether to return the current state of this Analytics Property's quota. Quota is returned in `PropertyQuota <#PropertyQuota>`__. + comparisons (MutableSequence[google.analytics.data_v1beta.types.Comparison]): + Optional. The configuration of comparisons + requested and displayed. The request only + requires a comparisons field in order to receive + a comparison column in the response. """ property: str = proto.Field( @@ -335,6 +347,11 @@ class RunReportRequest(proto.Message): proto.BOOL, number=14, ) + comparisons: MutableSequence[data.Comparison] = proto.RepeatedField( + proto.MESSAGE, + number=15, + message=data.Comparison, + ) class RunReportResponse(proto.Message): @@ -504,6 +521,12 @@ class RunPivotReportRequest(proto.Message): Toggles whether to return the current state of this Analytics Property's quota. Quota is returned in `PropertyQuota <#PropertyQuota>`__. + comparisons (MutableSequence[google.analytics.data_v1beta.types.Comparison]): + Optional. The configuration of comparisons + requested and displayed. The request requires + both a comparisons field and a comparisons + dimension to receive a comparison column in the + response. """ property: str = proto.Field( @@ -557,6 +580,11 @@ class RunPivotReportRequest(proto.Message): proto.BOOL, number=11, ) + comparisons: MutableSequence[data.Comparison] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message=data.Comparison, + ) class RunPivotReportResponse(proto.Message): diff --git a/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py b/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py index 822dbacc246d..9cc69fc324a8 100644 --- a/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py +++ b/packages/google-analytics-data/google/analytics/data_v1beta/types/data.py @@ -31,6 +31,7 @@ "Dimension", "DimensionExpression", "Metric", + "Comparison", "FilterExpression", "FilterExpressionList", "Filter", @@ -54,6 +55,7 @@ "QuotaStatus", "DimensionMetadata", "MetricMetadata", + "ComparisonMetadata", "DimensionCompatibility", "MetricCompatibility", }, @@ -471,6 +473,56 @@ class Metric(proto.Message): ) +class Comparison(proto.Message): + r"""Defines an individual comparison. Most requests will include + multiple comparisons so that the report compares between the + comparisons. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Each comparison produces separate rows in the + response. In the response, this comparison is + identified by this name. If name is unspecified, + we will use the saved comparisons display name. + + This field is a member of `oneof`_ ``_name``. + dimension_filter (google.analytics.data_v1beta.types.FilterExpression): + A basic comparison. + + This field is a member of `oneof`_ ``one_comparison``. + comparison (str): + A saved comparison identified by the + comparison's resource name. For example, + 'comparisons/1234'. + + This field is a member of `oneof`_ ``one_comparison``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + dimension_filter: "FilterExpression" = proto.Field( + proto.MESSAGE, + number=2, + oneof="one_comparison", + message="FilterExpression", + ) + comparison: str = proto.Field( + proto.STRING, + number=3, + oneof="one_comparison", + ) + + class FilterExpression(proto.Message): r"""To express dimension or metric filters. The fields in the same FilterExpression need to be either all dimensions or all @@ -1751,8 +1803,14 @@ class DimensionMetadata(proto.Message): the deprecation period, the dimension will be available only by ``apiName``. custom_definition (bool): - True if the dimension is a custom dimension - for this property. + True if the dimension is custom to this + property. This includes user, event, & item + scoped custom dimensions; to learn more about + custom dimensions, see + https://support.google.com/analytics/answer/14240153. + This also include custom channel groups; to + learn more about custom channel groups, see + https://support.google.com/analytics/answer/13051316. category (str): The display name of the category that this dimension belongs to. Similar dimensions and @@ -1889,6 +1947,35 @@ class BlockedReason(proto.Enum): ) +class ComparisonMetadata(proto.Message): + r"""The metadata for a single comparison. + + Attributes: + api_name (str): + This comparison's resource name. Useable in + `Comparison <#Comparison>`__'s ``comparison`` field. For + example, 'comparisons/1234'. + ui_name (str): + This comparison's name within the Google + Analytics user interface. + description (str): + This comparison's description. + """ + + api_name: str = proto.Field( + proto.STRING, + number=1, + ) + ui_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + + class DimensionCompatibility(proto.Message): r"""The compatibility for a single dimension. diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json index d710f6b29e8a..619e88f4243b 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-data", - "version": "0.18.10" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json index 6e9433c51432..29e86a085403 100644 --- a/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json +++ b/packages/google-analytics-data/samples/generated_samples/snippet_metadata_google.analytics.data.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-analytics-data", - "version": "0.18.10" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-analytics-data/scripts/fixup_data_v1beta_keywords.py b/packages/google-analytics-data/scripts/fixup_data_v1beta_keywords.py index 3a98463f2491..7363c0b9a5be 100644 --- a/packages/google-analytics-data/scripts/fixup_data_v1beta_keywords.py +++ b/packages/google-analytics-data/scripts/fixup_data_v1beta_keywords.py @@ -47,9 +47,9 @@ class dataCallTransformer(cst.CSTTransformer): 'get_metadata': ('name', ), 'list_audience_exports': ('parent', 'page_size', 'page_token', ), 'query_audience_export': ('name', 'offset', 'limit', ), - 'run_pivot_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'pivots', 'dimension_filter', 'metric_filter', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', ), + 'run_pivot_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'pivots', 'dimension_filter', 'metric_filter', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', 'comparisons', ), 'run_realtime_report': ('property', 'dimensions', 'metrics', 'dimension_filter', 'metric_filter', 'limit', 'metric_aggregations', 'order_bys', 'return_property_quota', 'minute_ranges', ), - 'run_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'metric_aggregations', 'order_bys', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', ), + 'run_report': ('property', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'metric_aggregations', 'order_bys', 'currency_code', 'cohort_spec', 'keep_empty_rows', 'return_property_quota', 'comparisons', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py index 795c02b02eaa..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.12.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py index 795c02b02eaa..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.12.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py index 4cc17d87193a..1c4059675d8a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py @@ -103,7 +103,7 @@ SolutionType, UserInfo, ) -from .types.completion import SuggestionDenyListEntry +from .types.completion import CompletionSuggestion, SuggestionDenyListEntry from .types.completion_service import CompleteQueryRequest, CompleteQueryResponse from .types.control import Condition, Control from .types.control_service import ( @@ -141,7 +141,7 @@ UpdateSessionRequest, ) from .types.custom_tuning_model import CustomTuningModel -from .types.data_store import DataStore +from .types.data_store import DataStore, LanguageInfo from .types.data_store_service import ( CreateDataStoreMetadata, CreateDataStoreRequest, @@ -203,6 +203,7 @@ ) from .types.grounding import FactChunk, GroundingFact from .types.import_config import ( + AlloyDbSource, BigQuerySource, BigtableOptions, BigtableSource, @@ -210,6 +211,9 @@ FhirStoreSource, FirestoreSource, GcsSource, + ImportCompletionSuggestionsMetadata, + ImportCompletionSuggestionsRequest, + ImportCompletionSuggestionsResponse, ImportDocumentsMetadata, ImportDocumentsRequest, ImportDocumentsResponse, @@ -233,6 +237,9 @@ ReportConsentChangeRequest, ) from .types.purge_config import ( + PurgeCompletionSuggestionsMetadata, + PurgeCompletionSuggestionsRequest, + PurgeCompletionSuggestionsResponse, PurgeDocumentsMetadata, PurgeDocumentsRequest, PurgeDocumentsResponse, @@ -314,11 +321,16 @@ FetchDomainVerificationStatusResponse, GetSiteSearchEngineRequest, GetTargetSiteRequest, + GetUriPatternDocumentDataRequest, + GetUriPatternDocumentDataResponse, ListTargetSitesRequest, ListTargetSitesResponse, RecrawlUrisMetadata, RecrawlUrisRequest, RecrawlUrisResponse, + SetUriPatternDocumentDataMetadata, + SetUriPatternDocumentDataRequest, + SetUriPatternDocumentDataResponse, UpdateTargetSiteMetadata, UpdateTargetSiteRequest, ) @@ -359,6 +371,7 @@ "UserEventServiceAsyncClient", "AclConfig", "AclConfigServiceClient", + "AlloyDbSource", "Answer", "AnswerQueryRequest", "AnswerQueryResponse", @@ -382,6 +395,7 @@ "CompleteQueryResponse", "CompletionInfo", "CompletionServiceClient", + "CompletionSuggestion", "Condition", "Control", "ControlServiceClient", @@ -472,10 +486,15 @@ "GetSessionRequest", "GetSiteSearchEngineRequest", "GetTargetSiteRequest", + "GetUriPatternDocumentDataRequest", + "GetUriPatternDocumentDataResponse", "GroundedGenerationServiceClient", "GroundingFact", "GuidedSearchSpec", "IdpConfig", + "ImportCompletionSuggestionsMetadata", + "ImportCompletionSuggestionsRequest", + "ImportCompletionSuggestionsResponse", "ImportDocumentsMetadata", "ImportDocumentsRequest", "ImportDocumentsResponse", @@ -491,6 +510,7 @@ "ImportUserEventsResponse", "IndustryVertical", "Interval", + "LanguageInfo", "ListChunksRequest", "ListChunksResponse", "ListControlsRequest", @@ -531,6 +551,9 @@ "ProjectServiceClient", "ProvisionProjectMetadata", "ProvisionProjectRequest", + "PurgeCompletionSuggestionsMetadata", + "PurgeCompletionSuggestionsRequest", + "PurgeCompletionSuggestionsResponse", "PurgeDocumentsMetadata", "PurgeDocumentsRequest", "PurgeDocumentsResponse", @@ -573,6 +596,9 @@ "ServingConfig", "ServingConfigServiceClient", "Session", + "SetUriPatternDocumentDataMetadata", + "SetUriPatternDocumentDataRequest", + "SetUriPatternDocumentDataResponse", "SiteSearchEngine", "SiteSearchEngineServiceClient", "SiteVerificationInfo", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json index fd770a37dd08..d1a982467642 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json @@ -113,11 +113,21 @@ "complete_query" ] }, + "ImportCompletionSuggestions": { + "methods": [ + "import_completion_suggestions" + ] + }, "ImportSuggestionDenyListEntries": { "methods": [ "import_suggestion_deny_list_entries" ] }, + "PurgeCompletionSuggestions": { + "methods": [ + "purge_completion_suggestions" + ] + }, "PurgeSuggestionDenyListEntries": { "methods": [ "purge_suggestion_deny_list_entries" @@ -133,11 +143,21 @@ "complete_query" ] }, + "ImportCompletionSuggestions": { + "methods": [ + "import_completion_suggestions" + ] + }, "ImportSuggestionDenyListEntries": { "methods": [ "import_suggestion_deny_list_entries" ] }, + "PurgeCompletionSuggestions": { + "methods": [ + "purge_completion_suggestions" + ] + }, "PurgeSuggestionDenyListEntries": { "methods": [ "purge_suggestion_deny_list_entries" @@ -153,11 +173,21 @@ "complete_query" ] }, + "ImportCompletionSuggestions": { + "methods": [ + "import_completion_suggestions" + ] + }, "ImportSuggestionDenyListEntries": { "methods": [ "import_suggestion_deny_list_entries" ] }, + "PurgeCompletionSuggestions": { + "methods": [ + "purge_completion_suggestions" + ] + }, "PurgeSuggestionDenyListEntries": { "methods": [ "purge_suggestion_deny_list_entries" @@ -1650,6 +1680,11 @@ "get_target_site" ] }, + "GetUriPatternDocumentData": { + "methods": [ + "get_uri_pattern_document_data" + ] + }, "ListTargetSites": { "methods": [ "list_target_sites" @@ -1660,6 +1695,11 @@ "recrawl_uris" ] }, + "SetUriPatternDocumentData": { + "methods": [ + "set_uri_pattern_document_data" + ] + }, "UpdateTargetSite": { "methods": [ "update_target_site" @@ -1715,6 +1755,11 @@ "get_target_site" ] }, + "GetUriPatternDocumentData": { + "methods": [ + "get_uri_pattern_document_data" + ] + }, "ListTargetSites": { "methods": [ "list_target_sites" @@ -1725,6 +1770,11 @@ "recrawl_uris" ] }, + "SetUriPatternDocumentData": { + "methods": [ + "set_uri_pattern_document_data" + ] + }, "UpdateTargetSite": { "methods": [ "update_target_site" @@ -1780,6 +1830,11 @@ "get_target_site" ] }, + "GetUriPatternDocumentData": { + "methods": [ + "get_uri_pattern_document_data" + ] + }, "ListTargetSites": { "methods": [ "list_target_sites" @@ -1790,6 +1845,11 @@ "recrawl_uris" ] }, + "SetUriPatternDocumentData": { + "methods": [ + "set_uri_pattern_document_data" + ] + }, "UpdateTargetSite": { "methods": [ "update_target_site" diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py index 795c02b02eaa..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.12.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py index ef39ffbb3978..707fe9bd7382 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/acl_config_service/transports/rest.py @@ -646,6 +646,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -768,6 +772,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py index ce59a92031e1..db5fc94e2798 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/chunk_service/transports/rest.py @@ -651,6 +651,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -773,6 +777,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py index abbeae545fa3..9587344070c3 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py @@ -574,6 +574,222 @@ async def sample_purge_suggestion_deny_list_entries(): # Done; return the response. return response + async def import_completion_suggestions( + self, + request: Optional[ + Union[import_config.ImportCompletionSuggestionsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_import_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.suggestions.global_score = 0.126 + inline_source.suggestions.suggestion = "suggestion_value" + + request = discoveryengine_v1alpha.ImportCompletionSuggestionsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsRequest, dict]]): + The request object. Request message for + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsResponse` Response of the + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. If the long running operation is done, this + message is returned by the + google.longrunning.Operations.response field if the + operation is successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportCompletionSuggestionsRequest): + request = import_config.ImportCompletionSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_completion_suggestions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportCompletionSuggestionsResponse, + metadata_type=import_config.ImportCompletionSuggestionsMetadata, + ) + + # Done; return the response. + return response + + async def purge_completion_suggestions( + self, + request: Optional[ + Union[purge_config.PurgeCompletionSuggestionsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_purge_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeCompletionSuggestionsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.purge_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.PurgeCompletionSuggestionsRequest, dict]]): + The request object. Request message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeCompletionSuggestionsResponse` Response message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, purge_config.PurgeCompletionSuggestionsRequest): + request = purge_config.PurgeCompletionSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.purge_completion_suggestions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeCompletionSuggestionsResponse, + metadata_type=purge_config.PurgeCompletionSuggestionsMetadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py index 46183f69fc17..3c919b767b53 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py @@ -993,6 +993,222 @@ def sample_purge_suggestion_deny_list_entries(): # Done; return the response. return response + def import_completion_suggestions( + self, + request: Optional[ + Union[import_config.ImportCompletionSuggestionsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_import_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.suggestions.global_score = 0.126 + inline_source.suggestions.suggestion = "suggestion_value" + + request = discoveryengine_v1alpha.ImportCompletionSuggestionsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsRequest, dict]): + The request object. Request message for + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsResponse` Response of the + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. If the long running operation is done, this + message is returned by the + google.longrunning.Operations.response field if the + operation is successful. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, import_config.ImportCompletionSuggestionsRequest): + request = import_config.ImportCompletionSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.import_completion_suggestions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportCompletionSuggestionsResponse, + metadata_type=import_config.ImportCompletionSuggestionsMetadata, + ) + + # Done; return the response. + return response + + def purge_completion_suggestions( + self, + request: Optional[ + Union[purge_config.PurgeCompletionSuggestionsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_purge_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeCompletionSuggestionsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.purge_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.PurgeCompletionSuggestionsRequest, dict]): + The request object. Request message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeCompletionSuggestionsResponse` Response message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, purge_config.PurgeCompletionSuggestionsRequest): + request = purge_config.PurgeCompletionSuggestionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.purge_completion_suggestions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeCompletionSuggestionsResponse, + metadata_type=purge_config.PurgeCompletionSuggestionsMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "CompletionServiceClient": return self diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py index 3f086bcc5ab3..d7d1d39861c8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py @@ -149,6 +149,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.import_completion_suggestions: gapic_v1.method.wrap_method( + self.import_completion_suggestions, + default_timeout=None, + client_info=client_info, + ), + self.purge_completion_suggestions: gapic_v1.method.wrap_method( + self.purge_completion_suggestions, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -195,6 +205,24 @@ def purge_suggestion_deny_list_entries( ]: raise NotImplementedError() + @property + def import_completion_suggestions( + self, + ) -> Callable[ + [import_config.ImportCompletionSuggestionsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def purge_completion_suggestions( + self, + ) -> Callable[ + [purge_config.PurgeCompletionSuggestionsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py index 263d542984e2..d388c96f899b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py @@ -351,6 +351,68 @@ def purge_suggestion_deny_list_entries( ) return self._stubs["purge_suggestion_deny_list_entries"] + @property + def import_completion_suggestions( + self, + ) -> Callable[ + [import_config.ImportCompletionSuggestionsRequest], operations_pb2.Operation + ]: + r"""Return a callable for the import completion suggestions method over gRPC. + + Imports + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + Returns: + Callable[[~.ImportCompletionSuggestionsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_completion_suggestions" not in self._stubs: + self._stubs[ + "import_completion_suggestions" + ] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.CompletionService/ImportCompletionSuggestions", + request_serializer=import_config.ImportCompletionSuggestionsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_completion_suggestions"] + + @property + def purge_completion_suggestions( + self, + ) -> Callable[ + [purge_config.PurgeCompletionSuggestionsRequest], operations_pb2.Operation + ]: + r"""Return a callable for the purge completion suggestions method over gRPC. + + Permanently deletes all + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + Returns: + Callable[[~.PurgeCompletionSuggestionsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_completion_suggestions" not in self._stubs: + self._stubs["purge_completion_suggestions"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.CompletionService/PurgeCompletionSuggestions", + request_serializer=purge_config.PurgeCompletionSuggestionsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["purge_completion_suggestions"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py index b9cf83782eca..b69a7960fd1b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py @@ -359,6 +359,70 @@ def purge_suggestion_deny_list_entries( ) return self._stubs["purge_suggestion_deny_list_entries"] + @property + def import_completion_suggestions( + self, + ) -> Callable[ + [import_config.ImportCompletionSuggestionsRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the import completion suggestions method over gRPC. + + Imports + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + Returns: + Callable[[~.ImportCompletionSuggestionsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_completion_suggestions" not in self._stubs: + self._stubs[ + "import_completion_suggestions" + ] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.CompletionService/ImportCompletionSuggestions", + request_serializer=import_config.ImportCompletionSuggestionsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_completion_suggestions"] + + @property + def purge_completion_suggestions( + self, + ) -> Callable[ + [purge_config.PurgeCompletionSuggestionsRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the purge completion suggestions method over gRPC. + + Permanently deletes all + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + for a DataStore. + + Returns: + Callable[[~.PurgeCompletionSuggestionsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_completion_suggestions" not in self._stubs: + self._stubs["purge_completion_suggestions"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.CompletionService/PurgeCompletionSuggestions", + request_serializer=purge_config.PurgeCompletionSuggestionsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["purge_completion_suggestions"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -377,6 +441,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.import_completion_suggestions: gapic_v1.method_async.wrap_method( + self.import_completion_suggestions, + default_timeout=None, + client_info=client_info, + ), + self.purge_completion_suggestions: gapic_v1.method_async.wrap_method( + self.purge_completion_suggestions, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py index 925ce48599b5..63275807365a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py @@ -84,6 +84,14 @@ def post_complete_query(self, response): logging.log(f"Received response: {response}") return response + def pre_import_completion_suggestions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_completion_suggestions(self, response): + logging.log(f"Received response: {response}") + return response + def pre_import_suggestion_deny_list_entries(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -92,6 +100,14 @@ def post_import_suggestion_deny_list_entries(self, response): logging.log(f"Received response: {response}") return response + def pre_purge_completion_suggestions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_completion_suggestions(self, response): + logging.log(f"Received response: {response}") + return response + def pre_purge_suggestion_deny_list_entries(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -129,6 +145,31 @@ def post_complete_query( """ return response + def pre_import_completion_suggestions( + self, + request: import_config.ImportCompletionSuggestionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + import_config.ImportCompletionSuggestionsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for import_completion_suggestions + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService server. + """ + return request, metadata + + def post_import_completion_suggestions( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_completion_suggestions + + Override in a subclass to manipulate the response + after it is returned by the CompletionService server but before + it is returned to user code. + """ + return response + def pre_import_suggestion_deny_list_entries( self, request: import_config.ImportSuggestionDenyListEntriesRequest, @@ -154,6 +195,31 @@ def post_import_suggestion_deny_list_entries( """ return response + def pre_purge_completion_suggestions( + self, + request: purge_config.PurgeCompletionSuggestionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + purge_config.PurgeCompletionSuggestionsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for purge_completion_suggestions + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService server. + """ + return request, metadata + + def post_purge_completion_suggestions( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_completion_suggestions + + Override in a subclass to manipulate the response + after it is returned by the CompletionService server but before + it is returned to user code. + """ + return response + def pre_purge_suggestion_deny_list_entries( self, request: purge_config.PurgeSuggestionDenyListEntriesRequest, @@ -419,6 +485,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -481,6 +551,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -604,6 +678,109 @@ def __call__( resp = self._interceptor.post_complete_query(resp) return resp + class _ImportCompletionSuggestions(CompletionServiceRestStub): + def __hash__(self): + return hash("ImportCompletionSuggestions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: import_config.ImportCompletionSuggestionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the import completion + suggestions method over HTTP. + + Args: + request (~.import_config.ImportCompletionSuggestionsRequest): + The request object. Request message for + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/completionSuggestions:import", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/dataStores/*}/completionSuggestions:import", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_import_completion_suggestions( + request, metadata + ) + pb_request = import_config.ImportCompletionSuggestionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_completion_suggestions(resp) + return resp + class _ImportSuggestionDenyListEntries(CompletionServiceRestStub): def __hash__(self): return hash("ImportSuggestionDenyListEntries") @@ -712,6 +889,109 @@ def __call__( resp = self._interceptor.post_import_suggestion_deny_list_entries(resp) return resp + class _PurgeCompletionSuggestions(CompletionServiceRestStub): + def __hash__(self): + return hash("PurgeCompletionSuggestions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: purge_config.PurgeCompletionSuggestionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the purge completion + suggestions method over HTTP. + + Args: + request (~.purge_config.PurgeCompletionSuggestionsRequest): + The request object. Request message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/completionSuggestions:purge", + "body": "*", + }, + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/dataStores/*}/completionSuggestions:purge", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_purge_completion_suggestions( + request, metadata + ) + pb_request = purge_config.PurgeCompletionSuggestionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_purge_completion_suggestions(resp) + return resp + class _PurgeSuggestionDenyListEntries(CompletionServiceRestStub): def __hash__(self): return hash("PurgeSuggestionDenyListEntries") @@ -829,6 +1109,16 @@ def complete_query( # In C++ this would require a dynamic_cast return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore + @property + def import_completion_suggestions( + self, + ) -> Callable[ + [import_config.ImportCompletionSuggestionsRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportCompletionSuggestions(self._session, self._host, self._interceptor) # type: ignore + @property def import_suggestion_deny_list_entries( self, @@ -839,6 +1129,16 @@ def import_suggestion_deny_list_entries( # In C++ this would require a dynamic_cast return self._ImportSuggestionDenyListEntries(self._session, self._host, self._interceptor) # type: ignore + @property + def purge_completion_suggestions( + self, + ) -> Callable[ + [purge_config.PurgeCompletionSuggestionsRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PurgeCompletionSuggestions(self._session, self._host, self._interceptor) # type: ignore + @property def purge_suggestion_deny_list_entries( self, @@ -1000,6 +1300,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1122,6 +1426,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py index af39e8465b32..d0e22d880b62 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/control_service/transports/rest.py @@ -1057,6 +1057,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1179,6 +1183,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py index 81aed288849c..400e9510c30f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py @@ -2208,6 +2208,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -2330,6 +2334,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py index 20ed8c8e2c19..0e4e88f79606 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py @@ -548,6 +548,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -610,6 +614,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1565,6 +1573,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1687,6 +1699,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py index c6f0962ef19a..e3eca6321b0d 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py @@ -558,6 +558,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -620,6 +624,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1637,6 +1645,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1759,6 +1771,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py index b5f01b4df43f..154f133546a1 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py @@ -561,6 +561,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -623,6 +627,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1615,6 +1623,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1737,6 +1749,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py index c43f3f022640..70370a89bc7e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/estimate_billing_service/transports/rest.py @@ -351,6 +351,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -413,6 +417,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -698,6 +706,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -820,6 +832,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py index fa6bfcc7099a..d8ec9fc9fdad 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/async_client.py @@ -94,6 +94,8 @@ class EvaluationServiceAsyncClient: parse_serving_config_path = staticmethod( EvaluationServiceClient.parse_serving_config_path ) + session_path = staticmethod(EvaluationServiceClient.session_path) + parse_session_path = staticmethod(EvaluationServiceClient.parse_session_path) common_billing_account_path = staticmethod( EvaluationServiceClient.common_billing_account_path ) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py index 8b3d84243281..f5afb85dddbe 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/client.py @@ -351,6 +351,30 @@ def parse_serving_config_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def session_path( + project: str, + location: str, + data_store: str, + session: str, + ) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format( + project=project, + location=location, + data_store=data_store, + session=session, + ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str, str]: + """Parses a session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/sessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py index 753bfe047b59..82ea82ae397d 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/evaluation_service/transports/rest.py @@ -445,6 +445,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -507,6 +511,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1097,6 +1105,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1219,6 +1231,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py index 83c023a25579..f2682dcbbf69 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/grounded_generation_service/transports/rest.py @@ -528,6 +528,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -650,6 +654,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py index b415132045b4..218599a9fed7 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/project_service/transports/rest.py @@ -412,6 +412,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -474,6 +478,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -959,6 +967,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1081,6 +1093,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py index 254839651c73..1e47b1e1b48b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/rank_service/transports/rest.py @@ -519,6 +519,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -641,6 +645,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py index 15b829f895f4..624921f67721 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py @@ -533,6 +533,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -655,6 +659,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py index 783cc3209c18..f72b37c13b79 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_service/transports/rest.py @@ -502,6 +502,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -564,6 +568,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1354,6 +1362,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1476,6 +1488,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py index a8e81cc246bf..699df466ff57 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/sample_query_set_service/transports/rest.py @@ -1067,6 +1067,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1189,6 +1193,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py index 7cb12e185fbb..c13a59038be6 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py @@ -472,6 +472,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -534,6 +538,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1233,6 +1241,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1355,6 +1367,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py index 38f0381c3dac..df7822be74f9 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py @@ -78,6 +78,8 @@ class SearchServiceAsyncClient: parse_serving_config_path = staticmethod( SearchServiceClient.parse_serving_config_path ) + session_path = staticmethod(SearchServiceClient.session_path) + parse_session_path = staticmethod(SearchServiceClient.parse_session_path) common_billing_account_path = staticmethod( SearchServiceClient.common_billing_account_path ) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/client.py index 8f9a5264a18b..7e589620b6a8 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/client.py @@ -308,6 +308,30 @@ def parse_serving_config_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def session_path( + project: str, + location: str, + data_store: str, + session: str, + ) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format( + project=project, + location=location, + data_store=data_store, + session=session, + ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str, str]: + """Parses a session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/sessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py index 1826592e4eba..43ed23bb3529 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py @@ -531,6 +531,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -653,6 +657,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py index 49ede827a7b3..cae34a20c85e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/search_tuning_service/transports/rest.py @@ -384,6 +384,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -446,6 +450,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -834,6 +842,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -956,6 +968,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py index 32dabfc1c1e1..b6a7c8d4f13e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/serving_config_service/transports/rest.py @@ -833,6 +833,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -955,6 +959,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py index 145d97a99cea..9e9a6a534e7f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py @@ -1735,6 +1735,210 @@ async def sample_fetch_domain_verification_status(): # Done; return the response. return response + async def set_uri_pattern_document_data( + self, + request: Optional[ + Union[site_search_engine_service.SetUriPatternDocumentDataRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Sets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_set_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.set_uri_pattern_document_data(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.SetUriPatternDocumentDataRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.SetUriPatternDocumentDataResponse` Response message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.SetUriPatternDocumentDataRequest + ): + request = site_search_engine_service.SetUriPatternDocumentDataRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.set_uri_pattern_document_data + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + site_search_engine_service.SetUriPatternDocumentDataResponse, + metadata_type=site_search_engine_service.SetUriPatternDocumentDataMetadata, + ) + + # Done; return the response. + return response + + async def get_uri_pattern_document_data( + self, + request: Optional[ + Union[site_search_engine_service.GetUriPatternDocumentDataRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> site_search_engine_service.GetUriPatternDocumentDataResponse: + r"""Gets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_get_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + response = await client.get_uri_pattern_document_data(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataResponse: + Response message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.GetUriPatternDocumentDataRequest + ): + request = site_search_engine_service.GetUriPatternDocumentDataRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_uri_pattern_document_data + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py index f3d9e66d311f..8afe9a3720bf 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py @@ -2149,6 +2149,210 @@ def sample_fetch_domain_verification_status(): # Done; return the response. return response + def set_uri_pattern_document_data( + self, + request: Optional[ + Union[site_search_engine_service.SetUriPatternDocumentDataRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Sets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_set_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.set_uri_pattern_document_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.SetUriPatternDocumentDataRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.SetUriPatternDocumentDataResponse` Response message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.SetUriPatternDocumentDataRequest + ): + request = site_search_engine_service.SetUriPatternDocumentDataRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.set_uri_pattern_document_data + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + site_search_engine_service.SetUriPatternDocumentDataResponse, + metadata_type=site_search_engine_service.SetUriPatternDocumentDataMetadata, + ) + + # Done; return the response. + return response + + def get_uri_pattern_document_data( + self, + request: Optional[ + Union[site_search_engine_service.GetUriPatternDocumentDataRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> site_search_engine_service.GetUriPatternDocumentDataResponse: + r"""Gets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_get_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + response = client.get_uri_pattern_document_data(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataResponse: + Response message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, site_search_engine_service.GetUriPatternDocumentDataRequest + ): + request = site_search_engine_service.GetUriPatternDocumentDataRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_uri_pattern_document_data + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("site_search_engine", request.site_search_engine),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "SiteSearchEngineServiceClient": return self diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py index 251d0e2a1e52..c3a5fb6debcb 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py @@ -193,6 +193,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_uri_pattern_document_data: gapic_v1.method.wrap_method( + self.set_uri_pattern_document_data, + default_timeout=None, + client_info=client_info, + ), + self.get_uri_pattern_document_data: gapic_v1.method.wrap_method( + self.get_uri_pattern_document_data, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -326,6 +336,27 @@ def fetch_domain_verification_status( ]: raise NotImplementedError() + @property + def set_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.SetUriPatternDocumentDataRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.GetUriPatternDocumentDataRequest], + Union[ + site_search_engine_service.GetUriPatternDocumentDataResponse, + Awaitable[site_search_engine_service.GetUriPatternDocumentDataResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py index 28d1cda2a65c..2ab9ee6e85a7 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py @@ -614,6 +614,70 @@ def fetch_domain_verification_status( ) return self._stubs["fetch_domain_verification_status"] + @property + def set_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.SetUriPatternDocumentDataRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the set uri pattern document data method over gRPC. + + Sets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + Returns: + Callable[[~.SetUriPatternDocumentDataRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_uri_pattern_document_data" not in self._stubs: + self._stubs[ + "set_uri_pattern_document_data" + ] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/SetUriPatternDocumentData", + request_serializer=site_search_engine_service.SetUriPatternDocumentDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["set_uri_pattern_document_data"] + + @property + def get_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.GetUriPatternDocumentDataRequest], + site_search_engine_service.GetUriPatternDocumentDataResponse, + ]: + r"""Return a callable for the get uri pattern document data method over gRPC. + + Gets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + Returns: + Callable[[~.GetUriPatternDocumentDataRequest], + ~.GetUriPatternDocumentDataResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_uri_pattern_document_data" not in self._stubs: + self._stubs[ + "get_uri_pattern_document_data" + ] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/GetUriPatternDocumentData", + request_serializer=site_search_engine_service.GetUriPatternDocumentDataRequest.serialize, + response_deserializer=site_search_engine_service.GetUriPatternDocumentDataResponse.deserialize, + ) + return self._stubs["get_uri_pattern_document_data"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py index 028619248567..de6718679d52 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py @@ -625,6 +625,70 @@ def fetch_domain_verification_status( ) return self._stubs["fetch_domain_verification_status"] + @property + def set_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.SetUriPatternDocumentDataRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the set uri pattern document data method over gRPC. + + Sets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + Returns: + Callable[[~.SetUriPatternDocumentDataRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_uri_pattern_document_data" not in self._stubs: + self._stubs[ + "set_uri_pattern_document_data" + ] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/SetUriPatternDocumentData", + request_serializer=site_search_engine_service.SetUriPatternDocumentDataRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["set_uri_pattern_document_data"] + + @property + def get_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.GetUriPatternDocumentDataRequest], + Awaitable[site_search_engine_service.GetUriPatternDocumentDataResponse], + ]: + r"""Return a callable for the get uri pattern document data method over gRPC. + + Gets the URI Pattern to Document data mapping for an + Advanced Site Search DataStore. + + Returns: + Callable[[~.GetUriPatternDocumentDataRequest], + Awaitable[~.GetUriPatternDocumentDataResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_uri_pattern_document_data" not in self._stubs: + self._stubs[ + "get_uri_pattern_document_data" + ] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/GetUriPatternDocumentData", + request_serializer=site_search_engine_service.GetUriPatternDocumentDataRequest.serialize, + response_deserializer=site_search_engine_service.GetUriPatternDocumentDataResponse.deserialize, + ) + return self._stubs["get_uri_pattern_document_data"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -688,6 +752,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.set_uri_pattern_document_data: gapic_v1.method_async.wrap_method( + self.set_uri_pattern_document_data, + default_timeout=None, + client_info=client_info, + ), + self.get_uri_pattern_document_data: gapic_v1.method_async.wrap_method( + self.get_uri_pattern_document_data, + default_timeout=None, + client_info=client_info, + ), } def close(self): diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py index 1b1de82c41ee..f9c4f86cd60f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py @@ -147,6 +147,14 @@ def post_get_target_site(self, response): logging.log(f"Received response: {response}") return response + def pre_get_uri_pattern_document_data(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_uri_pattern_document_data(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_target_sites(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -163,6 +171,14 @@ def post_recrawl_uris(self, response): logging.log(f"Received response: {response}") return response + def pre_set_uri_pattern_document_data(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_uri_pattern_document_data(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_target_site(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -407,6 +423,32 @@ def post_get_target_site( """ return response + def pre_get_uri_pattern_document_data( + self, + request: site_search_engine_service.GetUriPatternDocumentDataRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + site_search_engine_service.GetUriPatternDocumentDataRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for get_uri_pattern_document_data + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_get_uri_pattern_document_data( + self, response: site_search_engine_service.GetUriPatternDocumentDataResponse + ) -> site_search_engine_service.GetUriPatternDocumentDataResponse: + """Post-rpc interceptor for get_uri_pattern_document_data + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + def pre_list_target_sites( self, request: site_search_engine_service.ListTargetSitesRequest, @@ -457,6 +499,32 @@ def post_recrawl_uris( """ return response + def pre_set_uri_pattern_document_data( + self, + request: site_search_engine_service.SetUriPatternDocumentDataRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + site_search_engine_service.SetUriPatternDocumentDataRequest, + Sequence[Tuple[str, str]], + ]: + """Pre-rpc interceptor for set_uri_pattern_document_data + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_set_uri_pattern_document_data( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for set_uri_pattern_document_data + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + def pre_update_target_site( self, request: site_search_engine_service.UpdateTargetSiteRequest, @@ -722,6 +790,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -784,6 +856,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -1713,6 +1789,103 @@ def __call__( resp = self._interceptor.post_get_target_site(resp) return resp + class _GetUriPatternDocumentData(SiteSearchEngineServiceRestStub): + def __hash__(self): + return hash("GetUriPatternDocumentData") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: site_search_engine_service.GetUriPatternDocumentDataRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> site_search_engine_service.GetUriPatternDocumentDataResponse: + r"""Call the get uri pattern document + data method over HTTP. + + Args: + request (~.site_search_engine_service.GetUriPatternDocumentDataRequest): + The request object. Request message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.site_search_engine_service.GetUriPatternDocumentDataResponse: + Response message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:getUriPatternDocumentData", + }, + ] + request, metadata = self._interceptor.pre_get_uri_pattern_document_data( + request, metadata + ) + pb_request = site_search_engine_service.GetUriPatternDocumentDataRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = site_search_engine_service.GetUriPatternDocumentDataResponse() + pb_resp = site_search_engine_service.GetUriPatternDocumentDataResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_uri_pattern_document_data(resp) + return resp + class _ListTargetSites(SiteSearchEngineServiceRestStub): def __hash__(self): return hash("ListTargetSites") @@ -1909,6 +2082,106 @@ def __call__( resp = self._interceptor.post_recrawl_uris(resp) return resp + class _SetUriPatternDocumentData(SiteSearchEngineServiceRestStub): + def __hash__(self): + return hash("SetUriPatternDocumentData") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: site_search_engine_service.SetUriPatternDocumentDataRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the set uri pattern document + data method over HTTP. + + Args: + request (~.site_search_engine_service.SetUriPatternDocumentDataRequest): + The request object. Request message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:setUriPatternDocumentData", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_uri_pattern_document_data( + request, metadata + ) + pb_request = site_search_engine_service.SetUriPatternDocumentDataRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_uri_pattern_document_data(resp) + return resp + class _UpdateTargetSite(SiteSearchEngineServiceRestStub): def __hash__(self): return hash("UpdateTargetSite") @@ -2107,6 +2380,17 @@ def get_target_site( # In C++ this would require a dynamic_cast return self._GetTargetSite(self._session, self._host, self._interceptor) # type: ignore + @property + def get_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.GetUriPatternDocumentDataRequest], + site_search_engine_service.GetUriPatternDocumentDataResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetUriPatternDocumentData(self._session, self._host, self._interceptor) # type: ignore + @property def list_target_sites( self, @@ -2128,6 +2412,17 @@ def recrawl_uris( # In C++ this would require a dynamic_cast return self._RecrawlUris(self._session, self._host, self._interceptor) # type: ignore + @property + def set_uri_pattern_document_data( + self, + ) -> Callable[ + [site_search_engine_service.SetUriPatternDocumentDataRequest], + operations_pb2.Operation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetUriPatternDocumentData(self._session, self._host, self._interceptor) # type: ignore + @property def update_target_site( self, @@ -2289,6 +2584,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -2411,6 +2710,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py index 117026a6902c..ca33b596e0d6 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py @@ -449,6 +449,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -511,6 +515,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", @@ -637,6 +645,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect", }, + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*}/userEvents:collect", + }, ] request, metadata = self._interceptor.pre_collect_user_event( request, metadata @@ -1175,6 +1187,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/evaluations/*/operations/*}", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*/operations/*}", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", @@ -1297,6 +1313,10 @@ def __call__( "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/identity_mapping_stores/*}/operations", + }, { "method": "get", "uri": "/v1alpha/{name=projects/*/locations/*}/operations", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py index 733193e2dee8..3f73bf8fcdbc 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py @@ -34,7 +34,7 @@ SolutionType, UserInfo, ) -from .completion import SuggestionDenyListEntry +from .completion import CompletionSuggestion, SuggestionDenyListEntry from .completion_service import CompleteQueryRequest, CompleteQueryResponse from .control import Condition, Control from .control_service import ( @@ -72,7 +72,7 @@ UpdateSessionRequest, ) from .custom_tuning_model import CustomTuningModel -from .data_store import DataStore +from .data_store import DataStore, LanguageInfo from .data_store_service import ( CreateDataStoreMetadata, CreateDataStoreRequest, @@ -134,6 +134,7 @@ ) from .grounding import FactChunk, GroundingFact from .import_config import ( + AlloyDbSource, BigQuerySource, BigtableOptions, BigtableSource, @@ -141,6 +142,9 @@ FhirStoreSource, FirestoreSource, GcsSource, + ImportCompletionSuggestionsMetadata, + ImportCompletionSuggestionsRequest, + ImportCompletionSuggestionsResponse, ImportDocumentsMetadata, ImportDocumentsRequest, ImportDocumentsResponse, @@ -164,6 +168,9 @@ ReportConsentChangeRequest, ) from .purge_config import ( + PurgeCompletionSuggestionsMetadata, + PurgeCompletionSuggestionsRequest, + PurgeCompletionSuggestionsResponse, PurgeDocumentsMetadata, PurgeDocumentsRequest, PurgeDocumentsResponse, @@ -245,11 +252,16 @@ FetchDomainVerificationStatusResponse, GetSiteSearchEngineRequest, GetTargetSiteRequest, + GetUriPatternDocumentDataRequest, + GetUriPatternDocumentDataResponse, ListTargetSitesRequest, ListTargetSitesResponse, RecrawlUrisMetadata, RecrawlUrisRequest, RecrawlUrisResponse, + SetUriPatternDocumentDataMetadata, + SetUriPatternDocumentDataRequest, + SetUriPatternDocumentDataResponse, UpdateTargetSiteMetadata, UpdateTargetSiteRequest, ) @@ -288,6 +300,7 @@ "SearchTier", "SearchUseCase", "SolutionType", + "CompletionSuggestion", "SuggestionDenyListEntry", "CompleteQueryRequest", "CompleteQueryResponse", @@ -323,6 +336,7 @@ "UpdateSessionRequest", "CustomTuningModel", "DataStore", + "LanguageInfo", "CreateDataStoreMetadata", "CreateDataStoreRequest", "DeleteDataStoreMetadata", @@ -374,6 +388,7 @@ "CheckGroundingSpec", "FactChunk", "GroundingFact", + "AlloyDbSource", "BigQuerySource", "BigtableOptions", "BigtableSource", @@ -381,6 +396,9 @@ "FhirStoreSource", "FirestoreSource", "GcsSource", + "ImportCompletionSuggestionsMetadata", + "ImportCompletionSuggestionsRequest", + "ImportCompletionSuggestionsResponse", "ImportDocumentsMetadata", "ImportDocumentsRequest", "ImportDocumentsResponse", @@ -400,6 +418,9 @@ "ProvisionProjectMetadata", "ProvisionProjectRequest", "ReportConsentChangeRequest", + "PurgeCompletionSuggestionsMetadata", + "PurgeCompletionSuggestionsRequest", + "PurgeCompletionSuggestionsResponse", "PurgeDocumentsMetadata", "PurgeDocumentsRequest", "PurgeDocumentsResponse", @@ -477,11 +498,16 @@ "FetchDomainVerificationStatusResponse", "GetSiteSearchEngineRequest", "GetTargetSiteRequest", + "GetUriPatternDocumentDataRequest", + "GetUriPatternDocumentDataResponse", "ListTargetSitesRequest", "ListTargetSitesResponse", "RecrawlUrisMetadata", "RecrawlUrisRequest", "RecrawlUrisResponse", + "SetUriPatternDocumentDataMetadata", + "SetUriPatternDocumentDataRequest", + "SetUriPatternDocumentDataResponse", "UpdateTargetSiteMetadata", "UpdateTargetSiteRequest", "CompletionInfo", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/answer.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/answer.py index c91f8d65eae8..aea3764d85fb 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/answer.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/answer.py @@ -100,12 +100,25 @@ class AnswerSkippedReason(proto.Enum): Google skips the answer if there is a potential policy violation detected. This includes content that may be violent or toxic. + NO_RELEVANT_CONTENT (5): + The no relevant content case. + + Google skips the answer if there is no relevant + content in the retrieved search results. + JAIL_BREAKING_QUERY_IGNORED (6): + The jail-breaking query ignored case. + + For example, "Reply in the tone of a competing + company's CEO". Google skips the answer if the + query is classified as a jail-breaking query. """ ANSWER_SKIPPED_REASON_UNSPECIFIED = 0 ADVERSARIAL_QUERY_IGNORED = 1 NON_ANSWER_SEEKING_QUERY_IGNORED = 2 OUT_OF_DOMAIN_QUERY_IGNORED = 3 POTENTIAL_POLICY_VIOLATION = 4 + NO_RELEVANT_CONTENT = 5 + JAIL_BREAKING_QUERY_IGNORED = 6 class Citation(proto.Message): r"""Citation info for a segment. @@ -165,6 +178,10 @@ class Reference(proto.Message): chunk_info (google.cloud.discoveryengine_v1alpha.types.Answer.Reference.ChunkInfo): Chunk information. + This field is a member of `oneof`_ ``content``. + structured_document_info (google.cloud.discoveryengine_v1alpha.types.Answer.Reference.StructuredDocumentInfo): + Structured document information. + This field is a member of `oneof`_ ``content``. """ @@ -190,11 +207,22 @@ class UnstructuredDocumentInfo(proto.Message): class ChunkContent(proto.Message): r"""Chunk content. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: content (str): Chunk textual content. page_identifier (str): Page identifier. + relevance_score (float): + The relevance of the chunk for a given query. + Values range from 0.0 (completely irrelevant) to + 1.0 (completely relevant). This value is for + informational purpose only. It may change for + the same query and chunk at any time due to a + model retraining or change in implementation. + + This field is a member of `oneof`_ ``_relevance_score``. """ content: str = proto.Field( @@ -205,6 +233,11 @@ class ChunkContent(proto.Message): proto.STRING, number=2, ) + relevance_score: float = proto.Field( + proto.FLOAT, + number=3, + optional=True, + ) document: str = proto.Field( proto.STRING, @@ -242,7 +275,12 @@ class ChunkInfo(proto.Message): content (str): Chunk textual content. relevance_score (float): - Relevance score. + The relevance of the chunk for a given query. + Values range from 0.0 (completely irrelevant) to + 1.0 (completely relevant). This value is for + informational purpose only. It may change for + the same query and chunk at any time due to a + model retraining or change in implementation. This field is a member of `oneof`_ ``_relevance_score``. document_metadata (google.cloud.discoveryengine_v1alpha.types.Answer.Reference.ChunkInfo.DocumentMetadata): @@ -310,6 +348,26 @@ class DocumentMetadata(proto.Message): ) ) + class StructuredDocumentInfo(proto.Message): + r"""Structured search information. + + Attributes: + document (str): + Document resource name. + struct_data (google.protobuf.struct_pb2.Struct): + Structured search data. + """ + + document: str = proto.Field( + proto.STRING, + number=1, + ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + unstructured_document_info: "Answer.Reference.UnstructuredDocumentInfo" = ( proto.Field( proto.MESSAGE, @@ -324,6 +382,14 @@ class DocumentMetadata(proto.Message): oneof="content", message="Answer.Reference.ChunkInfo", ) + structured_document_info: "Answer.Reference.StructuredDocumentInfo" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="content", + message="Answer.Reference.StructuredDocumentInfo", + ) + ) class Step(proto.Message): r"""Step information. @@ -410,6 +476,13 @@ class SearchResult(proto.Message): chunk_info (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Answer.Step.Action.Observation.SearchResult.ChunkInfo]): If citation_type is CHUNK_LEVEL_CITATION and chunk mode is on, populate chunk info. + struct_data (google.protobuf.struct_pb2.Struct): + Data representation. + The structured JSON data for the document. + It's populated from the struct data from the + Document , or the Chunk in + search result + . """ class SnippetInfo(proto.Message): @@ -443,7 +516,12 @@ class ChunkInfo(proto.Message): content (str): Chunk textual content. relevance_score (float): - Relevance score. + The relevance of the chunk for a given query. + Values range from 0.0 (completely irrelevant) to + 1.0 (completely relevant). This value is for + informational purpose only. It may change for + the same query and chunk at any time due to a + model retraining or change in implementation. This field is a member of `oneof`_ ``_relevance_score``. """ @@ -488,6 +566,11 @@ class ChunkInfo(proto.Message): number=5, message="Answer.Step.Action.Observation.SearchResult.ChunkInfo", ) + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) search_results: MutableSequence[ "Answer.Step.Action.Observation.SearchResult" @@ -556,10 +639,13 @@ class Type(proto.Enum): Adversarial query classification type. NON_ANSWER_SEEKING_QUERY (2): Non-answer-seeking query classification type. + JAIL_BREAKING_QUERY (3): + Jail-breaking query classification type. """ TYPE_UNSPECIFIED = 0 ADVERSARIAL_QUERY = 1 NON_ANSWER_SEEKING_QUERY = 2 + JAIL_BREAKING_QUERY = 3 type_: "Answer.QueryUnderstandingInfo.QueryClassificationInfo.Type" = ( proto.Field( diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/chunk.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/chunk.py index 3f7b6d7f569e..9fb19d7cc902 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/chunk.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/chunk.py @@ -48,9 +48,9 @@ class Chunk(proto.Message): Content is a string from a document (parsed content). relevance_score (float): - The relevance score based on similarity. Higher score - indicates higher chunk relevance. The score is in range - [-1.0, 1.0]. Only populated on + Output only. Represents the relevance score based on + similarity. Higher score indicates higher chunk relevance. + The score is in range [-1.0, 1.0]. Only populated on [SearchService.SearchResponse][]. This field is a member of `oneof`_ ``_relevance_score``. diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/completion.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/completion.py index 53c279b47280..920c005c6669 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/completion.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/completion.py @@ -23,6 +23,7 @@ package="google.cloud.discoveryengine.v1alpha", manifest={ "SuggestionDenyListEntry", + "CompletionSuggestion", }, ) @@ -68,4 +69,75 @@ class MatchOperator(proto.Enum): ) +class CompletionSuggestion(proto.Message): + r"""Autocomplete suggestions that are imported from Customer. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + global_score (float): + Global score of this suggestion. Control how + this suggestion would be scored / ranked. + + This field is a member of `oneof`_ ``ranking_info``. + frequency (int): + Frequency of this suggestion. Will be used to + rank suggestions when score is not available. + + This field is a member of `oneof`_ ``ranking_info``. + suggestion (str): + Required. The suggestion text. + language_code (str): + BCP-47 language code of this suggestion. + group_id (str): + If two suggestions have the same groupId, + they will not be returned together. Instead the + one ranked higher will be returned. This can be + used to deduplicate semantically identical + suggestions. + group_score (float): + The score of this suggestion within its + group. + alternative_phrases (MutableSequence[str]): + Alternative matching phrases for this + suggestion. + """ + + global_score: float = proto.Field( + proto.DOUBLE, + number=2, + oneof="ranking_info", + ) + frequency: int = proto.Field( + proto.INT64, + number=3, + oneof="ranking_info", + ) + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + group_id: str = proto.Field( + proto.STRING, + number=5, + ) + group_score: float = proto.Field( + proto.DOUBLE, + number=6, + ) + alternative_phrases: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py index 39a949871fd2..477e794f1b24 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py @@ -433,6 +433,28 @@ class AnswerQueryRequest(proto.Message): The field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error is returned. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. """ class SafetySpec(proto.Message): @@ -639,14 +661,8 @@ class SearchParams(proto.Message): returned. search_result_mode (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SearchResultMode): Specifies the search result mode. If unspecified, the search - result mode is based on - [DataStore.DocumentProcessingConfig.chunking_config][]: - - - If [DataStore.DocumentProcessingConfig.chunking_config][] - is specified, it defaults to ``CHUNKS``. - - Otherwise, it defaults to ``DOCUMENTS``. See `parse and - chunk - documents `__ + result mode defaults to ``DOCUMENTS``. See `parse and chunk + documents `__ custom_fine_tuning_spec (google.cloud.discoveryengine_v1alpha.types.CustomFineTuningSpec): Custom fine tuning configs. data_store_specs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.DataStoreSpec]): @@ -916,10 +932,13 @@ class Type(proto.Enum): Adversarial query classification type. NON_ANSWER_SEEKING_QUERY (2): Non-answer-seeking query classification type. + JAIL_BREAKING_QUERY (3): + Jail-breaking query classification type. """ TYPE_UNSPECIFIED = 0 ADVERSARIAL_QUERY = 1 NON_ANSWER_SEEKING_QUERY = 2 + JAIL_BREAKING_QUERY = 3 types: MutableSequence[ "AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type" @@ -1008,6 +1027,11 @@ class QueryRephraserSpec(proto.Message): proto.STRING, number=12, ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=13, + ) class AnswerQueryResponse(proto.Message): @@ -1018,8 +1042,8 @@ class AnswerQueryResponse(proto.Message): Attributes: answer (google.cloud.discoveryengine_v1alpha.types.Answer): Answer resource object. If - [AnswerQueryRequest.StepSpec.max_step_count][] is greater - than 1, use + [AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec.max_rephrase_steps][google.cloud.discoveryengine.v1alpha.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec.max_rephrase_steps] + is greater than 1, use [Answer.name][google.cloud.discoveryengine.v1alpha.Answer.name] to fetch answer information using [ConversationalSearchService.GetAnswer][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.GetAnswer] diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/custom_tuning_model.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/custom_tuning_model.py index 85992c5f567e..ab529ab2e91f 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/custom_tuning_model.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/custom_tuning_model.py @@ -50,6 +50,8 @@ class CustomTuningModel(proto.Message): Timestamp the Model was created at. training_start_time (google.protobuf.timestamp_pb2.Timestamp): Timestamp the model training was initiated. + metrics (MutableMapping[str, float]): + The metrics of the trained model. """ class ModelState(proto.Enum): @@ -69,6 +71,9 @@ class ModelState(proto.Enum): The model is ready for serving. TRAINING_FAILED (5): The model training failed. + NO_IMPROVEMENT (6): + The model training finished successfully but + metrics did not improve. """ MODEL_STATE_UNSPECIFIED = 0 TRAINING_PAUSED = 1 @@ -76,6 +81,7 @@ class ModelState(proto.Enum): TRAINING_COMPLETE = 3 READY_FOR_SERVING = 4 TRAINING_FAILED = 5 + NO_IMPROVEMENT = 6 name: str = proto.Field( proto.STRING, @@ -104,6 +110,11 @@ class ModelState(proto.Enum): number=6, message=timestamp_pb2.Timestamp, ) + metrics: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=7, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py index d974ecb7ccc5..82b01be6e0e5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py @@ -30,6 +30,7 @@ package="google.cloud.discoveryengine.v1alpha", manifest={ "DataStore", + "LanguageInfo", }, ) @@ -76,6 +77,8 @@ class DataStore(proto.Message): Output only. Timestamp the [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] was created at. + language_info (google.cloud.discoveryengine_v1alpha.types.LanguageInfo): + Language info for DataStore. idp_config (google.cloud.discoveryengine_v1alpha.types.IdpConfig): Output only. Data store level identity provider config. @@ -173,6 +176,11 @@ class ContentConfig(proto.Enum): number=4, message=timestamp_pb2.Timestamp, ) + language_info: "LanguageInfo" = proto.Field( + proto.MESSAGE, + number=14, + message="LanguageInfo", + ) idp_config: common.IdpConfig = proto.Field( proto.MESSAGE, number=21, @@ -194,4 +202,42 @@ class ContentConfig(proto.Enum): ) +class LanguageInfo(proto.Message): + r"""Language info for DataStore. + + Attributes: + language_code (str): + The language code for the DataStore. + normalized_language_code (str): + Output only. This is the normalized form of language_code. + E.g.: language_code of ``en-GB``, ``en_GB``, ``en-UK`` or + ``en-gb`` will have normalized_language_code of ``en-GB``. + language (str): + Output only. Language part of normalized_language_code. + E.g.: ``en-US`` -> ``en``, ``zh-Hans-HK`` -> ``zh``, ``en`` + -> ``en``. + region (str): + Output only. Region part of normalized_language_code, if + present. E.g.: ``en-US`` -> ``US``, ``zh-Hans-HK`` -> + ``HK``, ``en`` -> \``. + """ + + language_code: str = proto.Field( + proto.STRING, + number=1, + ) + normalized_language_code: str = proto.Field( + proto.STRING, + number=2, + ) + language: str = proto.Field( + proto.STRING, + number=3, + ) + region: str = proto.Field( + proto.STRING, + number=4, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py index d98a83c8021e..6209648b303a 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py @@ -72,6 +72,17 @@ class CreateDataStoreRequest(proto.Message): create an advanced data store for site search. If the data store is not configured as site search (GENERIC vertical and PUBLIC_WEBSITE content_config), this flag will be ignored. + skip_default_schema_creation (bool): + A boolean flag indicating whether to skip the default schema + creation for the data store. Only enable this flag if you + are certain that the default schema is incompatible with + your use case. + + If set to true, you must manually create a schema for the + data store before any documents can be ingested. + + This flag cannot be specified if + ``data_store.starting_schema`` is specified. """ parent: str = proto.Field( @@ -91,6 +102,10 @@ class CreateDataStoreRequest(proto.Message): proto.BOOL, number=4, ) + skip_default_schema_creation: bool = proto.Field( + proto.BOOL, + number=7, + ) class GetDataStoreRequest(proto.Message): @@ -180,7 +195,7 @@ class ListDataStoresRequest(proto.Message): must match the call that provided the page token. Otherwise, an INVALID_ARGUMENT error is returned. filter (str): - Filter by solution type. For example: + Filter by solution type . For example: ``filter = 'solution_type:SOLUTION_TYPE_SEARCH'`` """ diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document.py index 0134792178ce..7792e6eb5a81 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document.py @@ -124,7 +124,7 @@ class Content(proto.Message): uri (str): The URI of the content. Only Cloud Storage URIs (e.g. ``gs://bucket-name/path/to/file``) are supported. The - maximum file size is 2.5 MB for text-based formats, 100 MB + maximum file size is 2.5 MB for text-based formats, 200 MB for other formats. This field is a member of `oneof`_ ``content``. @@ -189,6 +189,8 @@ class AccessRestriction(proto.Message): Attributes: principals (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Principal]): List of principals. + idp_wide (bool): + All users within the Identity Provider. """ principals: MutableSequence[common.Principal] = proto.RepeatedField( @@ -196,6 +198,10 @@ class AccessRestriction(proto.Message): number=1, message=common.Principal, ) + idp_wide: bool = proto.Field( + proto.BOOL, + number=2, + ) readers: MutableSequence[ "Document.AclInfo.AccessRestriction" diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_processing_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_processing_config.py index 11db01fea067..35ef016b7661 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_processing_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_processing_config.py @@ -57,9 +57,13 @@ class DocumentProcessingConfig(proto.Message): digital parsing, ocr parsing or layout parsing is supported. - ``html``: Override parsing config for HTML files, only - digital parsing and or layout parsing are supported. + digital parsing and layout parsing are supported. - ``docx``: Override parsing config for DOCX files, only - digital parsing and or layout parsing are supported. + digital parsing and layout parsing are supported. + - ``pptx``: Override parsing config for PPTX files, only + digital parsing and layout parsing are supported. + - ``xlsx``: Override parsing config for XLSX files, only + digital parsing and layout parsing are supported. """ class ChunkingConfig(proto.Message): diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_service.py index bbbf2ca1e493..cee091f225bd 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/document_service.py @@ -311,8 +311,8 @@ class ProcessedDocumentType(proto.Enum): Only available if ChunkingConfig is enabled on the data store. PNG_CONVERTED_DOCUMENT (3): - Returns the converted PNG Image bytes if - available. + Returns the converted Image bytes (as JPEG or + PNG) if available. """ PROCESSED_DOCUMENT_TYPE_UNSPECIFIED = 0 PARSED_DOCUMENT = 1 diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py index 8926d209b780..35e5e74f7660 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/import_config.py @@ -40,6 +40,7 @@ "BigtableSource", "FhirStoreSource", "CloudSqlSource", + "AlloyDbSource", "FirestoreSource", "ImportErrorConfig", "ImportUserEventsRequest", @@ -51,6 +52,9 @@ "ImportSuggestionDenyListEntriesRequest", "ImportSuggestionDenyListEntriesResponse", "ImportSuggestionDenyListEntriesMetadata", + "ImportCompletionSuggestionsRequest", + "ImportCompletionSuggestionsResponse", + "ImportCompletionSuggestionsMetadata", "ImportSampleQueriesRequest", "ImportSampleQueriesResponse", "ImportSampleQueriesMetadata", @@ -474,6 +478,11 @@ class FhirStoreSource(proto.Message): characters. Can be specified if one wants to have the FhirStore export to a specific Cloud Storage directory. + resource_types (MutableSequence[str]): + The FHIR resource types to import. The resource types should + be a subset of all `supported FHIR resource + types `__. + Default to all supported FHIR resource types if empty. """ fhir_store: str = proto.Field( @@ -484,6 +493,10 @@ class FhirStoreSource(proto.Message): proto.STRING, number=2, ) + resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) class CloudSqlSource(proto.Message): @@ -546,6 +559,65 @@ class CloudSqlSource(proto.Message): ) +class AlloyDbSource(proto.Message): + r"""AlloyDB source import data from. + + Attributes: + project_id (str): + The project ID that the AlloyDB source is in + with a length limit of 128 characters. If not + specified, inherits the project ID from the + parent request. + location_id (str): + Required. The AlloyDB location to copy the + data from with a length limit of 256 characters. + cluster_id (str): + Required. The AlloyDB cluster to copy the + data from with a length limit of 256 characters. + database_id (str): + Required. The AlloyDB database to copy the + data from with a length limit of 256 characters. + table_id (str): + Required. The AlloyDB table to copy the data + from with a length limit of 256 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the AlloyDB export to a specific Cloud + Storage directory. + + Ensure that the AlloyDB service account has the + necessary Cloud Storage Admin permissions to + access the specified Cloud Storage directory. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + location_id: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_id: str = proto.Field( + proto.STRING, + number=4, + ) + table_id: str = proto.Field( + proto.STRING, + number=5, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=6, + ) + + class FirestoreSource(proto.Message): r"""Firestore source import data from. @@ -857,6 +929,10 @@ class ImportDocumentsRequest(proto.Message): firestore_source (google.cloud.discoveryengine_v1alpha.types.FirestoreSource): Firestore input source. + This field is a member of `oneof`_ ``source``. + alloy_db_source (google.cloud.discoveryengine_v1alpha.types.AlloyDbSource): + AlloyDB input source. + This field is a member of `oneof`_ ``source``. bigtable_source (google.cloud.discoveryengine_v1alpha.types.BigtableSource): Cloud Bigtable input source. @@ -1031,6 +1107,12 @@ class InlineSource(proto.Message): oneof="source", message="FirestoreSource", ) + alloy_db_source: "AlloyDbSource" = proto.Field( + proto.MESSAGE, + number=14, + oneof="source", + message="AlloyDbSource", + ) bigtable_source: "BigtableSource" = proto.Field( proto.MESSAGE, number=15, @@ -1221,6 +1303,157 @@ class ImportSuggestionDenyListEntriesMetadata(proto.Message): ) +class ImportCompletionSuggestionsRequest(proto.Message): + r"""Request message for + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + inline_source (google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsRequest.InlineSource): + The Inline source for suggestion entries. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1alpha.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1alpha.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent data store resource name for which to + import customer autocomplete suggestions. + + Follows pattern + ``projects/*/locations/*/collections/*/dataStores/*`` + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + class InlineSource(proto.Message): + r"""The inline source for CompletionSuggestions. + + Attributes: + suggestions (MutableSequence[google.cloud.discoveryengine_v1alpha.types.CompletionSuggestion]): + Required. A list of all denylist entries to + import. Max of 1000 items. + """ + + suggestions: MutableSequence[ + completion.CompletionSuggestion + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=completion.CompletionSuggestion, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=InlineSource, + ) + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message="GcsSource", + ) + bigquery_source: "BigQuerySource" = proto.Field( + proto.MESSAGE, + number=4, + oneof="source", + message="BigQuerySource", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="ImportErrorConfig", + ) + + +class ImportCompletionSuggestionsResponse(proto.Message): + r"""Response of the + [CompletionService.ImportCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions] + method. If the long running operation is done, this message is + returned by the google.longrunning.Operations.response field if the + operation is successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: "ImportErrorConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="ImportErrorConfig", + ) + + +class ImportCompletionSuggestionsMetadata(proto.Message): + r"""Metadata related to the progress of the + ImportCompletionSuggestions operation. This will be returned by + the google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + successfully imported. + failure_count (int): + Count of + [CompletionSuggestion][google.cloud.discoveryengine.v1alpha.CompletionSuggestion]s + that failed to be imported. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + class ImportSampleQueriesRequest(proto.Message): r"""Request message for [SampleQueryService.ImportSampleQueries][google.cloud.discoveryengine.v1alpha.SampleQueryService.ImportSampleQueries] diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/purge_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/purge_config.py index 214e53a08daf..dffcc82360a6 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/purge_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/purge_config.py @@ -36,6 +36,9 @@ "PurgeSuggestionDenyListEntriesRequest", "PurgeSuggestionDenyListEntriesResponse", "PurgeSuggestionDenyListEntriesMetadata", + "PurgeCompletionSuggestionsRequest", + "PurgeCompletionSuggestionsResponse", + "PurgeCompletionSuggestionsMetadata", }, ) @@ -178,6 +181,10 @@ class PurgeDocumentsRequest(proto.Message): [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] method. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -190,6 +197,11 @@ class PurgeDocumentsRequest(proto.Message): [Document.id][google.cloud.discoveryengine.v1alpha.Document.id] per line. + This field is a member of `oneof`_ ``source``. + inline_source (google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest.InlineSource): + Inline source for the input content for + purge. + This field is a member of `oneof`_ ``source``. parent (str): Required. The parent resource name, such as @@ -206,12 +218,36 @@ class PurgeDocumentsRequest(proto.Message): documents. """ + class InlineSource(proto.Message): + r"""The inline source for the input config for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. + + Attributes: + documents (MutableSequence[str]): + Required. A list of full resource name of documents to + purge. In the format + ``projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*``. + Recommended max of 100 items. + """ + + documents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + gcs_source: import_config.GcsSource = proto.Field( proto.MESSAGE, number=5, oneof="source", message=import_config.GcsSource, ) + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=6, + oneof="source", + message=InlineSource, + ) parent: str = proto.Field( proto.STRING, number=1, @@ -372,4 +408,72 @@ class PurgeSuggestionDenyListEntriesMetadata(proto.Message): ) +class PurgeCompletionSuggestionsRequest(proto.Message): + r"""Request message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + + Attributes: + parent (str): + Required. The parent data store resource name for which to + purge completion suggestions. Follows pattern + projects/\ */locations/*/collections/*/dataStores/*. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PurgeCompletionSuggestionsResponse(proto.Message): + r"""Response message for + [CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions] + method. + + Attributes: + purge_succeeded (bool): + Whether the completion suggestions were + successfully purged. + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + """ + + purge_succeeded: bool = proto.Field( + proto.BOOL, + number=1, + ) + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +class PurgeCompletionSuggestionsMetadata(proto.Message): + r"""Metadata related to the progress of the + PurgeCompletionSuggestions operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/schema.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/schema.py index aabad9f12b6e..3d8194328771 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/schema.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/schema.py @@ -423,12 +423,17 @@ class AdvancedSiteSearchDataSource(proto.Enum): Retrieve value from meta tag. PAGEMAP (2): Retrieve value from page map. + URI_PATTERN_MAPPING (3): + Retrieve value from the attributes set by + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + API. SCHEMA_ORG (4): Retrieve value from schema.org data. """ ADVANCED_SITE_SEARCH_DATA_SOURCE_UNSPECIFIED = 0 METATAGS = 1 PAGEMAP = 2 + URI_PATTERN_MAPPING = 3 SCHEMA_ORG = 4 field_path: str = proto.Field( diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py index 808fa372ae30..00e46651dd81 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py @@ -139,9 +139,12 @@ class SearchRequest(proto.Message): object. Leave it unset if ordered by relevance. ``order_by`` expression is case-sensitive. - For more information on ordering for retail search, see - `Ordering `__ - + For more information on ordering the website search results, + see `Order web search + results `__. + For more information on ordering the healthcare search + results, see `Order healthcare search + results `__. If this field is unrecognizable, an ``INVALID_ARGUMENT`` is returned. user_info (google.cloud.discoveryengine_v1alpha.types.UserInfo): @@ -149,6 +152,19 @@ class SearchRequest(proto.Message): analytics. [UserInfo.user_agent][google.cloud.discoveryengine.v1alpha.UserInfo.user_agent] is used to deduce ``device_type`` for analytics. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see `Standard + fields `__. + This field helps to better interpret the query. If a value + isn't specified, the query language code is automatically + detected, which may not be accurate. + region_code (str): + The Unicode country/region code (CLDR) of a location, such + as "US" and "419". For more information, see `Standard + fields `__. + If set, then results will be boosted based on the + region_code provided. facet_specs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.FacetSpec]): Facet specifications for faceted search. If empty, no facets are returned. @@ -222,22 +238,30 @@ class SearchRequest(proto.Message): retrieval documents. This overrides [ServingConfig.ranking_expression][google.cloud.discoveryengine.v1alpha.ServingConfig.ranking_expression]. The ranking expression is a single function or multiple - functions that are joint by "+". + functions that are joined by "+". - ranking_expression = function, { " + ", function }; - Supported functions: + + Supported functions: + - double \* relevance_score - - double \* dotProduct(embedding_field_path) Function - variables: ``relevance_score``: pre-defined keywords, - used for measure relevance between query and document. - ``embedding_field_path``: the document embedding field - used with query embedding vector. ``dotProduct``: - embedding function between embedding_field_path and query - embedding vector. - - Example ranking expression: If document has an embedding - field doc_embedding, the ranking expression could be - ``0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)``. + - double \* dotProduct(embedding_field_path) + + Function variables: + + - ``relevance_score``: pre-defined keywords, used for + measure relevance between query and document. + - ``embedding_field_path``: the document embedding field + used with query embedding vector. + - ``dotProduct``: embedding function between + embedding_field_path and query embedding vector. + + Example ranking expression: + + :: + + If document has an embedding field doc_embedding, the ranking expression + could be `0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)`. safe_search (bool): Whether to turn on safe search. This is only supported for website search. @@ -263,10 +287,88 @@ class SearchRequest(proto.Message): See `Google Cloud Document `__ for more details. + natural_language_query_understanding_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec): + If ``naturalLanguageQueryUnderstandingSpec`` is not + specified, no additional natural language query + understanding will be done. + search_as_you_type_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SearchAsYouTypeSpec): + Search as you type configuration. Only supported for the + [IndustryVertical.MEDIA][google.cloud.discoveryengine.v1alpha.IndustryVertical.MEDIA] + vertical. custom_fine_tuning_spec (google.cloud.discoveryengine_v1alpha.types.CustomFineTuningSpec): - Custom fine tuning configs. + Custom fine tuning configs. If set, it has higher priority + than the configs set in + [ServingConfig.custom_fine_tuning_spec][google.cloud.discoveryengine.v1alpha.ServingConfig.custom_fine_tuning_spec]. + session (str): + The session resource name. Optional. + + Session allows users to do multi-turn /search API calls or + coordination between /search API calls and /answer API + calls. + + Example #1 (multi-turn /search API calls): + + 1. Call /search API with the auto-session mode (see below). + 2. Call /search API with the session ID generated in the + first call. Here, the previous search query gets + considered in query standing. I.e., if the first query is + "How did Alphabet do in 2022?" and the current query is + "How about 2023?", the current query will be interpreted + as "How did Alphabet do in 2023?". + + Example #2 (coordination between /search API calls and + /answer API calls): + + 1. Call /search API with the auto-session mode (see below). + 2. Call /answer API with the session ID generated in the + first call. Here, the answer generation happens in the + context of the search results from the first search call. + + Auto-session mode: when ``projects/.../sessions/-`` is used, + a new session gets automatically created. Otherwise, users + can use the create-session API to create a session manually. + + Multi-turn Search feature is currently at private GA stage. + Please use v1alpha or v1beta version instead before we + launch this feature to public GA. Or ask for allowlisting + through Google Support team. + session_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SessionSpec): + Session specification. + + Can be used only when ``session`` is set. + relevance_threshold (google.cloud.discoveryengine_v1alpha.types.SearchRequest.RelevanceThreshold): + The relevance threshold of the search + results. + Default to Google defined threshold, leveraging + a balance of precision and recall to deliver + both highly accurate results and comprehensive + coverage of relevant information. """ + class RelevanceThreshold(proto.Enum): + r"""The relevance threshold of the search results. The higher + relevance threshold is, the higher relevant results are shown + and the less number of results are returned. + + Values: + RELEVANCE_THRESHOLD_UNSPECIFIED (0): + Default value. In this case, server behavior + defaults to Google defined threshold. + LOWEST (1): + Lowest relevance threshold. + LOW (2): + Low relevance threshold. + MEDIUM (3): + Medium relevance threshold. + HIGH (4): + High relevance threshold. + """ + RELEVANCE_THRESHOLD_UNSPECIFIED = 0 + LOWEST = 1 + LOW = 2 + MEDIUM = 3 + HIGH = 4 + class ImageQuery(proto.Message): r"""Specifies the image query input. @@ -288,9 +390,8 @@ class ImageQuery(proto.Message): class DataStoreSpec(proto.Message): r"""A struct to define data stores to filter on in a search call and - configurations for those data stores. A maximum of 1 DataStoreSpec - per data_store is allowed. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. + configurations for those data stores. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. Attributes: data_store (str): @@ -314,7 +415,10 @@ class FacetSpec(proto.Message): limit (int): Maximum facet values that are returned for this facet. If unspecified, defaults to 20. The maximum allowed value is - 300. Values above 300 are coerced to 300. + 300. Values above 300 are coerced to 300. For aggregation in + healthcare search, when the [FacetKey.key] is + "healthcare_aggregation_key", the limit will be overridden + to 10,000 internally, regardless of the value set here. If this field is negative, an ``INVALID_ARGUMENT`` is returned. @@ -914,6 +1018,14 @@ class SummarySpec(proto.Message): navigational queries. If this field is set to ``true``, we skip generating summaries for non-summary seeking queries and return fallback messages instead. + ignore_low_relevant_content (bool): + Specifies whether to filter out queries that have low + relevance. The default value is ``false``. + + If this field is set to ``false``, all search results are + used regardless of relevance to generate answers. If set to + ``true``, only queries with high relevance search results + will generate answers. model_prompt_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec): If specified, the spec will be used to modify the prompt provided to the LLM. @@ -991,6 +1103,10 @@ class ModelSpec(proto.Message): proto.BOOL, number=4, ) + ignore_low_relevant_content: bool = proto.Field( + proto.BOOL, + number=9, + ) model_prompt_spec: "SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec" = proto.Field( proto.MESSAGE, number=5, @@ -1182,6 +1298,144 @@ class EmbeddingVector(proto.Message): message="SearchRequest.EmbeddingSpec.EmbeddingVector", ) + class NaturalLanguageQueryUnderstandingSpec(proto.Message): + r"""Specification to enable natural language understanding + capabilities for search requests. + + Attributes: + filter_extraction_condition (google.cloud.discoveryengine_v1alpha.types.SearchRequest.NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition): + The condition under which filter extraction should occur. + Default to [Condition.DISABLED][]. + geo_search_query_detection_field_names (MutableSequence[str]): + Field names used for location-based filtering, where + geolocation filters are detected in natural language search + queries. Only valid when the FilterExtractionCondition is + set to ``ENABLED``. + + If this field is set, it overrides the field names set in + [ServingConfig.geo_search_query_detection_field_names][google.cloud.discoveryengine.v1alpha.ServingConfig.geo_search_query_detection_field_names]. + """ + + class FilterExtractionCondition(proto.Enum): + r"""Enum describing under which condition filter extraction + should occur. + + Values: + CONDITION_UNSPECIFIED (0): + Server behavior defaults to [Condition.DISABLED][]. + DISABLED (1): + Disables NL filter extraction. + ENABLED (2): + Enables NL filter extraction. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + filter_extraction_condition: "SearchRequest.NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.NaturalLanguageQueryUnderstandingSpec.FilterExtractionCondition", + ) + geo_search_query_detection_field_names: MutableSequence[ + str + ] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class SearchAsYouTypeSpec(proto.Message): + r"""Specification for search as you type in search requests. + + Attributes: + condition (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SearchAsYouTypeSpec.Condition): + The condition under which search as you type should occur. + Default to + [Condition.DISABLED][google.cloud.discoveryengine.v1alpha.SearchRequest.SearchAsYouTypeSpec.Condition.DISABLED]. + """ + + class Condition(proto.Enum): + r"""Enum describing under which condition search as you type + should occur. + + Values: + CONDITION_UNSPECIFIED (0): + Server behavior defaults to + [Condition.DISABLED][google.cloud.discoveryengine.v1alpha.SearchRequest.SearchAsYouTypeSpec.Condition.DISABLED]. + DISABLED (1): + Disables Search As You Type. + ENABLED (2): + Enables Search As You Type. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + condition: "SearchRequest.SearchAsYouTypeSpec.Condition" = proto.Field( + proto.ENUM, + number=1, + enum="SearchRequest.SearchAsYouTypeSpec.Condition", + ) + + class SessionSpec(proto.Message): + r"""Session specification. + + Multi-turn Search feature is currently at private GA stage. + Please use v1alpha or v1beta version instead before we launch + this feature to public GA. Or ask for allowlisting through + Google Support team. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + query_id (str): + If set, the search result gets stored to the "turn" + specified by this query ID. + + Example: Let's say the session looks like this: session { + name: ".../sessions/xxx" turns { query { text: "What is + foo?" query_id: ".../questions/yyy" } answer: "Foo is ..." } + turns { query { text: "How about bar then?" query_id: + ".../questions/zzz" } } } + + The user can call /search API with a request like this: + + :: + + session: ".../sessions/xxx" + session_spec { query_id: ".../questions/zzz" } + + Then, the API stores the search result, associated with the + last turn. The stored search result can be used by a + subsequent /answer API call (with the session ID and the + query ID specified). Also, it is possible to call /search + and /answer in parallel with the same session ID & query ID. + search_result_persistence_count (int): + The number of top search results to persist. The persisted + search results can be used for the subsequent /answer api + call. + + This field is simliar to the ``summary_result_count`` field + in + [SearchRequest.ContentSearchSpec.SummarySpec.summary_result_count][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.summary_result_count]. + + At most 10 results for documents mode, or 50 for chunks + mode. + + This field is a member of `oneof`_ ``_search_result_persistence_count``. + """ + + query_id: str = proto.Field( + proto.STRING, + number=1, + ) + search_result_persistence_count: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + serving_config: str = proto.Field( proto.STRING, number=1, @@ -1233,6 +1487,14 @@ class EmbeddingVector(proto.Message): number=21, message=common.UserInfo, ) + language_code: str = proto.Field( + proto.STRING, + number=35, + ) + region_code: str = proto.Field( + proto.STRING, + number=36, + ) facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( proto.MESSAGE, number=9, @@ -1286,11 +1548,37 @@ class EmbeddingVector(proto.Message): proto.STRING, number=22, ) + natural_language_query_understanding_spec: NaturalLanguageQueryUnderstandingSpec = ( + proto.Field( + proto.MESSAGE, + number=28, + message=NaturalLanguageQueryUnderstandingSpec, + ) + ) + search_as_you_type_spec: SearchAsYouTypeSpec = proto.Field( + proto.MESSAGE, + number=31, + message=SearchAsYouTypeSpec, + ) custom_fine_tuning_spec: common.CustomFineTuningSpec = proto.Field( proto.MESSAGE, number=34, message=common.CustomFineTuningSpec, ) + session: str = proto.Field( + proto.STRING, + number=41, + ) + session_spec: SessionSpec = proto.Field( + proto.MESSAGE, + number=42, + message=SessionSpec, + ) + relevance_threshold: RelevanceThreshold = proto.Field( + proto.ENUM, + number=44, + enum=RelevanceThreshold, + ) class SearchResponse(proto.Message): @@ -1348,6 +1636,18 @@ class SearchResponse(proto.Message): query_expansion_info (google.cloud.discoveryengine_v1alpha.types.SearchResponse.QueryExpansionInfo): Query expansion information for the returned results. + natural_language_query_understanding_info (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo): + Natural language query understanding + information for the returned results. + session_info (google.cloud.discoveryengine_v1alpha.types.SearchResponse.SessionInfo): + Session information. + + Only set if + [SearchRequest.session][google.cloud.discoveryengine.v1alpha.SearchRequest.session] + is provided. See its description for more details. + one_box_results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.OneBoxResult]): + A list of One Box results. There can be + multiple One Box results of different types. """ class SearchResult(proto.Message): @@ -1536,13 +1836,13 @@ class SummarySkippedReason(proto.Enum): ADVERSARIAL_QUERY_IGNORED (1): The adversarial query ignored case. - Only populated when + Only used when [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] is set to ``true``. NON_SUMMARY_SEEKING_QUERY_IGNORED (2): The non-summary seeking query ignored case. - Only populated when + Only used when [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] is set to ``true``. OUT_OF_DOMAIN_QUERY_IGNORED (3): @@ -1564,6 +1864,18 @@ class SummarySkippedReason(proto.Enum): Google skips the summary if the LLM addon is not enabled. + NO_RELEVANT_CONTENT (6): + The no relevant content case. + + Google skips the summary if there is no relevant + content in the retrieved search results. + JAIL_BREAKING_QUERY_IGNORED (7): + The jail-breaking query ignored case. + + For example, "Reply in the tone of a competing company's + CEO". Only used when + [SearchRequest.ContentSearchSpec.SummarySpec.ignore_jail_breaking_query] + is set to ``true``. """ SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 ADVERSARIAL_QUERY_IGNORED = 1 @@ -1571,6 +1883,8 @@ class SummarySkippedReason(proto.Enum): OUT_OF_DOMAIN_QUERY_IGNORED = 3 POTENTIAL_POLICY_VIOLATION = 4 LLM_ADDON_NOT_ENABLED = 5 + NO_RELEVANT_CONTENT = 6 + JAIL_BREAKING_QUERY_IGNORED = 7 class SafetyAttributes(proto.Message): r"""Safety Attribute categories and their associated confidence @@ -1813,6 +2127,350 @@ class QueryExpansionInfo(proto.Message): number=2, ) + class NaturalLanguageQueryUnderstandingInfo(proto.Message): + r"""Information describing what natural language understanding + was done on the input query. + + Attributes: + extracted_filters (str): + The filters that were extracted from the + input query. + rewritten_query (str): + Rewritten input query minus the extracted + filters. + structured_extracted_filter (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter): + The filters that were extracted from the + input query represented in a structured form. + """ + + class StructuredExtractedFilter(proto.Message): + r"""The filters that were extracted from the input query + represented in a structured form. + + Attributes: + expression (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression): + The expression denoting the filter that was + extracted from the input query in a structured + form. It can be a simple expression denoting a + single string, numerical or geolocation + constraint or a compound expression which is a + combination of multiple expressions connected + using logical (OR and AND) operators. + """ + + class StringConstraint(proto.Message): + r"""Constraint expression of a string field. + + Attributes: + field_name (str): + Name of the string field as defined in the + schema. + values (MutableSequence[str]): + Values of the string field. The record will + only be returned if the field value matches one + of the values specified here. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class NumberConstraint(proto.Message): + r"""Constraint expression of a number field. Example: price < + 100. + + Attributes: + field_name (str): + Name of the numerical field as defined in the + schema. + comparison (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint.Comparison): + The comparison operation performed between + the field value and the value specified in the + constraint. + value (float): + The value specified in the numerical + constraint. + """ + + class Comparison(proto.Enum): + r"""The comparison operation that was performed. + + Values: + COMPARISON_UNSPECIFIED (0): + Undefined comparison operator. + EQUALS (1): + Denotes equality ``=`` operator. + LESS_THAN_EQUALS (2): + Denotes less than or equal to ``<=`` operator. + LESS_THAN (3): + Denotes less than ``<`` operator. + GREATER_THAN_EQUALS (4): + Denotes greater than or equal to ``>=`` operator. + GREATER_THAN (5): + Denotes greater than ``>`` operator. + """ + COMPARISON_UNSPECIFIED = 0 + EQUALS = 1 + LESS_THAN_EQUALS = 2 + LESS_THAN = 3 + GREATER_THAN_EQUALS = 4 + GREATER_THAN = 5 + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + comparison: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint.Comparison" = proto.Field( + proto.ENUM, + number=2, + enum="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint.Comparison", + ) + value: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + class GeolocationConstraint(proto.Message): + r"""Constraint of a geolocation field. + Name of the geolocation field as defined in the schema. + + Attributes: + field_name (str): + The name of the geolocation field as defined + in the schema. + address (str): + The reference address that was inferred from + the input query. The proximity of the reference + address to the geolocation field will be used to + filter the results. + latitude (float): + The latitude of the geolocation inferred from + the input query. + longitude (float): + The longitude of the geolocation inferred + from the input query. + radius_in_meters (float): + The radius in meters around the address. The + record is returned if the location of the + geolocation field is within the radius. + """ + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + address: str = proto.Field( + proto.STRING, + number=2, + ) + latitude: float = proto.Field( + proto.DOUBLE, + number=4, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=5, + ) + radius_in_meters: float = proto.Field( + proto.FLOAT, + number=3, + ) + + class AndExpression(proto.Message): + r"""Logical ``And`` operator. + + Attributes: + expressions (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression]): + The expressions that were ANDed together. + """ + + expressions: MutableSequence[ + "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression", + ) + + class OrExpression(proto.Message): + r"""Logical ``Or`` operator. + + Attributes: + expressions (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression]): + The expressions that were ORed together. + """ + + expressions: MutableSequence[ + "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression", + ) + + class Expression(proto.Message): + r"""The expression denoting the filter that was extracted from + the input query. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_constraint (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.StringConstraint): + String constraint expression. + + This field is a member of `oneof`_ ``expr``. + number_constraint (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint): + Numerical constraint expression. + + This field is a member of `oneof`_ ``expr``. + geolocation_constraint (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.GeolocationConstraint): + Geolocation constraint expression. + + This field is a member of `oneof`_ ``expr``. + and_expr (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.AndExpression): + Logical "And" compound operator connecting + multiple expressions. + + This field is a member of `oneof`_ ``expr``. + or_expr (google.cloud.discoveryengine_v1alpha.types.SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.OrExpression): + Logical "Or" compound operator connecting + multiple expressions. + + This field is a member of `oneof`_ ``expr``. + """ + + string_constraint: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.StringConstraint" = proto.Field( + proto.MESSAGE, + number=1, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.StringConstraint", + ) + number_constraint: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint" = proto.Field( + proto.MESSAGE, + number=2, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.NumberConstraint", + ) + geolocation_constraint: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.GeolocationConstraint" = proto.Field( + proto.MESSAGE, + number=3, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.GeolocationConstraint", + ) + and_expr: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.AndExpression" = proto.Field( + proto.MESSAGE, + number=4, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.AndExpression", + ) + or_expr: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.OrExpression" = proto.Field( + proto.MESSAGE, + number=5, + oneof="expr", + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.OrExpression", + ) + + expression: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression" = proto.Field( + proto.MESSAGE, + number=1, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter.Expression", + ) + + extracted_filters: str = proto.Field( + proto.STRING, + number=1, + ) + rewritten_query: str = proto.Field( + proto.STRING, + number=2, + ) + structured_extracted_filter: "SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter" = proto.Field( + proto.MESSAGE, + number=3, + message="SearchResponse.NaturalLanguageQueryUnderstandingInfo.StructuredExtractedFilter", + ) + + class SessionInfo(proto.Message): + r"""Information about the session. + + Attributes: + name (str): + Name of the session. If the auto-session mode is used (when + [SearchRequest.session][google.cloud.discoveryengine.v1alpha.SearchRequest.session] + ends with "-"), this field holds the newly generated session + name. + query_id (str): + Query ID that corresponds to this search API + call. One session can have multiple turns, each + with a unique query ID. + + By specifying the session name and this query ID + in the Answer API call, the answer generation + happens in the context of the search results + from this search call. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query_id: str = proto.Field( + proto.STRING, + number=2, + ) + + class OneBoxResult(proto.Message): + r"""OneBoxResult is a holder for all results of specific type + that we want to display in UI differently. + + Attributes: + one_box_type (google.cloud.discoveryengine_v1alpha.types.SearchResponse.OneBoxResult.OneBoxType): + The type of One Box result. + search_results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.SearchResult]): + The search results for this One Box. + """ + + class OneBoxType(proto.Enum): + r"""The type of One Box result. + + Values: + ONE_BOX_TYPE_UNSPECIFIED (0): + Default value. Should not be used. + PEOPLE (1): + One Box result contains people results. + ORGANIZATION (2): + One Box result contains organization results. + SLACK (3): + One Box result contains slack results. + """ + ONE_BOX_TYPE_UNSPECIFIED = 0 + PEOPLE = 1 + ORGANIZATION = 2 + SLACK = 3 + + one_box_type: "SearchResponse.OneBoxResult.OneBoxType" = proto.Field( + proto.ENUM, + number=1, + enum="SearchResponse.OneBoxResult.OneBoxType", + ) + search_results: MutableSequence[ + "SearchResponse.SearchResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SearchResponse.SearchResult", + ) + @property def raw_page(self): return self @@ -1871,6 +2529,23 @@ def raw_page(self): number=14, message=QueryExpansionInfo, ) + natural_language_query_understanding_info: NaturalLanguageQueryUnderstandingInfo = ( + proto.Field( + proto.MESSAGE, + number=15, + message=NaturalLanguageQueryUnderstandingInfo, + ) + ) + session_info: SessionInfo = proto.Field( + proto.MESSAGE, + number=19, + message=SessionInfo, + ) + one_box_results: MutableSequence[OneBoxResult] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=OneBoxResult, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/serving_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/serving_config.py index a0801be911e2..788d25be739e 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/serving_config.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/serving_config.py @@ -119,23 +119,33 @@ class ServingConfig(proto.Message): functions that are joined by "+". - ranking_expression = function, { " + ", function }; - Supported functions: + + Supported functions: + - double \* relevance_score - - double \* dotProduct(embedding_field_path) Function - variables: relevance_score: pre-defined keywords, used - for measure relevance between query and document. - embedding_field_path: the document embedding field used - with query embedding vector. dotProduct: embedding - function between embedding_field_path and query embedding - vector. - - Example ranking expression: If document has an embedding - field doc_embedding, the ranking expression could be 0.5 \* - relevance_score + 0.3 \* dotProduct(doc_embedding). + - double \* dotProduct(embedding_field_path) + + Function variables: + + - ``relevance_score``: pre-defined keywords, used for + measure relevance between query and document. + - ``embedding_field_path``: the document embedding field + used with query embedding vector. + - ``dotProduct``: embedding function between + embedding_field_path and query embedding vector. + + Example ranking expression: + + :: + + If document has an embedding field doc_embedding, the ranking expression + could be `0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)`. guided_search_spec (google.cloud.discoveryengine_v1alpha.types.GuidedSearchSpec): Guided search configs. custom_fine_tuning_spec (google.cloud.discoveryengine_v1alpha.types.CustomFineTuningSpec): - Custom fine tuning configs. + Custom fine tuning configs. If + [SearchRequest.custom_fine_tuning_spec][google.cloud.discoveryengine.v1alpha.SearchRequest.custom_fine_tuning_spec] + is set, it has higher priority than the configs set here. create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. ServingConfig created timestamp. update_time (google.protobuf.timestamp_pb2.Timestamp): diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py index 59b5a7b45592..dfa19d378dca 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore @@ -54,6 +55,11 @@ "BatchVerifyTargetSitesMetadata", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", + "SetUriPatternDocumentDataRequest", + "SetUriPatternDocumentDataResponse", + "SetUriPatternDocumentDataMetadata", + "GetUriPatternDocumentDataRequest", + "GetUriPatternDocumentDataResponse", }, ) @@ -848,4 +854,135 @@ def raw_page(self): ) +class SetUriPatternDocumentDataRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + + Attributes: + site_search_engine (str): + Required. Full resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1alpha.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + document_data_map (MutableMapping[str, google.protobuf.struct_pb2.Struct]): + Document data keyed by URI pattern. Each entry must be + consistent with the + [Schema][google.cloud.discoveryengine.v1alpha.Schema]. For + example: + [Schema][google.cloud.discoveryengine.v1alpha.Schema] = { + "type": "object", "properties": { "Categories": { "type": + "array", "items": { "retrievable": true, "type": "string" } + } } + + document_data_map = { "www.url1.com/*": { "Categories": + ["category1", "category2"] }, "www.url2.com/*": { + "Categories": ["category3"] } } + empty_document_data_map (bool): + If true, clears the document data map. If true, + [SetUriPatternDocumentDataRequest.document_data_map][google.cloud.discoveryengine.v1alpha.SetUriPatternDocumentDataRequest.document_data_map] + must be empty. + schema (google.protobuf.struct_pb2.Struct): + Optional. If not provided, the current + [Schema][google.cloud.discoveryengine.v1alpha.Schema] is + used. If provided, validates and updates the + [Schema][google.cloud.discoveryengine.v1alpha.Schema]. If + validation fails, an error is returned. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + document_data_map: MutableMapping[str, struct_pb2.Struct] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + empty_document_data_map: bool = proto.Field( + proto.BOOL, + number=4, + ) + schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class SetUriPatternDocumentDataResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + method. + + """ + + +class SetUriPatternDocumentDataMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.SetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GetUriPatternDocumentDataRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + + Attributes: + site_search_engine (str): + Required. Full resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1alpha.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetUriPatternDocumentDataResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.GetUriPatternDocumentData][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData] + method. + + Attributes: + document_data_map (MutableMapping[str, google.protobuf.struct_pb2.Struct]): + Document data keyed by URI pattern. For example: + document_data_map = { "www.url1.com/*": { "Categories": + ["category1", "category2"] }, "www.url2.com/*": { + "Categories": ["category3"] } } + """ + + document_data_map: MutableMapping[str, struct_pb2.Struct] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py index 795c02b02eaa..558c8aab67c5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.12.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_async.py new file mode 100644 index 000000000000..ab1bc52e25f8 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionSuggestions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_CompletionService_ImportCompletionSuggestions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_import_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.suggestions.global_score = 0.126 + inline_source.suggestions.suggestion = "suggestion_value" + + request = discoveryengine_v1alpha.ImportCompletionSuggestionsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_CompletionService_ImportCompletionSuggestions_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_sync.py new file mode 100644 index 000000000000..e058a0270ac2 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCompletionSuggestions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_CompletionService_ImportCompletionSuggestions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_import_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.suggestions.global_score = 0.126 + inline_source.suggestions.suggestion = "suggestion_value" + + request = discoveryengine_v1alpha.ImportCompletionSuggestionsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_CompletionService_ImportCompletionSuggestions_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_async.py new file mode 100644 index 000000000000..762f7bdc2a29 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeCompletionSuggestions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_CompletionService_PurgeCompletionSuggestions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_purge_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeCompletionSuggestionsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.purge_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_CompletionService_PurgeCompletionSuggestions_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_sync.py new file mode 100644 index 000000000000..eb7b8c6440f8 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeCompletionSuggestions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_CompletionService_PurgeCompletionSuggestions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_purge_completion_suggestions(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeCompletionSuggestionsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.purge_completion_suggestions(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_CompletionService_PurgeCompletionSuggestions_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_async.py new file mode 100644 index 000000000000..9a5cff3696a0 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUriPatternDocumentData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_GetUriPatternDocumentData_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_get_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + response = await client.get_uri_pattern_document_data(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_GetUriPatternDocumentData_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_sync.py new file mode 100644 index 000000000000..41a518593d73 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUriPatternDocumentData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_GetUriPatternDocumentData_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_get_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + response = client.get_uri_pattern_document_data(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_GetUriPatternDocumentData_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_async.py new file mode 100644 index 000000000000..1590ef8b5484 --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetUriPatternDocumentData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_SetUriPatternDocumentData_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_set_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.set_uri_pattern_document_data(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_SetUriPatternDocumentData_async] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_sync.py new file mode 100644 index 000000000000..620e32727b9b --- /dev/null +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetUriPatternDocumentData +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_SetUriPatternDocumentData_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_set_uri_pattern_document_data(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Make the request + operation = client.set_uri_pattern_document_data(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_SetUriPatternDocumentData_sync] diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json index d5f823d00e2e..69944fc7ce8a 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.12.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json index 3e530a811ce1..2884e903e0cf 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.12.0" + "version": "0.1.0" }, "snippets": [ { @@ -800,6 +800,159 @@ ], "title": "discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient.import_completion_suggestions", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionSuggestions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_completion_suggestions" + }, + "description": "Sample for ImportCompletionSuggestions", + "file": "discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_CompletionService_ImportCompletionSuggestions_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient.import_completion_suggestions", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.ImportCompletionSuggestions", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "ImportCompletionSuggestions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportCompletionSuggestionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_completion_suggestions" + }, + "description": "Sample for ImportCompletionSuggestions", + "file": "discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_CompletionService_ImportCompletionSuggestions_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_completion_service_import_completion_suggestions_sync.py" + }, { "canonical": true, "clientMethod": { @@ -953,6 +1106,159 @@ ], "title": "discoveryengine_v1alpha_generated_completion_service_import_suggestion_deny_list_entries_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient.purge_completion_suggestions", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "PurgeCompletionSuggestions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeCompletionSuggestionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_completion_suggestions" + }, + "description": "Sample for PurgeCompletionSuggestions", + "file": "discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_CompletionService_PurgeCompletionSuggestions_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient.purge_completion_suggestions", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.PurgeCompletionSuggestions", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "PurgeCompletionSuggestions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeCompletionSuggestionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_completion_suggestions" + }, + "description": "Sample for PurgeCompletionSuggestions", + "file": "discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_CompletionService_PurgeCompletionSuggestions_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_completion_service_purge_completion_suggestions_sync.py" + }, { "canonical": true, "clientMethod": { @@ -14097,8 +14403,165 @@ }, "parameters": [ { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.FetchDomainVerificationStatusRequest" + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.FetchDomainVerificationStatusRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.pagers.FetchDomainVerificationStatusAsyncPager", + "shortName": "fetch_domain_verification_status" + }, + "description": "Sample for FetchDomainVerificationStatus", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_FetchDomainVerificationStatus_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", + "shortName": "SiteSearchEngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.fetch_domain_verification_status", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.FetchDomainVerificationStatus", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "FetchDomainVerificationStatus" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.FetchDomainVerificationStatusRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.pagers.FetchDomainVerificationStatusPager", + "shortName": "fetch_domain_verification_status" + }, + "description": "Sample for FetchDomainVerificationStatus", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_FetchDomainVerificationStatus_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient", + "shortName": "SiteSearchEngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.get_site_search_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetSiteSearchEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "GetSiteSearchEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetSiteSearchEngineRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -14113,22 +14576,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.pagers.FetchDomainVerificationStatusAsyncPager", - "shortName": "fetch_domain_verification_status" + "resultType": "google.cloud.discoveryengine_v1alpha.types.SiteSearchEngine", + "shortName": "get_site_search_engine" }, - "description": "Sample for FetchDomainVerificationStatus", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_async.py", + "description": "Sample for GetSiteSearchEngine", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_FetchDomainVerificationStatus_async", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetSiteSearchEngine_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14148,12 +14611,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_async.py" + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_async.py" }, { "canonical": true, @@ -14162,19 +14625,23 @@ "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.fetch_domain_verification_status", + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.get_site_search_engine", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.FetchDomainVerificationStatus", + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetSiteSearchEngine", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "FetchDomainVerificationStatus" + "shortName": "GetSiteSearchEngine" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.FetchDomainVerificationStatusRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetSiteSearchEngineRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -14189,22 +14656,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.pagers.FetchDomainVerificationStatusPager", - "shortName": "fetch_domain_verification_status" + "resultType": "google.cloud.discoveryengine_v1alpha.types.SiteSearchEngine", + "shortName": "get_site_search_engine" }, - "description": "Sample for FetchDomainVerificationStatus", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_sync.py", + "description": "Sample for GetSiteSearchEngine", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_FetchDomainVerificationStatus_sync", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetSiteSearchEngine_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14224,12 +14691,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_site_search_engine_service_fetch_domain_verification_status_sync.py" + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_sync.py" }, { "canonical": true, @@ -14239,19 +14706,19 @@ "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient", "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.get_site_search_engine", + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.get_target_site", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetSiteSearchEngine", + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetTargetSite", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "GetSiteSearchEngine" + "shortName": "GetTargetSite" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetSiteSearchEngineRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetTargetSiteRequest" }, { "name": "name", @@ -14270,14 +14737,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.SiteSearchEngine", - "shortName": "get_site_search_engine" + "resultType": "google.cloud.discoveryengine_v1alpha.types.TargetSite", + "shortName": "get_target_site" }, - "description": "Sample for GetSiteSearchEngine", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_async.py", + "description": "Sample for GetTargetSite", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetSiteSearchEngine_async", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetTargetSite_async", "segments": [ { "end": 51, @@ -14310,7 +14777,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_async.py" + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_async.py" }, { "canonical": true, @@ -14319,19 +14786,19 @@ "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.get_site_search_engine", + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.get_target_site", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetSiteSearchEngine", + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetTargetSite", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "GetSiteSearchEngine" + "shortName": "GetTargetSite" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetSiteSearchEngineRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetTargetSiteRequest" }, { "name": "name", @@ -14350,14 +14817,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.SiteSearchEngine", - "shortName": "get_site_search_engine" + "resultType": "google.cloud.discoveryengine_v1alpha.types.TargetSite", + "shortName": "get_target_site" }, - "description": "Sample for GetSiteSearchEngine", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_sync.py", + "description": "Sample for GetTargetSite", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetSiteSearchEngine_sync", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetTargetSite_sync", "segments": [ { "end": 51, @@ -14390,7 +14857,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_site_search_engine_sync.py" + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_sync.py" }, { "canonical": true, @@ -14400,23 +14867,19 @@ "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient", "shortName": "SiteSearchEngineServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.get_target_site", + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.get_uri_pattern_document_data", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetTargetSite", + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "GetTargetSite" + "shortName": "GetUriPatternDocumentData" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetTargetSiteRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataRequest" }, { "name": "retry", @@ -14431,14 +14894,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.TargetSite", - "shortName": "get_target_site" + "resultType": "google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataResponse", + "shortName": "get_uri_pattern_document_data" }, - "description": "Sample for GetTargetSite", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_async.py", + "description": "Sample for GetUriPatternDocumentData", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetTargetSite_async", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetUriPatternDocumentData_async", "segments": [ { "end": 51, @@ -14471,7 +14934,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_async.py" + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_async.py" }, { "canonical": true, @@ -14480,23 +14943,19 @@ "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", "shortName": "SiteSearchEngineServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.get_target_site", + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.get_uri_pattern_document_data", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetTargetSite", + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.GetUriPatternDocumentData", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", "shortName": "SiteSearchEngineService" }, - "shortName": "GetTargetSite" + "shortName": "GetUriPatternDocumentData" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetTargetSiteRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataRequest" }, { "name": "retry", @@ -14511,14 +14970,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.TargetSite", - "shortName": "get_target_site" + "resultType": "google.cloud.discoveryengine_v1alpha.types.GetUriPatternDocumentDataResponse", + "shortName": "get_uri_pattern_document_data" }, - "description": "Sample for GetTargetSite", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_sync.py", + "description": "Sample for GetUriPatternDocumentData", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetTargetSite_sync", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_GetUriPatternDocumentData_sync", "segments": [ { "end": 51, @@ -14551,7 +15010,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_target_site_sync.py" + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_get_uri_pattern_document_data_sync.py" }, { "canonical": true, @@ -14867,6 +15326,159 @@ ], "title": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient", + "shortName": "SiteSearchEngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.set_uri_pattern_document_data", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "SetUriPatternDocumentData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.SetUriPatternDocumentDataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "set_uri_pattern_document_data" + }, + "description": "Sample for SetUriPatternDocumentData", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_SetUriPatternDocumentData_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", + "shortName": "SiteSearchEngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.set_uri_pattern_document_data", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.SetUriPatternDocumentData", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "SetUriPatternDocumentData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.SetUriPatternDocumentDataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "set_uri_pattern_document_data" + }, + "description": "Sample for SetUriPatternDocumentData", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_SetUriPatternDocumentData_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_site_search_engine_service_set_uri_pattern_document_data_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json index b979fed13038..cff39c47dc30 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-discoveryengine", - "version": "0.12.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py index d5a01a5ceefe..e10372b3b1fa 100644 --- a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py +++ b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py @@ -39,7 +39,7 @@ def partition( class discoveryengineCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'answer_query': ('serving_config', 'query', 'session', 'safety_spec', 'related_questions_spec', 'answer_generation_spec', 'search_spec', 'query_understanding_spec', 'asynchronous_mode', 'user_pseudo_id', ), + 'answer_query': ('serving_config', 'query', 'session', 'safety_spec', 'related_questions_spec', 'answer_generation_spec', 'search_spec', 'query_understanding_spec', 'asynchronous_mode', 'user_pseudo_id', 'user_labels', ), 'batch_create_target_sites': ('parent', 'requests', ), 'batch_verify_target_sites': ('parent', ), 'check_grounding': ('grounding_config', 'answer_candidate', 'facts', 'grounding_spec', 'user_labels', ), @@ -48,7 +48,7 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', 'filter', 'boost_spec', ), 'create_control': ('parent', 'control', 'control_id', ), 'create_conversation': ('parent', 'conversation', ), - 'create_data_store': ('parent', 'data_store', 'data_store_id', 'create_advanced_site_search', ), + 'create_data_store': ('parent', 'data_store', 'data_store_id', 'create_advanced_site_search', 'skip_default_schema_creation', ), 'create_document': ('parent', 'document', 'document_id', ), 'create_engine': ('parent', 'engine', 'engine_id', ), 'create_evaluation': ('parent', 'evaluation', ), @@ -90,7 +90,9 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'get_session': ('name', ), 'get_site_search_engine': ('name', ), 'get_target_site': ('name', ), - 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'fhir_store_source', 'spanner_source', 'cloud_sql_source', 'firestore_source', 'bigtable_source', 'error_config', 'reconciliation_mode', 'update_mask', 'auto_generate_ids', 'id_field', ), + 'get_uri_pattern_document_data': ('site_search_engine', ), + 'import_completion_suggestions': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), + 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'fhir_store_source', 'spanner_source', 'cloud_sql_source', 'firestore_source', 'alloy_db_source', 'bigtable_source', 'error_config', 'reconciliation_mode', 'update_mask', 'auto_generate_ids', 'id_field', ), 'import_sample_queries': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), 'import_suggestion_deny_list_entries': ('parent', 'inline_source', 'gcs_source', ), 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), @@ -111,7 +113,8 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'list_target_sites': ('parent', 'page_size', 'page_token', ), 'pause_engine': ('name', ), 'provision_project': ('name', 'accept_data_use_terms', 'data_use_terms_version', ), - 'purge_documents': ('parent', 'filter', 'gcs_source', 'error_config', 'force', ), + 'purge_completion_suggestions': ('parent', ), + 'purge_documents': ('parent', 'filter', 'gcs_source', 'inline_source', 'error_config', 'force', ), 'purge_suggestion_deny_list_entries': ('parent', ), 'purge_user_events': ('parent', 'filter', 'force', ), 'rank': ('ranking_config', 'records', 'model', 'top_n', 'query', 'ignore_record_details_in_response', 'user_labels', ), @@ -119,7 +122,8 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'recrawl_uris': ('site_search_engine', 'uris', ), 'report_consent_change': ('consent_change_action', 'project', 'service_term_id', 'service_term_version', ), 'resume_engine': ('name', ), - 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'data_store_specs', 'filter', 'canonical_filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', 'custom_fine_tuning_spec', ), + 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'data_store_specs', 'filter', 'canonical_filter', 'order_by', 'user_info', 'language_code', 'region_code', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', 'natural_language_query_understanding_spec', 'search_as_you_type_spec', 'custom_fine_tuning_spec', 'session', 'session_spec', 'relevance_threshold', ), + 'set_uri_pattern_document_data': ('site_search_engine', 'document_data_map', 'empty_document_data_map', 'schema', ), 'train_custom_model': ('data_store', 'gcs_training_input', 'model_type', 'error_config', 'model_id', ), 'tune_engine': ('name', ), 'update_acl_config': ('acl_config', ), diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py index 78d3ac9b42c6..9834caeffcaa 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py @@ -46,6 +46,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import json_format +from google.type import date_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers @@ -2063,6 +2064,610 @@ async def test_purge_suggestion_deny_list_entries_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportCompletionSuggestionsRequest, + dict, + ], +) +def test_import_completion_suggestions(request_type, transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = import_config.ImportCompletionSuggestionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_completion_suggestions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_completion_suggestions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionSuggestionsRequest() + + +def test_import_completion_suggestions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = import_config.ImportCompletionSuggestionsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_completion_suggestions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionSuggestionsRequest( + parent="parent_value", + ) + + +def test_import_completion_suggestions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_completion_suggestions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_completion_suggestions + ] = mock_rpc + request = {} + client.import_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_completion_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_completion_suggestions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.import_completion_suggestions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportCompletionSuggestionsRequest() + + +@pytest.mark.asyncio +async def test_import_completion_suggestions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.import_completion_suggestions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.import_completion_suggestions + ] = mock_object + + request = {} + await client.import_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_completion_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_completion_suggestions_async( + transport: str = "grpc_asyncio", + request_type=import_config.ImportCompletionSuggestionsRequest, +): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.import_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = import_config.ImportCompletionSuggestionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_completion_suggestions_async_from_dict(): + await test_import_completion_suggestions_async(request_type=dict) + + +def test_import_completion_suggestions_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionSuggestionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_completion_suggestions_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportCompletionSuggestionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_completion_suggestions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeCompletionSuggestionsRequest, + dict, + ], +) +def test_purge_completion_suggestions(request_type, transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.purge_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = purge_config.PurgeCompletionSuggestionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_completion_suggestions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.purge_completion_suggestions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeCompletionSuggestionsRequest() + + +def test_purge_completion_suggestions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = purge_config.PurgeCompletionSuggestionsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.purge_completion_suggestions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeCompletionSuggestionsRequest( + parent="parent_value", + ) + + +def test_purge_completion_suggestions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.purge_completion_suggestions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.purge_completion_suggestions + ] = mock_rpc + request = {} + client.purge_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.purge_completion_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_purge_completion_suggestions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.purge_completion_suggestions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeCompletionSuggestionsRequest() + + +@pytest.mark.asyncio +async def test_purge_completion_suggestions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.purge_completion_suggestions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.purge_completion_suggestions + ] = mock_object + + request = {} + await client.purge_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.purge_completion_suggestions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_purge_completion_suggestions_async( + transport: str = "grpc_asyncio", + request_type=purge_config.PurgeCompletionSuggestionsRequest, +): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.purge_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = purge_config.PurgeCompletionSuggestionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_completion_suggestions_async_from_dict(): + await test_purge_completion_suggestions_async(request_type=dict) + + +def test_purge_completion_suggestions_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeCompletionSuggestionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.purge_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_purge_completion_suggestions_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeCompletionSuggestionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_completion_suggestions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.purge_completion_suggestions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + @pytest.mark.parametrize( "request_type", [ @@ -2070,7 +2675,553 @@ async def test_purge_suggestion_deny_list_entries_field_headers_async(): dict, ], ) -def test_complete_query_rest(request_type): +def test_complete_query_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "data_store": "projects/sample1/locations/sample2/dataStores/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.complete_query in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.complete_query] = mock_rpc + + request = {} + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.complete_query(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_complete_query_rest_required_fields( + request_type=completion_service.CompleteQueryRequest, +): + transport_class = transports.CompletionServiceRestTransport + + request_init = {} + request_init["data_store"] = "" + request_init["query"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "query" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).complete_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "query" in jsonified_request + assert jsonified_request["query"] == request_init["query"] + + jsonified_request["dataStore"] = "data_store_value" + jsonified_request["query"] = "query_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).complete_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "include_tail_suggestions", + "query", + "query_model", + "user_pseudo_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "dataStore" in jsonified_request + assert jsonified_request["dataStore"] == "data_store_value" + assert "query" in jsonified_request + assert jsonified_request["query"] == "query_value" + + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = completion_service.CompleteQueryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.complete_query(request) + + expected_params = [ + ( + "query", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_complete_query_rest_unset_required_fields(): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.complete_query._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "includeTailSuggestions", + "query", + "queryModel", + "userPseudoId", + ) + ) + & set( + ( + "dataStore", + "query", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CompletionServiceRestInterceptor, "post_complete_query" + ) as post, mock.patch.object( + transports.CompletionServiceRestInterceptor, "pre_complete_query" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb( + completion_service.CompleteQueryRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = completion_service.CompleteQueryResponse.to_json( + completion_service.CompleteQueryResponse() + ) + + request = completion_service.CompleteQueryRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_complete_query_rest_bad_request( + transport: str = "rest", request_type=completion_service.CompleteQueryRequest +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "data_store": "projects/sample1/locations/sample2/dataStores/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.complete_query(request) + + +def test_complete_query_rest_error(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + import_config.ImportSuggestionDenyListEntriesRequest, + dict, + ], +) +def test_import_suggestion_deny_list_entries_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.import_suggestion_deny_list_entries(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_suggestion_deny_list_entries + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.import_suggestion_deny_list_entries + ] = mock_rpc + + request = {} + client.import_suggestion_deny_list_entries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_suggestion_deny_list_entries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_suggestion_deny_list_entries_rest_required_fields( + request_type=import_config.ImportSuggestionDenyListEntriesRequest, +): + transport_class = transports.CompletionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.import_suggestion_deny_list_entries(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_suggestion_deny_list_entries_rest_unset_required_fields(): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.import_suggestion_deny_list_entries._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_suggestion_deny_list_entries_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CompletionServiceRestInterceptor, + "post_import_suggestion_deny_list_entries", + ) as post, mock.patch.object( + transports.CompletionServiceRestInterceptor, + "pre_import_suggestion_deny_list_entries", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportSuggestionDenyListEntriesRequest.pb( + import_config.ImportSuggestionDenyListEntriesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = import_config.ImportSuggestionDenyListEntriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_suggestion_deny_list_entries( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_suggestion_deny_list_entries_rest_bad_request( + transport: str = "rest", + request_type=import_config.ImportSuggestionDenyListEntriesRequest, +): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_suggestion_deny_list_entries(request) + + +def test_import_suggestion_deny_list_entries_rest_error(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + purge_config.PurgeSuggestionDenyListEntriesRequest, + dict, + ], +) +def test_purge_suggestion_deny_list_entries_rest(request_type): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2078,34 +3229,29 @@ def test_complete_query_rest(request_type): # send a request that will satisfy transcoding request_init = { - "data_store": "projects/sample1/locations/sample2/dataStores/sample3" + "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.complete_query(request) + response = client.purge_suggestion_deny_list_entries(request) # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True + assert response.operation.name == "operations/spam" -def test_complete_query_rest_use_cached_wrapped_rpc(): +def test_purge_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -2119,36 +3265,44 @@ def test_complete_query_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.complete_query in client._transport._wrapped_methods + assert ( + client._transport.purge_suggestion_deny_list_entries + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.complete_query] = mock_rpc + client._transport._wrapped_methods[ + client._transport.purge_suggestion_deny_list_entries + ] = mock_rpc request = {} - client.complete_query(request) + client.purge_suggestion_deny_list_entries(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.complete_query(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.purge_suggestion_deny_list_entries(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_complete_query_rest_required_fields( - request_type=completion_service.CompleteQueryRequest, +def test_purge_suggestion_deny_list_entries_rest_required_fields( + request_type=purge_config.PurgeSuggestionDenyListEntriesRequest, ): transport_class = transports.CompletionServiceRestTransport request_init = {} - request_init["data_store"] = "" - request_init["query"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -2156,39 +3310,24 @@ def test_complete_query_rest_required_fields( ) # verify fields with default values are dropped - assert "query" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_query._get_unset_required_fields(jsonified_request) + ).purge_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "query" in jsonified_request - assert jsonified_request["query"] == request_init["query"] - jsonified_request["dataStore"] = "data_store_value" - jsonified_request["query"] = "query_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).complete_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "include_tail_suggestions", - "query", - "query_model", - "user_pseudo_id", - ) - ) + ).purge_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "dataStore" in jsonified_request - assert jsonified_request["dataStore"] == "data_store_value" - assert "query" in jsonified_request - assert jsonified_request["query"] == "query_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2197,7 +3336,7 @@ def test_complete_query_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = completion_service.CompleteQueryResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -2209,60 +3348,39 @@ def test_complete_query_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.complete_query(request) + response = client.purge_suggestion_deny_list_entries(request) - expected_params = [ - ( - "query", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_complete_query_rest_unset_required_fields(): +def test_purge_suggestion_deny_list_entries_rest_unset_required_fields(): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.complete_query._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "includeTailSuggestions", - "query", - "queryModel", - "userPseudoId", - ) - ) - & set( - ( - "dataStore", - "query", - ) - ) + unset_fields = ( + transport.purge_suggestion_deny_list_entries._get_unset_required_fields({}) ) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): +def test_purge_suggestion_deny_list_entries_rest_interceptors(null_interceptor): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2275,14 +3393,18 @@ def test_complete_query_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.CompletionServiceRestInterceptor, "post_complete_query" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.CompletionServiceRestInterceptor, + "post_purge_suggestion_deny_list_entries", ) as post, mock.patch.object( - transports.CompletionServiceRestInterceptor, "pre_complete_query" + transports.CompletionServiceRestInterceptor, + "pre_purge_suggestion_deny_list_entries", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb( - completion_service.CompleteQueryRequest() + pb_message = purge_config.PurgeSuggestionDenyListEntriesRequest.pb( + purge_config.PurgeSuggestionDenyListEntriesRequest() ) transcode.return_value = { "method": "post", @@ -2294,19 +3416,19 @@ def test_complete_query_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = completion_service.CompleteQueryResponse.to_json( - completion_service.CompleteQueryResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = completion_service.CompleteQueryRequest() + request = purge_config.PurgeSuggestionDenyListEntriesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() + post.return_value = operations_pb2.Operation() - client.complete_query( + client.purge_suggestion_deny_list_entries( request, metadata=[ ("key", "val"), @@ -2318,8 +3440,9 @@ def test_complete_query_rest_interceptors(null_interceptor): post.assert_called_once() -def test_complete_query_rest_bad_request( - transport: str = "rest", request_type=completion_service.CompleteQueryRequest +def test_purge_suggestion_deny_list_entries_rest_bad_request( + transport: str = "rest", + request_type=purge_config.PurgeSuggestionDenyListEntriesRequest, ): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2328,7 +3451,7 @@ def test_complete_query_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "data_store": "projects/sample1/locations/sample2/dataStores/sample3" + "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4" } request = request_type(**request_init) @@ -2341,10 +3464,10 @@ def test_complete_query_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.complete_query(request) + client.purge_suggestion_deny_list_entries(request) -def test_complete_query_rest_error(): +def test_purge_suggestion_deny_list_entries_rest_error(): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2353,11 +3476,11 @@ def test_complete_query_rest_error(): @pytest.mark.parametrize( "request_type", [ - import_config.ImportSuggestionDenyListEntriesRequest, + import_config.ImportCompletionSuggestionsRequest, dict, ], ) -def test_import_suggestion_deny_list_entries_rest(request_type): +def test_import_completion_suggestions_rest(request_type): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2381,13 +3504,13 @@ def test_import_suggestion_deny_list_entries_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.import_suggestion_deny_list_entries(request) + response = client.import_completion_suggestions(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_import_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): +def test_import_completion_suggestions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -2402,7 +3525,7 @@ def test_import_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.import_suggestion_deny_list_entries + client._transport.import_completion_suggestions in client._transport._wrapped_methods ) @@ -2412,11 +3535,11 @@ def test_import_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.import_suggestion_deny_list_entries + client._transport.import_completion_suggestions ] = mock_rpc request = {} - client.import_suggestion_deny_list_entries(request) + client.import_completion_suggestions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2425,15 +3548,15 @@ def test_import_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.import_suggestion_deny_list_entries(request) + client.import_completion_suggestions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_import_suggestion_deny_list_entries_rest_required_fields( - request_type=import_config.ImportSuggestionDenyListEntriesRequest, +def test_import_completion_suggestions_rest_required_fields( + request_type=import_config.ImportCompletionSuggestionsRequest, ): transport_class = transports.CompletionServiceRestTransport @@ -2449,7 +3572,7 @@ def test_import_suggestion_deny_list_entries_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) + ).import_completion_suggestions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -2458,7 +3581,7 @@ def test_import_suggestion_deny_list_entries_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) + ).import_completion_suggestions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2497,26 +3620,26 @@ def test_import_suggestion_deny_list_entries_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.import_suggestion_deny_list_entries(request) + response = client.import_completion_suggestions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_import_suggestion_deny_list_entries_rest_unset_required_fields(): +def test_import_completion_suggestions_rest_unset_required_fields(): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.import_suggestion_deny_list_entries._get_unset_required_fields({}) + unset_fields = transport.import_completion_suggestions._get_unset_required_fields( + {} ) assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_suggestion_deny_list_entries_rest_interceptors(null_interceptor): +def test_import_completion_suggestions_rest_interceptors(null_interceptor): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2532,15 +3655,14 @@ def test_import_suggestion_deny_list_entries_rest_interceptors(null_interceptor) operation.Operation, "_set_result_from_operation" ), mock.patch.object( transports.CompletionServiceRestInterceptor, - "post_import_suggestion_deny_list_entries", + "post_import_completion_suggestions", ) as post, mock.patch.object( - transports.CompletionServiceRestInterceptor, - "pre_import_suggestion_deny_list_entries", + transports.CompletionServiceRestInterceptor, "pre_import_completion_suggestions" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = import_config.ImportSuggestionDenyListEntriesRequest.pb( - import_config.ImportSuggestionDenyListEntriesRequest() + pb_message = import_config.ImportCompletionSuggestionsRequest.pb( + import_config.ImportCompletionSuggestionsRequest() ) transcode.return_value = { "method": "post", @@ -2556,7 +3678,7 @@ def test_import_suggestion_deny_list_entries_rest_interceptors(null_interceptor) operations_pb2.Operation() ) - request = import_config.ImportSuggestionDenyListEntriesRequest() + request = import_config.ImportCompletionSuggestionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2564,7 +3686,7 @@ def test_import_suggestion_deny_list_entries_rest_interceptors(null_interceptor) pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.import_suggestion_deny_list_entries( + client.import_completion_suggestions( request, metadata=[ ("key", "val"), @@ -2576,9 +3698,9 @@ def test_import_suggestion_deny_list_entries_rest_interceptors(null_interceptor) post.assert_called_once() -def test_import_suggestion_deny_list_entries_rest_bad_request( +def test_import_completion_suggestions_rest_bad_request( transport: str = "rest", - request_type=import_config.ImportSuggestionDenyListEntriesRequest, + request_type=import_config.ImportCompletionSuggestionsRequest, ): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2600,10 +3722,10 @@ def test_import_suggestion_deny_list_entries_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.import_suggestion_deny_list_entries(request) + client.import_completion_suggestions(request) -def test_import_suggestion_deny_list_entries_rest_error(): +def test_import_completion_suggestions_rest_error(): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2612,11 +3734,11 @@ def test_import_suggestion_deny_list_entries_rest_error(): @pytest.mark.parametrize( "request_type", [ - purge_config.PurgeSuggestionDenyListEntriesRequest, + purge_config.PurgeCompletionSuggestionsRequest, dict, ], ) -def test_purge_suggestion_deny_list_entries_rest(request_type): +def test_purge_completion_suggestions_rest(request_type): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2640,13 +3762,13 @@ def test_purge_suggestion_deny_list_entries_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.purge_suggestion_deny_list_entries(request) + response = client.purge_completion_suggestions(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_purge_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): +def test_purge_completion_suggestions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -2661,7 +3783,7 @@ def test_purge_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.purge_suggestion_deny_list_entries + client._transport.purge_completion_suggestions in client._transport._wrapped_methods ) @@ -2671,11 +3793,11 @@ def test_purge_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.purge_suggestion_deny_list_entries + client._transport.purge_completion_suggestions ] = mock_rpc request = {} - client.purge_suggestion_deny_list_entries(request) + client.purge_completion_suggestions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2684,15 +3806,15 @@ def test_purge_suggestion_deny_list_entries_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.purge_suggestion_deny_list_entries(request) + client.purge_completion_suggestions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_purge_suggestion_deny_list_entries_rest_required_fields( - request_type=purge_config.PurgeSuggestionDenyListEntriesRequest, +def test_purge_completion_suggestions_rest_required_fields( + request_type=purge_config.PurgeCompletionSuggestionsRequest, ): transport_class = transports.CompletionServiceRestTransport @@ -2708,7 +3830,7 @@ def test_purge_suggestion_deny_list_entries_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).purge_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) + ).purge_completion_suggestions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -2717,7 +3839,7 @@ def test_purge_suggestion_deny_list_entries_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).purge_suggestion_deny_list_entries._get_unset_required_fields(jsonified_request) + ).purge_completion_suggestions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2756,26 +3878,24 @@ def test_purge_suggestion_deny_list_entries_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.purge_suggestion_deny_list_entries(request) + response = client.purge_completion_suggestions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_purge_suggestion_deny_list_entries_rest_unset_required_fields(): +def test_purge_completion_suggestions_rest_unset_required_fields(): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.purge_suggestion_deny_list_entries._get_unset_required_fields({}) - ) + unset_fields = transport.purge_completion_suggestions._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_suggestion_deny_list_entries_rest_interceptors(null_interceptor): +def test_purge_completion_suggestions_rest_interceptors(null_interceptor): transport = transports.CompletionServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2790,16 +3910,14 @@ def test_purge_suggestion_deny_list_entries_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.CompletionServiceRestInterceptor, - "post_purge_suggestion_deny_list_entries", + transports.CompletionServiceRestInterceptor, "post_purge_completion_suggestions" ) as post, mock.patch.object( - transports.CompletionServiceRestInterceptor, - "pre_purge_suggestion_deny_list_entries", + transports.CompletionServiceRestInterceptor, "pre_purge_completion_suggestions" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = purge_config.PurgeSuggestionDenyListEntriesRequest.pb( - purge_config.PurgeSuggestionDenyListEntriesRequest() + pb_message = purge_config.PurgeCompletionSuggestionsRequest.pb( + purge_config.PurgeCompletionSuggestionsRequest() ) transcode.return_value = { "method": "post", @@ -2815,7 +3933,7 @@ def test_purge_suggestion_deny_list_entries_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = purge_config.PurgeSuggestionDenyListEntriesRequest() + request = purge_config.PurgeCompletionSuggestionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2823,7 +3941,7 @@ def test_purge_suggestion_deny_list_entries_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.purge_suggestion_deny_list_entries( + client.purge_completion_suggestions( request, metadata=[ ("key", "val"), @@ -2835,9 +3953,8 @@ def test_purge_suggestion_deny_list_entries_rest_interceptors(null_interceptor): post.assert_called_once() -def test_purge_suggestion_deny_list_entries_rest_bad_request( - transport: str = "rest", - request_type=purge_config.PurgeSuggestionDenyListEntriesRequest, +def test_purge_completion_suggestions_rest_bad_request( + transport: str = "rest", request_type=purge_config.PurgeCompletionSuggestionsRequest ): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2859,10 +3976,10 @@ def test_purge_suggestion_deny_list_entries_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.purge_suggestion_deny_list_entries(request) + client.purge_completion_suggestions(request) -def test_purge_suggestion_deny_list_entries_rest_error(): +def test_purge_completion_suggestions_rest_error(): client = CompletionServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3010,6 +4127,8 @@ def test_completion_service_base_transport(): "complete_query", "import_suggestion_deny_list_entries", "purge_suggestion_deny_list_entries", + "import_completion_suggestions", + "purge_completion_suggestions", "get_operation", "cancel_operation", "list_operations", @@ -3302,6 +4421,12 @@ def test_completion_service_client_transport_session_collision(transport_name): session1 = client1.transport.purge_suggestion_deny_list_entries._session session2 = client2.transport.purge_suggestion_deny_list_entries._session assert session1 != session2 + session1 = client1.transport.import_completion_suggestions._session + session2 = client2.transport.import_completion_suggestions._session + assert session1 != session2 + session1 = client1.transport.purge_completion_suggestions._session + session2 = client2.transport.purge_completion_suggestions._session + assert session1 != session2 def test_completion_service_grpc_transport_channel(): diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py index 87d953c3f426..98578bb499d0 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py @@ -4159,6 +4159,12 @@ def test_create_data_store_rest(request_type): "default_schema_id": "default_schema_id_value", "content_config": 1, "create_time": {"seconds": 751, "nanos": 543}, + "language_info": { + "language_code": "language_code_value", + "normalized_language_code": "normalized_language_code_value", + "language": "language_value", + "region": "region_value", + }, "idp_config": { "idp_type": 1, "external_idp_config": {"workforce_pool_name": "workforce_pool_name_value"}, @@ -4375,6 +4381,7 @@ def test_create_data_store_rest_required_fields( ( "create_advanced_site_search", "data_store_id", + "skip_default_schema_creation", ) ) jsonified_request.update(unset_fields) @@ -4441,6 +4448,7 @@ def test_create_data_store_rest_unset_required_fields(): ( "createAdvancedSiteSearch", "dataStoreId", + "skipDefaultSchemaCreation", ) ) & set( @@ -5623,6 +5631,12 @@ def test_update_data_store_rest(request_type): "default_schema_id": "default_schema_id_value", "content_config": 1, "create_time": {"seconds": 751, "nanos": 543}, + "language_info": { + "language_code": "language_code_value", + "normalized_language_code": "normalized_language_code_value", + "language": "language_value", + "region": "region_value", + }, "idp_config": { "idp_type": 1, "external_idp_config": {"workforce_pool_name": "workforce_pool_name_value"}, diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py index 462474b9b4ec..4e2a81932b43 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py @@ -5022,7 +5022,8 @@ def test_create_document_rest(request_type): { "principals": [ {"user_id": "user_id_value", "group_id": "group_id_value"} - ] + ], + "idp_wide": True, } ] }, @@ -5476,7 +5477,8 @@ def test_update_document_rest(request_type): { "principals": [ {"user_id": "user_id_value", "group_id": "group_id_value"} - ] + ], + "idp_wide": True, } ] }, diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py index 0b1d9c98d48c..d05b60250570 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_evaluation_service.py @@ -3824,6 +3824,8 @@ def test_create_evaluation_rest(request_type): "user_id": "user_id_value", "user_agent": "user_agent_value", }, + "language_code": "language_code_value", + "region_code": "region_code_value", "facet_specs": [ { "facet_key": { @@ -3890,6 +3892,7 @@ def test_create_evaluation_rest(request_type): "include_citations": True, "ignore_adversarial_query": True, "ignore_non_summary_seeking_query": True, + "ignore_low_relevant_content": True, "model_prompt_spec": {"preamble": "preamble_value"}, "language_code": "language_code_value", "model_spec": {"version": "version_value"}, @@ -3916,7 +3919,21 @@ def test_create_evaluation_rest(request_type): "ranking_expression": "ranking_expression_value", "safe_search": True, "user_labels": {}, + "natural_language_query_understanding_spec": { + "filter_extraction_condition": 1, + "geo_search_query_detection_field_names": [ + "geo_search_query_detection_field_names_value1", + "geo_search_query_detection_field_names_value2", + ], + }, + "search_as_you_type_spec": {"condition": 1}, "custom_fine_tuning_spec": {"enable_search_adaptor": True}, + "session": "session_value", + "session_spec": { + "query_id": "query_id_value", + "search_result_persistence_count": 3328, + }, + "relevance_threshold": 1, }, "query_set_spec": {"sample_query_set": "sample_query_set_value"}, }, @@ -5506,8 +5523,39 @@ def test_parse_serving_config_path(): assert expected == actual +def test_session_path(): + project = "scallop" + location = "abalone" + data_store = "squid" + session = "clam" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format( + project=project, + location=location, + data_store=data_store, + session=session, + ) + actual = EvaluationServiceClient.session_path( + project, location, data_store, session + ) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "whelk", + "location": "octopus", + "data_store": "oyster", + "session": "nudibranch", + } + path = EvaluationServiceClient.session_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_session_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5517,7 +5565,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "mussel", } path = EvaluationServiceClient.common_billing_account_path(**expected) @@ -5527,7 +5575,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "winkle" expected = "folders/{folder}".format( folder=folder, ) @@ -5537,7 +5585,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "nautilus", } path = EvaluationServiceClient.common_folder_path(**expected) @@ -5547,7 +5595,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -5557,7 +5605,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "abalone", } path = EvaluationServiceClient.common_organization_path(**expected) @@ -5567,7 +5615,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "squid" expected = "projects/{project}".format( project=project, ) @@ -5577,7 +5625,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "clam", } path = EvaluationServiceClient.common_project_path(**expected) @@ -5587,8 +5635,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -5599,8 +5647,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "oyster", + "location": "nudibranch", } path = EvaluationServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py index 4259273e7d2a..796d624b5960 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py @@ -1200,8 +1200,11 @@ def test_search_non_empty_request_with_auto_populated_field(): filter="filter_value", canonical_filter="canonical_filter_value", order_by="order_by_value", + language_code="language_code_value", + region_code="region_code_value", user_pseudo_id="user_pseudo_id_value", ranking_expression="ranking_expression_value", + session="session_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,8 +1223,11 @@ def test_search_non_empty_request_with_auto_populated_field(): filter="filter_value", canonical_filter="canonical_filter_value", order_by="order_by_value", + language_code="language_code_value", + region_code="region_code_value", user_pseudo_id="user_pseudo_id_value", ranking_expression="ranking_expression_value", + session="session_value", ) @@ -2636,8 +2642,37 @@ def test_parse_serving_config_path(): assert expected == actual +def test_session_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + session = "abalone" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format( + project=project, + location=location, + data_store=data_store, + session=session, + ) + actual = SearchServiceClient.session_path(project, location, data_store, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "squid", + "location": "clam", + "data_store": "whelk", + "session": "octopus", + } + path = SearchServiceClient.session_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_session_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2647,7 +2682,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = SearchServiceClient.common_billing_account_path(**expected) @@ -2657,7 +2692,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -2667,7 +2702,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = SearchServiceClient.common_folder_path(**expected) @@ -2677,7 +2712,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -2687,7 +2722,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = SearchServiceClient.common_organization_path(**expected) @@ -2697,7 +2732,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -2707,7 +2742,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = SearchServiceClient.common_project_path(**expected) @@ -2717,8 +2752,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -2729,8 +2764,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = SearchServiceClient.common_location_path(**expected) diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_serving_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_serving_config_service.py index 5aad88a14366..f5ce500ab80a 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_serving_config_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_serving_config_service.py @@ -2758,6 +2758,7 @@ def test_update_serving_config_rest(request_type): "include_citations": True, "ignore_adversarial_query": True, "ignore_non_summary_seeking_query": True, + "ignore_low_relevant_content": True, "model_prompt_spec": {"preamble": "preamble_value"}, "language_code": "language_code_value", "model_spec": {"version": "version_value"}, diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py index 34ca36208f34..ab98c6a89e04 100644 --- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py @@ -47,6 +47,7 @@ from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import json_format +from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio @@ -5767,6 +5768,610 @@ async def test_fetch_domain_verification_status_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.SetUriPatternDocumentDataRequest, + dict, + ], +) +def test_set_uri_pattern_document_data(request_type, transport: str = "grpc"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.set_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.SetUriPatternDocumentDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_set_uri_pattern_document_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.set_uri_pattern_document_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.SetUriPatternDocumentDataRequest() + + +def test_set_uri_pattern_document_data_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = site_search_engine_service.SetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.set_uri_pattern_document_data(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.SetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + +def test_set_uri_pattern_document_data_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.set_uri_pattern_document_data + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.set_uri_pattern_document_data + ] = mock_rpc + request = {} + client.set_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.set_uri_pattern_document_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_set_uri_pattern_document_data_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.set_uri_pattern_document_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.SetUriPatternDocumentDataRequest() + + +@pytest.mark.asyncio +async def test_set_uri_pattern_document_data_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.set_uri_pattern_document_data + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.set_uri_pattern_document_data + ] = mock_object + + request = {} + await client.set_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.set_uri_pattern_document_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_set_uri_pattern_document_data_async( + transport: str = "grpc_asyncio", + request_type=site_search_engine_service.SetUriPatternDocumentDataRequest, +): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.set_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.SetUriPatternDocumentDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_set_uri_pattern_document_data_async_from_dict(): + await test_set_uri_pattern_document_data_async(request_type=dict) + + +def test_set_uri_pattern_document_data_field_headers(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.SetUriPatternDocumentDataRequest() + + request.site_search_engine = "site_search_engine_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.set_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_uri_pattern_document_data_field_headers_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.SetUriPatternDocumentDataRequest() + + request.site_search_engine = "site_search_engine_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_uri_pattern_document_data), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.set_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.GetUriPatternDocumentDataRequest, + dict, + ], +) +def test_get_uri_pattern_document_data(request_type, transport: str = "grpc"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + site_search_engine_service.GetUriPatternDocumentDataResponse() + ) + response = client.get_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.GetUriPatternDocumentDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, site_search_engine_service.GetUriPatternDocumentDataResponse + ) + + +def test_get_uri_pattern_document_data_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_uri_pattern_document_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.GetUriPatternDocumentDataRequest() + + +def test_get_uri_pattern_document_data_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = site_search_engine_service.GetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_uri_pattern_document_data(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.GetUriPatternDocumentDataRequest( + site_search_engine="site_search_engine_value", + ) + + +def test_get_uri_pattern_document_data_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_uri_pattern_document_data + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_uri_pattern_document_data + ] = mock_rpc + request = {} + client.get_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_uri_pattern_document_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_uri_pattern_document_data_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.GetUriPatternDocumentDataResponse() + ) + response = await client.get_uri_pattern_document_data() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.GetUriPatternDocumentDataRequest() + + +@pytest.mark.asyncio +async def test_get_uri_pattern_document_data_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_uri_pattern_document_data + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_uri_pattern_document_data + ] = mock_object + + request = {} + await client.get_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_uri_pattern_document_data(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_uri_pattern_document_data_async( + transport: str = "grpc_asyncio", + request_type=site_search_engine_service.GetUriPatternDocumentDataRequest, +): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.GetUriPatternDocumentDataResponse() + ) + response = await client.get_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = site_search_engine_service.GetUriPatternDocumentDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, site_search_engine_service.GetUriPatternDocumentDataResponse + ) + + +@pytest.mark.asyncio +async def test_get_uri_pattern_document_data_async_from_dict(): + await test_get_uri_pattern_document_data_async(request_type=dict) + + +def test_get_uri_pattern_document_data_field_headers(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.GetUriPatternDocumentDataRequest() + + request.site_search_engine = "site_search_engine_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + call.return_value = ( + site_search_engine_service.GetUriPatternDocumentDataResponse() + ) + client.get_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_uri_pattern_document_data_field_headers_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.GetUriPatternDocumentDataRequest() + + request.site_search_engine = "site_search_engine_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_uri_pattern_document_data), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + site_search_engine_service.GetUriPatternDocumentDataResponse() + ) + await client.get_uri_pattern_document_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "site_search_engine=site_search_engine_value", + ) in kw["metadata"] + + @pytest.mark.parametrize( "request_type", [ @@ -5774,7 +6379,727 @@ async def test_fetch_domain_verification_status_async_pages(): dict, ], ) -def test_get_site_search_engine_rest(request_type): +def test_get_site_search_engine_rest(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = site_search_engine.SiteSearchEngine( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine.SiteSearchEngine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_site_search_engine(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, site_search_engine.SiteSearchEngine) + assert response.name == "name_value" + + +def test_get_site_search_engine_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_site_search_engine + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_site_search_engine + ] = mock_rpc + + request = {} + client.get_site_search_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_site_search_engine(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_site_search_engine_rest_required_fields( + request_type=site_search_engine_service.GetSiteSearchEngineRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_site_search_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_site_search_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = site_search_engine.SiteSearchEngine() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = site_search_engine.SiteSearchEngine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_site_search_engine(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_site_search_engine_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_site_search_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_site_search_engine_rest_interceptors(null_interceptor): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SiteSearchEngineServiceRestInterceptor(), + ) + client = SiteSearchEngineServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "post_get_site_search_engine" + ) as post, mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "pre_get_site_search_engine" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = site_search_engine_service.GetSiteSearchEngineRequest.pb( + site_search_engine_service.GetSiteSearchEngineRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = site_search_engine.SiteSearchEngine.to_json( + site_search_engine.SiteSearchEngine() + ) + + request = site_search_engine_service.GetSiteSearchEngineRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = site_search_engine.SiteSearchEngine() + + client.get_site_search_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_site_search_engine_rest_bad_request( + transport: str = "rest", + request_type=site_search_engine_service.GetSiteSearchEngineRequest, +): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_site_search_engine(request) + + +def test_get_site_search_engine_rest_flattened(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = site_search_engine.SiteSearchEngine() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine.SiteSearchEngine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_site_search_engine(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/dataStores/*/siteSearchEngine}" + % client.transport._host, + args[1], + ) + + +def test_get_site_search_engine_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_site_search_engine( + site_search_engine_service.GetSiteSearchEngineRequest(), + name="name_value", + ) + + +def test_get_site_search_engine_rest_error(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.CreateTargetSiteRequest, + dict, + ], +) +def test_create_target_site_rest(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request_init["target_site"] = { + "name": "name_value", + "provided_uri_pattern": "provided_uri_pattern_value", + "type_": 1, + "exact_match": True, + "generated_uri_pattern": "generated_uri_pattern_value", + "root_domain_uri": "root_domain_uri_value", + "site_verification_info": { + "site_verification_state": 1, + "verify_time": {"seconds": 751, "nanos": 543}, + }, + "indexing_status": 1, + "update_time": {}, + "failure_reason": {"quota_failure": {"total_required_quota": 2157}}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = site_search_engine_service.CreateTargetSiteRequest.meta.fields[ + "target_site" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["target_site"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["target_site"][field])): + del request_init["target_site"][field][i][subfield] + else: + del request_init["target_site"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_target_site(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_target_site_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_target_site in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_target_site + ] = mock_rpc + + request = {} + client.create_target_site(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_target_site(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_target_site_rest_required_fields( + request_type=site_search_engine_service.CreateTargetSiteRequest, +): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_target_site._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_target_site._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_target_site(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_target_site_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_target_site._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "targetSite", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_target_site_rest_interceptors(null_interceptor): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SiteSearchEngineServiceRestInterceptor(), + ) + client = SiteSearchEngineServiceClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "post_create_target_site" + ) as post, mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "pre_create_target_site" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = site_search_engine_service.CreateTargetSiteRequest.pb( + site_search_engine_service.CreateTargetSiteRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = site_search_engine_service.CreateTargetSiteRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_target_site( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_target_site_rest_bad_request( + transport: str = "rest", + request_type=site_search_engine_service.CreateTargetSiteRequest, +): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_target_site(request) + + +def test_create_target_site_rest_flattened(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + target_site=site_search_engine.TargetSite(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_target_site(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" + % client.transport._host, + args[1], + ) + + +def test_create_target_site_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_target_site( + site_search_engine_service.CreateTargetSiteRequest(), + parent="parent_value", + target_site=site_search_engine.TargetSite(name="name_value"), + ) + + +def test_create_target_site_rest_error(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + site_search_engine_service.BatchCreateTargetSitesRequest, + dict, + ], +) +def test_batch_create_target_sites_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5782,34 +7107,29 @@ def test_get_site_search_engine_rest(request_type): # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = site_search_engine.SiteSearchEngine( - name="name_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine.SiteSearchEngine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_site_search_engine(request) + response = client.batch_create_target_sites(request) # Establish that the response is the type that we expect. - assert isinstance(response, site_search_engine.SiteSearchEngine) - assert response.name == "name_value" + assert response.operation.name == "operations/spam" -def test_get_site_search_engine_rest_use_cached_wrapped_rpc(): +def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5824,7 +7144,7 @@ def test_get_site_search_engine_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_site_search_engine + client._transport.batch_create_target_sites in client._transport._wrapped_methods ) @@ -5834,29 +7154,33 @@ def test_get_site_search_engine_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_site_search_engine + client._transport.batch_create_target_sites ] = mock_rpc request = {} - client.get_site_search_engine(request) + client.batch_create_target_sites(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_site_search_engine(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_create_target_sites(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_site_search_engine_rest_required_fields( - request_type=site_search_engine_service.GetSiteSearchEngineRequest, +def test_batch_create_target_sites_rest_required_fields( + request_type=site_search_engine_service.BatchCreateTargetSitesRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5867,21 +7191,21 @@ def test_get_site_search_engine_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_site_search_engine._get_unset_required_fields(jsonified_request) + ).batch_create_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_site_search_engine._get_unset_required_fields(jsonified_request) + ).batch_create_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5890,7 +7214,7 @@ def test_get_site_search_engine_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = site_search_engine.SiteSearchEngine() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -5902,39 +7226,45 @@ def test_get_site_search_engine_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = site_search_engine.SiteSearchEngine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_site_search_engine(request) + response = client.batch_create_target_sites(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_site_search_engine_rest_unset_required_fields(): +def test_batch_create_target_sites_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_site_search_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.batch_create_target_sites._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_site_search_engine_rest_interceptors(null_interceptor): +def test_batch_create_target_sites_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5947,14 +7277,18 @@ def test_get_site_search_engine_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_get_site_search_engine" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, + "post_batch_create_target_sites", ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_get_site_search_engine" + transports.SiteSearchEngineServiceRestInterceptor, + "pre_batch_create_target_sites", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.GetSiteSearchEngineRequest.pb( - site_search_engine_service.GetSiteSearchEngineRequest() + pb_message = site_search_engine_service.BatchCreateTargetSitesRequest.pb( + site_search_engine_service.BatchCreateTargetSitesRequest() ) transcode.return_value = { "method": "post", @@ -5966,19 +7300,19 @@ def test_get_site_search_engine_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = site_search_engine.SiteSearchEngine.to_json( - site_search_engine.SiteSearchEngine() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = site_search_engine_service.GetSiteSearchEngineRequest() + request = site_search_engine_service.BatchCreateTargetSitesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = site_search_engine.SiteSearchEngine() + post.return_value = operations_pb2.Operation() - client.get_site_search_engine( + client.batch_create_target_sites( request, metadata=[ ("key", "val"), @@ -5990,93 +7324,34 @@ def test_get_site_search_engine_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_site_search_engine_rest_bad_request( - transport: str = "rest", - request_type=site_search_engine_service.GetSiteSearchEngineRequest, -): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_site_search_engine(request) - - -def test_get_site_search_engine_rest_flattened(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = site_search_engine.SiteSearchEngine() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine.SiteSearchEngine.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_site_search_engine(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=projects/*/locations/*/dataStores/*/siteSearchEngine}" - % client.transport._host, - args[1], - ) - - -def test_get_site_search_engine_rest_flattened_error(transport: str = "rest"): +def test_batch_create_target_sites_rest_bad_request( + transport: str = "rest", + request_type=site_search_engine_service.BatchCreateTargetSitesRequest, +): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_site_search_engine( - site_search_engine_service.GetSiteSearchEngineRequest(), - name="name_value", - ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.batch_create_target_sites(request) -def test_get_site_search_engine_rest_error(): +def test_batch_create_target_sites_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6085,11 +7360,11 @@ def test_get_site_search_engine_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.CreateTargetSiteRequest, + site_search_engine_service.GetTargetSiteRequest, dict, ], ) -def test_create_target_site_rest(request_type): +def test_get_target_site_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6097,113 +7372,48 @@ def test_create_target_site_rest(request_type): # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } - request_init["target_site"] = { - "name": "name_value", - "provided_uri_pattern": "provided_uri_pattern_value", - "type_": 1, - "exact_match": True, - "generated_uri_pattern": "generated_uri_pattern_value", - "root_domain_uri": "root_domain_uri_value", - "site_verification_info": { - "site_verification_state": 1, - "verify_time": {"seconds": 751, "nanos": 543}, - }, - "indexing_status": 1, - "update_time": {}, - "failure_reason": {"quota_failure": {"total_required_quota": 2157}}, + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = site_search_engine_service.CreateTargetSiteRequest.meta.fields[ - "target_site" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["target_site"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["target_site"][field])): - del request_init["target_site"][field][i][subfield] - else: - del request_init["target_site"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine.TargetSite( + name="name_value", + provided_uri_pattern="provided_uri_pattern_value", + type_=site_search_engine.TargetSite.Type.INCLUDE, + exact_match=True, + generated_uri_pattern="generated_uri_pattern_value", + root_domain_uri="root_domain_uri_value", + indexing_status=site_search_engine.TargetSite.IndexingStatus.PENDING, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine.TargetSite.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_target_site(request) + response = client.get_target_site(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, site_search_engine.TargetSite) + assert response.name == "name_value" + assert response.provided_uri_pattern == "provided_uri_pattern_value" + assert response.type_ == site_search_engine.TargetSite.Type.INCLUDE + assert response.exact_match is True + assert response.generated_uri_pattern == "generated_uri_pattern_value" + assert response.root_domain_uri == "root_domain_uri_value" + assert ( + response.indexing_status == site_search_engine.TargetSite.IndexingStatus.PENDING + ) -def test_create_target_site_rest_use_cached_wrapped_rpc(): +def test_get_target_site_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6217,43 +7427,35 @@ def test_create_target_site_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_target_site in client._transport._wrapped_methods - ) + assert client._transport.get_target_site in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_target_site - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_target_site] = mock_rpc request = {} - client.create_target_site(request) + client.get_target_site(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_target_site(request) + client.get_target_site(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_target_site_rest_required_fields( - request_type=site_search_engine_service.CreateTargetSiteRequest, +def test_get_target_site_rest_required_fields( + request_type=site_search_engine_service.GetTargetSiteRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6264,21 +7466,21 @@ def test_create_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_target_site._get_unset_required_fields(jsonified_request) + ).get_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_target_site._get_unset_required_fields(jsonified_request) + ).get_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6287,7 +7489,7 @@ def test_create_target_site_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine.TargetSite() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6299,45 +7501,39 @@ def test_create_target_site_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = site_search_engine.TargetSite.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_target_site(request) + response = client.get_target_site(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_target_site_rest_unset_required_fields(): +def test_get_target_site_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_target_site._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "targetSite", - ) - ) - ) + unset_fields = transport.get_target_site._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_target_site_rest_interceptors(null_interceptor): +def test_get_target_site_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6350,16 +7546,14 @@ def test_create_target_site_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_create_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "post_get_target_site" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_create_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_get_target_site" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.CreateTargetSiteRequest.pb( - site_search_engine_service.CreateTargetSiteRequest() + pb_message = site_search_engine_service.GetTargetSiteRequest.pb( + site_search_engine_service.GetTargetSiteRequest() ) transcode.return_value = { "method": "post", @@ -6371,19 +7565,19 @@ def test_create_target_site_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = site_search_engine.TargetSite.to_json( + site_search_engine.TargetSite() ) - request = site_search_engine_service.CreateTargetSiteRequest() + request = site_search_engine_service.GetTargetSiteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = site_search_engine.TargetSite() - client.create_target_site( + client.get_target_site( request, metadata=[ ("key", "val"), @@ -6395,9 +7589,9 @@ def test_create_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_target_site_rest_bad_request( +def test_get_target_site_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.CreateTargetSiteRequest, + request_type=site_search_engine_service.GetTargetSiteRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6406,7 +7600,7 @@ def test_create_target_site_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } request = request_type(**request_init) @@ -6419,10 +7613,10 @@ def test_create_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_target_site(request) + client.get_target_site(request) -def test_create_target_site_rest_flattened(): +def test_get_target_site_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6431,41 +7625,42 @@ def test_create_target_site_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine.TargetSite() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - target_site=site_search_engine.TargetSite(name="name_value"), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine.TargetSite.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_target_site(**mock_args) + client.get_target_site(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" + "%s/v1alpha/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" % client.transport._host, args[1], ) -def test_create_target_site_rest_flattened_error(transport: str = "rest"): +def test_get_target_site_rest_flattened_error(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6474,14 +7669,13 @@ def test_create_target_site_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_target_site( - site_search_engine_service.CreateTargetSiteRequest(), - parent="parent_value", - target_site=site_search_engine.TargetSite(name="name_value"), + client.get_target_site( + site_search_engine_service.GetTargetSiteRequest(), + name="name_value", ) -def test_create_target_site_rest_error(): +def test_get_target_site_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6490,11 +7684,11 @@ def test_create_target_site_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.BatchCreateTargetSitesRequest, + site_search_engine_service.UpdateTargetSiteRequest, dict, ], ) -def test_batch_create_target_sites_rest(request_type): +def test_update_target_site_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6502,8 +7696,94 @@ def test_batch_create_target_sites_rest(request_type): # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "target_site": { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } + } + request_init["target_site"] = { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4", + "provided_uri_pattern": "provided_uri_pattern_value", + "type_": 1, + "exact_match": True, + "generated_uri_pattern": "generated_uri_pattern_value", + "root_domain_uri": "root_domain_uri_value", + "site_verification_info": { + "site_verification_state": 1, + "verify_time": {"seconds": 751, "nanos": 543}, + }, + "indexing_status": 1, + "update_time": {}, + "failure_reason": {"quota_failure": {"total_required_quota": 2157}}, } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = site_search_engine_service.UpdateTargetSiteRequest.meta.fields[ + "target_site" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["target_site"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["target_site"][field])): + del request_init["target_site"][field][i][subfield] + else: + del request_init["target_site"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -6518,13 +7798,13 @@ def test_batch_create_target_sites_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_target_sites(request) + response = client.update_target_site(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): +def test_update_target_site_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6539,8 +7819,7 @@ def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_create_target_sites - in client._transport._wrapped_methods + client._transport.update_target_site in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6549,11 +7828,11 @@ def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_create_target_sites + client._transport.update_target_site ] = mock_rpc request = {} - client.batch_create_target_sites(request) + client.update_target_site(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6562,20 +7841,19 @@ def test_batch_create_target_sites_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.batch_create_target_sites(request) + client.update_target_site(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_batch_create_target_sites_rest_required_fields( - request_type=site_search_engine_service.BatchCreateTargetSitesRequest, +def test_update_target_site_rest_required_fields( + request_type=site_search_engine_service.UpdateTargetSiteRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6586,21 +7864,17 @@ def test_batch_create_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_target_sites._get_unset_required_fields(jsonified_request) + ).update_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_target_sites._get_unset_required_fields(jsonified_request) + ).update_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6621,7 +7895,7 @@ def test_batch_create_target_sites_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6634,32 +7908,24 @@ def test_batch_create_target_sites_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_target_sites(request) + response = client.update_target_site(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_create_target_sites_rest_unset_required_fields(): +def test_update_target_site_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_create_target_sites._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "requests", - ) - ) - ) + unset_fields = transport.update_target_site._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("targetSite",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_target_sites_rest_interceptors(null_interceptor): +def test_update_target_site_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6674,16 +7940,14 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, - "post_batch_create_target_sites", + transports.SiteSearchEngineServiceRestInterceptor, "post_update_target_site" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, - "pre_batch_create_target_sites", + transports.SiteSearchEngineServiceRestInterceptor, "pre_update_target_site" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.BatchCreateTargetSitesRequest.pb( - site_search_engine_service.BatchCreateTargetSitesRequest() + pb_message = site_search_engine_service.UpdateTargetSiteRequest.pb( + site_search_engine_service.UpdateTargetSiteRequest() ) transcode.return_value = { "method": "post", @@ -6699,7 +7963,7 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = site_search_engine_service.BatchCreateTargetSitesRequest() + request = site_search_engine_service.UpdateTargetSiteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -6707,7 +7971,7 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.batch_create_target_sites( + client.update_target_site( request, metadata=[ ("key", "val"), @@ -6719,9 +7983,9 @@ def test_batch_create_target_sites_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_create_target_sites_rest_bad_request( +def test_update_target_site_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.BatchCreateTargetSitesRequest, + request_type=site_search_engine_service.UpdateTargetSiteRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6730,7 +7994,9 @@ def test_batch_create_target_sites_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "target_site": { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } } request = request_type(**request_init) @@ -6743,10 +8009,69 @@ def test_batch_create_target_sites_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_create_target_sites(request) + client.update_target_site(request) -def test_batch_create_target_sites_rest_error(): +def test_update_target_site_rest_flattened(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "target_site": { + "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + target_site=site_search_engine.TargetSite(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_target_site(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{target_site.name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + % client.transport._host, + args[1], + ) + + +def test_update_target_site_rest_flattened_error(transport: str = "rest"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_target_site( + site_search_engine_service.UpdateTargetSiteRequest(), + target_site=site_search_engine.TargetSite(name="name_value"), + ) + + +def test_update_target_site_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6755,11 +8080,11 @@ def test_batch_create_target_sites_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.GetTargetSiteRequest, + site_search_engine_service.DeleteTargetSiteRequest, dict, ], ) -def test_get_target_site_rest(request_type): +def test_delete_target_site_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6774,41 +8099,22 @@ def test_get_target_site_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = site_search_engine.TargetSite( - name="name_value", - provided_uri_pattern="provided_uri_pattern_value", - type_=site_search_engine.TargetSite.Type.INCLUDE, - exact_match=True, - generated_uri_pattern="generated_uri_pattern_value", - root_domain_uri="root_domain_uri_value", - indexing_status=site_search_engine.TargetSite.IndexingStatus.PENDING, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine.TargetSite.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_target_site(request) + response = client.delete_target_site(request) # Establish that the response is the type that we expect. - assert isinstance(response, site_search_engine.TargetSite) - assert response.name == "name_value" - assert response.provided_uri_pattern == "provided_uri_pattern_value" - assert response.type_ == site_search_engine.TargetSite.Type.INCLUDE - assert response.exact_match is True - assert response.generated_uri_pattern == "generated_uri_pattern_value" - assert response.root_domain_uri == "root_domain_uri_value" - assert ( - response.indexing_status == site_search_engine.TargetSite.IndexingStatus.PENDING - ) + assert response.operation.name == "operations/spam" -def test_get_target_site_rest_use_cached_wrapped_rpc(): +def test_delete_target_site_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6822,30 +8128,38 @@ def test_get_target_site_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_target_site in client._transport._wrapped_methods + assert ( + client._transport.delete_target_site in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_target_site] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_target_site + ] = mock_rpc request = {} - client.get_target_site(request) + client.delete_target_site(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_target_site(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_target_site(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_target_site_rest_required_fields( - request_type=site_search_engine_service.GetTargetSiteRequest, +def test_delete_target_site_rest_required_fields( + request_type=site_search_engine_service.DeleteTargetSiteRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport @@ -6861,7 +8175,7 @@ def test_get_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_target_site._get_unset_required_fields(jsonified_request) + ).delete_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6870,7 +8184,7 @@ def test_get_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_target_site._get_unset_required_fields(jsonified_request) + ).delete_target_site._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6884,7 +8198,7 @@ def test_get_target_site_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = site_search_engine.TargetSite() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -6896,39 +8210,36 @@ def test_get_target_site_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = site_search_engine.TargetSite.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_target_site(request) + response = client.delete_target_site(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_target_site_rest_unset_required_fields(): +def test_delete_target_site_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_target_site._get_unset_required_fields({}) + unset_fields = transport.delete_target_site._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_target_site_rest_interceptors(null_interceptor): +def test_delete_target_site_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6941,14 +8252,16 @@ def test_get_target_site_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_get_target_site" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, "post_delete_target_site" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_get_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_delete_target_site" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.GetTargetSiteRequest.pb( - site_search_engine_service.GetTargetSiteRequest() + pb_message = site_search_engine_service.DeleteTargetSiteRequest.pb( + site_search_engine_service.DeleteTargetSiteRequest() ) transcode.return_value = { "method": "post", @@ -6960,19 +8273,19 @@ def test_get_target_site_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = site_search_engine.TargetSite.to_json( - site_search_engine.TargetSite() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = site_search_engine_service.GetTargetSiteRequest() + request = site_search_engine_service.DeleteTargetSiteRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = site_search_engine.TargetSite() + post.return_value = operations_pb2.Operation() - client.get_target_site( + client.delete_target_site( request, metadata=[ ("key", "val"), @@ -6984,9 +8297,9 @@ def test_get_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_target_site_rest_bad_request( +def test_delete_target_site_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.GetTargetSiteRequest, + request_type=site_search_engine_service.DeleteTargetSiteRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7008,10 +8321,10 @@ def test_get_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_target_site(request) + client.delete_target_site(request) -def test_get_target_site_rest_flattened(): +def test_delete_target_site_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7020,7 +8333,7 @@ def test_get_target_site_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = site_search_engine.TargetSite() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -7036,13 +8349,11 @@ def test_get_target_site_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine.TargetSite.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_target_site(**mock_args) + client.delete_target_site(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -7055,7 +8366,7 @@ def test_get_target_site_rest_flattened(): ) -def test_get_target_site_rest_flattened_error(transport: str = "rest"): +def test_delete_target_site_rest_flattened_error(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7064,13 +8375,13 @@ def test_get_target_site_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_target_site( - site_search_engine_service.GetTargetSiteRequest(), + client.delete_target_site( + site_search_engine_service.DeleteTargetSiteRequest(), name="name_value", ) -def test_get_target_site_rest_error(): +def test_delete_target_site_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7079,11 +8390,11 @@ def test_get_target_site_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.UpdateTargetSiteRequest, + site_search_engine_service.ListTargetSitesRequest, dict, ], ) -def test_update_target_site_rest(request_type): +def test_list_target_sites_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7091,115 +8402,38 @@ def test_update_target_site_rest(request_type): # send a request that will satisfy transcoding request_init = { - "target_site": { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } - } - request_init["target_site"] = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4", - "provided_uri_pattern": "provided_uri_pattern_value", - "type_": 1, - "exact_match": True, - "generated_uri_pattern": "generated_uri_pattern_value", - "root_domain_uri": "root_domain_uri_value", - "site_verification_info": { - "site_verification_state": 1, - "verify_time": {"seconds": 751, "nanos": 543}, - }, - "indexing_status": 1, - "update_time": {}, - "failure_reason": {"quota_failure": {"total_required_quota": 2157}}, + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = site_search_engine_service.UpdateTargetSiteRequest.meta.fields[ - "target_site" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["target_site"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["target_site"][field])): - del request_init["target_site"][field][i][subfield] - else: - del request_init["target_site"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine_service.ListTargetSitesResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine_service.ListTargetSitesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_target_site(request) + response = client.list_target_sites(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListTargetSitesPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 -def test_update_target_site_rest_use_cached_wrapped_rpc(): +def test_list_target_sites_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7213,9 +8447,7 @@ def test_update_target_site_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_target_site in client._transport._wrapped_methods - ) + assert client._transport.list_target_sites in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -7223,32 +8455,29 @@ def test_update_target_site_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_target_site + client._transport.list_target_sites ] = mock_rpc request = {} - client.update_target_site(request) + client.list_target_sites(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_target_site(request) + client.list_target_sites(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_target_site_rest_required_fields( - request_type=site_search_engine_service.UpdateTargetSiteRequest, +def test_list_target_sites_rest_required_fields( + request_type=site_search_engine_service.ListTargetSitesRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7259,17 +8488,28 @@ def test_update_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_target_site._get_unset_required_fields(jsonified_request) + ).list_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_target_site._get_unset_required_fields(jsonified_request) + ).list_target_sites._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7278,7 +8518,7 @@ def test_update_target_site_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine_service.ListTargetSitesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7290,37 +8530,49 @@ def test_update_target_site_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = site_search_engine_service.ListTargetSitesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_target_site(request) + response = client.list_target_sites(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_target_site_rest_unset_required_fields(): +def test_list_target_sites_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_target_site._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("targetSite",))) + unset_fields = transport.list_target_sites._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_target_site_rest_interceptors(null_interceptor): +def test_list_target_sites_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7333,16 +8585,14 @@ def test_update_target_site_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_update_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "post_list_target_sites" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_update_target_site" + transports.SiteSearchEngineServiceRestInterceptor, "pre_list_target_sites" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.UpdateTargetSiteRequest.pb( - site_search_engine_service.UpdateTargetSiteRequest() + pb_message = site_search_engine_service.ListTargetSitesRequest.pb( + site_search_engine_service.ListTargetSitesRequest() ) transcode.return_value = { "method": "post", @@ -7354,19 +8604,21 @@ def test_update_target_site_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = ( + site_search_engine_service.ListTargetSitesResponse.to_json( + site_search_engine_service.ListTargetSitesResponse() + ) ) - request = site_search_engine_service.UpdateTargetSiteRequest() + request = site_search_engine_service.ListTargetSitesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = site_search_engine_service.ListTargetSitesResponse() - client.update_target_site( + client.list_target_sites( request, metadata=[ ("key", "val"), @@ -7378,9 +8630,9 @@ def test_update_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_target_site_rest_bad_request( +def test_list_target_sites_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.UpdateTargetSiteRequest, + request_type=site_search_engine_service.ListTargetSitesRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7389,9 +8641,7 @@ def test_update_target_site_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "target_site": { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) @@ -7404,10 +8654,10 @@ def test_update_target_site_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_target_site(request) + client.list_target_sites(request) -def test_update_target_site_rest_flattened(): +def test_list_target_sites_rest_flattened(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7416,42 +8666,44 @@ def test_update_target_site_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine_service.ListTargetSitesResponse() # get arguments that satisfy an http rule for this method sample_request = { - "target_site": { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } # get truthy value for each flattened field mock_args = dict( - target_site=site_search_engine.TargetSite(name="name_value"), + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = site_search_engine_service.ListTargetSitesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_target_site(**mock_args) + client.list_target_sites(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1alpha/{target_site.name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" + "%s/v1alpha/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" % client.transport._host, args[1], ) -def test_update_target_site_rest_flattened_error(transport: str = "rest"): +def test_list_target_sites_rest_flattened_error(transport: str = "rest"): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7460,26 +8712,86 @@ def test_update_target_site_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_target_site( - site_search_engine_service.UpdateTargetSiteRequest(), - target_site=site_search_engine.TargetSite(name="name_value"), + client.list_target_sites( + site_search_engine_service.ListTargetSitesRequest(), + parent="parent_value", ) -def test_update_target_site_rest_error(): +def test_list_target_sites_rest_pager(transport: str = "rest"): client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + site_search_engine_service.ListTargetSitesResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.ListTargetSitesResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.ListTargetSitesResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.ListTargetSitesResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + site_search_engine_service.ListTargetSitesResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + + pager = client.list_target_sites(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, site_search_engine.TargetSite) for i in results) + + pages = list(client.list_target_sites(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.DeleteTargetSiteRequest, + site_search_engine_service.EnableAdvancedSiteSearchRequest, dict, ], ) -def test_delete_target_site_rest(request_type): +def test_enable_advanced_site_search_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7487,7 +8799,7 @@ def test_delete_target_site_rest(request_type): # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" + "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) @@ -7503,13 +8815,13 @@ def test_delete_target_site_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_target_site(request) + response = client.enable_advanced_site_search(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_target_site_rest_use_cached_wrapped_rpc(): +def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7524,7 +8836,8 @@ def test_delete_target_site_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_target_site in client._transport._wrapped_methods + client._transport.enable_advanced_site_search + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -7533,11 +8846,11 @@ def test_delete_target_site_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_target_site + client._transport.enable_advanced_site_search ] = mock_rpc request = {} - client.delete_target_site(request) + client.enable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -7546,20 +8859,20 @@ def test_delete_target_site_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_target_site(request) + client.enable_advanced_site_search(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_target_site_rest_required_fields( - request_type=site_search_engine_service.DeleteTargetSiteRequest, +def test_enable_advanced_site_search_rest_required_fields( + request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["site_search_engine"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7570,21 +8883,21 @@ def test_delete_target_site_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_target_site._get_unset_required_fields(jsonified_request) + ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["siteSearchEngine"] = "site_search_engine_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_target_site._get_unset_required_fields(jsonified_request) + ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7605,9 +8918,10 @@ def test_delete_target_site_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -7617,24 +8931,24 @@ def test_delete_target_site_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_target_site(request) + response = client.enable_advanced_site_search(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_target_site_rest_unset_required_fields(): +def test_enable_advanced_site_search_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_target_site._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.enable_advanced_site_search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_target_site_rest_interceptors(null_interceptor): +def test_enable_advanced_site_search_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7649,14 +8963,16 @@ def test_delete_target_site_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_delete_target_site" + transports.SiteSearchEngineServiceRestInterceptor, + "post_enable_advanced_site_search", ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_delete_target_site" + transports.SiteSearchEngineServiceRestInterceptor, + "pre_enable_advanced_site_search", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.DeleteTargetSiteRequest.pb( - site_search_engine_service.DeleteTargetSiteRequest() + pb_message = site_search_engine_service.EnableAdvancedSiteSearchRequest.pb( + site_search_engine_service.EnableAdvancedSiteSearchRequest() ) transcode.return_value = { "method": "post", @@ -7672,7 +8988,7 @@ def test_delete_target_site_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = site_search_engine_service.DeleteTargetSiteRequest() + request = site_search_engine_service.EnableAdvancedSiteSearchRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -7680,7 +8996,7 @@ def test_delete_target_site_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_target_site( + client.enable_advanced_site_search( request, metadata=[ ("key", "val"), @@ -7692,9 +9008,9 @@ def test_delete_target_site_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_target_site_rest_bad_request( +def test_enable_advanced_site_search_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.DeleteTargetSiteRequest, + request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7703,80 +9019,23 @@ def test_delete_target_site_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_target_site(request) - - -def test_delete_target_site_rest_flattened(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine/targetSites/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_target_site(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{name=projects/*/locations/*/dataStores/*/siteSearchEngine/targetSites/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_target_site_rest_flattened_error(transport: str = "rest"): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_target_site( - site_search_engine_service.DeleteTargetSiteRequest(), - name="name_value", - ) + "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.enable_advanced_site_search(request) -def test_delete_target_site_rest_error(): +def test_enable_advanced_site_search_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7785,11 +9044,11 @@ def test_delete_target_site_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.ListTargetSitesRequest, + site_search_engine_service.DisableAdvancedSiteSearchRequest, dict, ], ) -def test_list_target_sites_rest(request_type): +def test_disable_advanced_site_search_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7797,38 +9056,29 @@ def test_list_target_sites_rest(request_type): # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.ListTargetSitesResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine_service.ListTargetSitesResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_target_sites(request) + response = client.disable_advanced_site_search(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTargetSitesPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert response.operation.name == "operations/spam" -def test_list_target_sites_rest_use_cached_wrapped_rpc(): +def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7842,7 +9092,10 @@ def test_list_target_sites_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_target_sites in client._transport._wrapped_methods + assert ( + client._transport.disable_advanced_site_search + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -7850,29 +9103,33 @@ def test_list_target_sites_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_target_sites + client._transport.disable_advanced_site_search ] = mock_rpc request = {} - client.list_target_sites(request) + client.disable_advanced_site_search(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_target_sites(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.disable_advanced_site_search(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_target_sites_rest_required_fields( - request_type=site_search_engine_service.ListTargetSitesRequest, +def test_disable_advanced_site_search_rest_required_fields( + request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["site_search_engine"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7883,28 +9140,21 @@ def test_list_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_target_sites._get_unset_required_fields(jsonified_request) + ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["siteSearchEngine"] = "site_search_engine_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_target_sites._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7913,7 +9163,7 @@ def test_list_target_sites_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.ListTargetSitesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -7925,49 +9175,37 @@ def test_list_target_sites_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = site_search_engine_service.ListTargetSitesResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_target_sites(request) + response = client.disable_advanced_site_search(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_target_sites_rest_unset_required_fields(): +def test_disable_advanced_site_search_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_target_sites._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.disable_advanced_site_search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_target_sites_rest_interceptors(null_interceptor): +def test_disable_advanced_site_search_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -7980,14 +9218,18 @@ def test_list_target_sites_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_list_target_sites" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.SiteSearchEngineServiceRestInterceptor, + "post_disable_advanced_site_search", ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_list_target_sites" + transports.SiteSearchEngineServiceRestInterceptor, + "pre_disable_advanced_site_search", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.ListTargetSitesRequest.pb( - site_search_engine_service.ListTargetSitesRequest() + pb_message = site_search_engine_service.DisableAdvancedSiteSearchRequest.pb( + site_search_engine_service.DisableAdvancedSiteSearchRequest() ) transcode.return_value = { "method": "post", @@ -7999,21 +9241,19 @@ def test_list_target_sites_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = ( - site_search_engine_service.ListTargetSitesResponse.to_json( - site_search_engine_service.ListTargetSitesResponse() - ) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = site_search_engine_service.ListTargetSitesRequest() + request = site_search_engine_service.DisableAdvancedSiteSearchRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = site_search_engine_service.ListTargetSitesResponse() + post.return_value = operations_pb2.Operation() - client.list_target_sites( + client.disable_advanced_site_search( request, metadata=[ ("key", "val"), @@ -8025,9 +9265,9 @@ def test_list_target_sites_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_target_sites_rest_bad_request( +def test_disable_advanced_site_search_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.ListTargetSitesRequest, + request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8036,7 +9276,7 @@ def test_list_target_sites_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" } request = request_type(**request_init) @@ -8049,144 +9289,23 @@ def test_list_target_sites_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_target_sites(request) - - -def test_list_target_sites_rest_flattened(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.ListTargetSitesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = site_search_engine_service.ListTargetSitesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.list_target_sites(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1alpha/{parent=projects/*/locations/*/dataStores/*/siteSearchEngine}/targetSites" - % client.transport._host, - args[1], - ) - - -def test_list_target_sites_rest_flattened_error(transport: str = "rest"): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_target_sites( - site_search_engine_service.ListTargetSitesRequest(), - parent="parent_value", - ) - - -def test_list_target_sites_rest_pager(transport: str = "rest"): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - site_search_engine_service.ListTargetSitesResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.ListTargetSitesResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.ListTargetSitesResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.ListTargetSitesResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - site_search_engine_service.ListTargetSitesResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" - } - - pager = client.list_target_sites(request=sample_request) + client.disable_advanced_site_search(request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, site_search_engine.TargetSite) for i in results) - pages = list(client.list_target_sites(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_disable_advanced_site_search_rest_error(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.EnableAdvancedSiteSearchRequest, + site_search_engine_service.RecrawlUrisRequest, dict, ], ) -def test_enable_advanced_site_search_rest(request_type): +def test_recrawl_uris_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8210,13 +9329,13 @@ def test_enable_advanced_site_search_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.enable_advanced_site_search(request) + response = client.recrawl_uris(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): +def test_recrawl_uris_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8230,22 +9349,17 @@ def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.enable_advanced_site_search - in client._transport._wrapped_methods - ) + assert client._transport.recrawl_uris in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.enable_advanced_site_search - ] = mock_rpc + client._transport._wrapped_methods[client._transport.recrawl_uris] = mock_rpc request = {} - client.enable_advanced_site_search(request) + client.recrawl_uris(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8254,20 +9368,21 @@ def test_enable_advanced_site_search_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.enable_advanced_site_search(request) + client.recrawl_uris(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_enable_advanced_site_search_rest_required_fields( - request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, +def test_recrawl_uris_rest_required_fields( + request_type=site_search_engine_service.RecrawlUrisRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} request_init["site_search_engine"] = "" + request_init["uris"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8278,21 +9393,24 @@ def test_enable_advanced_site_search_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).recrawl_uris._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["siteSearchEngine"] = "site_search_engine_value" + jsonified_request["uris"] = "uris_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).enable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).recrawl_uris._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "siteSearchEngine" in jsonified_request assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + assert "uris" in jsonified_request + assert jsonified_request["uris"] == "uris_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8326,24 +9444,32 @@ def test_enable_advanced_site_search_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.enable_advanced_site_search(request) + response = client.recrawl_uris(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_enable_advanced_site_search_rest_unset_required_fields(): +def test_recrawl_uris_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.enable_advanced_site_search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) + unset_fields = transport.recrawl_uris._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "siteSearchEngine", + "uris", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_advanced_site_search_rest_interceptors(null_interceptor): +def test_recrawl_uris_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8358,16 +9484,14 @@ def test_enable_advanced_site_search_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, - "post_enable_advanced_site_search", + transports.SiteSearchEngineServiceRestInterceptor, "post_recrawl_uris" ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, - "pre_enable_advanced_site_search", + transports.SiteSearchEngineServiceRestInterceptor, "pre_recrawl_uris" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.EnableAdvancedSiteSearchRequest.pb( - site_search_engine_service.EnableAdvancedSiteSearchRequest() + pb_message = site_search_engine_service.RecrawlUrisRequest.pb( + site_search_engine_service.RecrawlUrisRequest() ) transcode.return_value = { "method": "post", @@ -8383,7 +9507,7 @@ def test_enable_advanced_site_search_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = site_search_engine_service.EnableAdvancedSiteSearchRequest() + request = site_search_engine_service.RecrawlUrisRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8391,7 +9515,7 @@ def test_enable_advanced_site_search_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.enable_advanced_site_search( + client.recrawl_uris( request, metadata=[ ("key", "val"), @@ -8403,9 +9527,8 @@ def test_enable_advanced_site_search_rest_interceptors(null_interceptor): post.assert_called_once() -def test_enable_advanced_site_search_rest_bad_request( - transport: str = "rest", - request_type=site_search_engine_service.EnableAdvancedSiteSearchRequest, +def test_recrawl_uris_rest_bad_request( + transport: str = "rest", request_type=site_search_engine_service.RecrawlUrisRequest ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8427,10 +9550,10 @@ def test_enable_advanced_site_search_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.enable_advanced_site_search(request) + client.recrawl_uris(request) -def test_enable_advanced_site_search_rest_error(): +def test_recrawl_uris_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8439,11 +9562,11 @@ def test_enable_advanced_site_search_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.DisableAdvancedSiteSearchRequest, + site_search_engine_service.BatchVerifyTargetSitesRequest, dict, ], ) -def test_disable_advanced_site_search_rest(request_type): +def test_batch_verify_target_sites_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8451,7 +9574,7 @@ def test_disable_advanced_site_search_rest(request_type): # send a request that will satisfy transcoding request_init = { - "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" } request = request_type(**request_init) @@ -8467,13 +9590,13 @@ def test_disable_advanced_site_search_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.disable_advanced_site_search(request) + response = client.batch_verify_target_sites(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): +def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8488,7 +9611,7 @@ def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.disable_advanced_site_search + client._transport.batch_verify_target_sites in client._transport._wrapped_methods ) @@ -8498,11 +9621,11 @@ def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.disable_advanced_site_search + client._transport.batch_verify_target_sites ] = mock_rpc request = {} - client.disable_advanced_site_search(request) + client.batch_verify_target_sites(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8511,20 +9634,20 @@ def test_disable_advanced_site_search_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.disable_advanced_site_search(request) + client.batch_verify_target_sites(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_disable_advanced_site_search_rest_required_fields( - request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, +def test_batch_verify_target_sites_rest_required_fields( + request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["site_search_engine"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8535,21 +9658,21 @@ def test_disable_advanced_site_search_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["siteSearchEngine"] = "site_search_engine_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).disable_advanced_site_search._get_unset_required_fields(jsonified_request) + ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "siteSearchEngine" in jsonified_request - assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8583,24 +9706,24 @@ def test_disable_advanced_site_search_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.disable_advanced_site_search(request) + response = client.batch_verify_target_sites(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_disable_advanced_site_search_rest_unset_required_fields(): +def test_batch_verify_target_sites_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.disable_advanced_site_search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) + unset_fields = transport.batch_verify_target_sites._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_advanced_site_search_rest_interceptors(null_interceptor): +def test_batch_verify_target_sites_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8616,15 +9739,15 @@ def test_disable_advanced_site_search_rest_interceptors(null_interceptor): operation.Operation, "_set_result_from_operation" ), mock.patch.object( transports.SiteSearchEngineServiceRestInterceptor, - "post_disable_advanced_site_search", + "post_batch_verify_target_sites", ) as post, mock.patch.object( transports.SiteSearchEngineServiceRestInterceptor, - "pre_disable_advanced_site_search", + "pre_batch_verify_target_sites", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.DisableAdvancedSiteSearchRequest.pb( - site_search_engine_service.DisableAdvancedSiteSearchRequest() + pb_message = site_search_engine_service.BatchVerifyTargetSitesRequest.pb( + site_search_engine_service.BatchVerifyTargetSitesRequest() ) transcode.return_value = { "method": "post", @@ -8640,7 +9763,7 @@ def test_disable_advanced_site_search_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = site_search_engine_service.DisableAdvancedSiteSearchRequest() + request = site_search_engine_service.BatchVerifyTargetSitesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8648,7 +9771,7 @@ def test_disable_advanced_site_search_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.disable_advanced_site_search( + client.batch_verify_target_sites( request, metadata=[ ("key", "val"), @@ -8660,9 +9783,9 @@ def test_disable_advanced_site_search_rest_interceptors(null_interceptor): post.assert_called_once() -def test_disable_advanced_site_search_rest_bad_request( +def test_batch_verify_target_sites_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.DisableAdvancedSiteSearchRequest, + request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8671,7 +9794,7 @@ def test_disable_advanced_site_search_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" } request = request_type(**request_init) @@ -8684,10 +9807,10 @@ def test_disable_advanced_site_search_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.disable_advanced_site_search(request) + client.batch_verify_target_sites(request) -def test_disable_advanced_site_search_rest_error(): +def test_batch_verify_target_sites_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8696,11 +9819,11 @@ def test_disable_advanced_site_search_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.RecrawlUrisRequest, + site_search_engine_service.FetchDomainVerificationStatusRequest, dict, ], ) -def test_recrawl_uris_rest(request_type): +def test_fetch_domain_verification_status_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8708,29 +9831,40 @@ def test_recrawl_uris_rest(request_type): # send a request that will satisfy transcoding request_init = { - "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine_service.FetchDomainVerificationStatusResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + site_search_engine_service.FetchDomainVerificationStatusResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.recrawl_uris(request) + response = client.fetch_domain_verification_status(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.FetchDomainVerificationStatusPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 -def test_recrawl_uris_rest_use_cached_wrapped_rpc(): +def test_fetch_domain_verification_status_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8744,40 +9878,40 @@ def test_recrawl_uris_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.recrawl_uris in client._transport._wrapped_methods + assert ( + client._transport.fetch_domain_verification_status + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.recrawl_uris] = mock_rpc + client._transport._wrapped_methods[ + client._transport.fetch_domain_verification_status + ] = mock_rpc request = {} - client.recrawl_uris(request) + client.fetch_domain_verification_status(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.recrawl_uris(request) + client.fetch_domain_verification_status(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_recrawl_uris_rest_required_fields( - request_type=site_search_engine_service.RecrawlUrisRequest, +def test_fetch_domain_verification_status_rest_required_fields( + request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} request_init["site_search_engine"] = "" - request_init["uris"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8788,24 +9922,28 @@ def test_recrawl_uris_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).recrawl_uris._get_unset_required_fields(jsonified_request) + ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["siteSearchEngine"] = "site_search_engine_value" - jsonified_request["uris"] = "uris_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).recrawl_uris._get_unset_required_fields(jsonified_request) + ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "siteSearchEngine" in jsonified_request assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" - assert "uris" in jsonified_request - assert jsonified_request["uris"] == "uris_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8814,7 +9952,7 @@ def test_recrawl_uris_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = site_search_engine_service.FetchDomainVerificationStatusResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8826,45 +9964,53 @@ def test_recrawl_uris_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + site_search_engine_service.FetchDomainVerificationStatusResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.recrawl_uris(request) + response = client.fetch_domain_verification_status(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_recrawl_uris_rest_unset_required_fields(): +def test_fetch_domain_verification_status_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.recrawl_uris._get_unset_required_fields({}) + unset_fields = ( + transport.fetch_domain_verification_status._get_unset_required_fields({}) + ) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "siteSearchEngine", - "uris", + "pageSize", + "pageToken", ) ) + & set(("siteSearchEngine",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_recrawl_uris_rest_interceptors(null_interceptor): +def test_fetch_domain_verification_status_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8877,16 +10023,16 @@ def test_recrawl_uris_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "post_recrawl_uris" + transports.SiteSearchEngineServiceRestInterceptor, + "post_fetch_domain_verification_status", ) as post, mock.patch.object( - transports.SiteSearchEngineServiceRestInterceptor, "pre_recrawl_uris" + transports.SiteSearchEngineServiceRestInterceptor, + "pre_fetch_domain_verification_status", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.RecrawlUrisRequest.pb( - site_search_engine_service.RecrawlUrisRequest() + pb_message = site_search_engine_service.FetchDomainVerificationStatusRequest.pb( + site_search_engine_service.FetchDomainVerificationStatusRequest() ) transcode.return_value = { "method": "post", @@ -8898,19 +10044,23 @@ def test_recrawl_uris_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = ( + site_search_engine_service.FetchDomainVerificationStatusResponse.to_json( + site_search_engine_service.FetchDomainVerificationStatusResponse() + ) ) - request = site_search_engine_service.RecrawlUrisRequest() + request = site_search_engine_service.FetchDomainVerificationStatusRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = ( + site_search_engine_service.FetchDomainVerificationStatusResponse() + ) - client.recrawl_uris( + client.fetch_domain_verification_status( request, metadata=[ ("key", "val"), @@ -8922,8 +10072,9 @@ def test_recrawl_uris_rest_interceptors(null_interceptor): post.assert_called_once() -def test_recrawl_uris_rest_bad_request( - transport: str = "rest", request_type=site_search_engine_service.RecrawlUrisRequest +def test_fetch_domain_verification_status_rest_bad_request( + transport: str = "rest", + request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8932,7 +10083,7 @@ def test_recrawl_uris_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "site_search_engine": "projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine" + "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" } request = request_type(**request_init) @@ -8945,23 +10096,85 @@ def test_recrawl_uris_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.recrawl_uris(request) + client.fetch_domain_verification_status(request) -def test_recrawl_uris_rest_error(): +def test_fetch_domain_verification_status_rest_pager(transport: str = "rest"): client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + next_page_token="abc", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[], + next_page_token="def", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + ], + next_page_token="ghi", + ), + site_search_engine_service.FetchDomainVerificationStatusResponse( + target_sites=[ + site_search_engine.TargetSite(), + site_search_engine.TargetSite(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + site_search_engine_service.FetchDomainVerificationStatusResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" + } + + pager = client.fetch_domain_verification_status(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, site_search_engine.TargetSite) for i in results) + + pages = list( + client.fetch_domain_verification_status(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.BatchVerifyTargetSitesRequest, + site_search_engine_service.SetUriPatternDocumentDataRequest, dict, ], ) -def test_batch_verify_target_sites_rest(request_type): +def test_set_uri_pattern_document_data_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8969,7 +10182,7 @@ def test_batch_verify_target_sites_rest(request_type): # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" + "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" } request = request_type(**request_init) @@ -8985,13 +10198,13 @@ def test_batch_verify_target_sites_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_verify_target_sites(request) + response = client.set_uri_pattern_document_data(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): +def test_set_uri_pattern_document_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9006,7 +10219,7 @@ def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.batch_verify_target_sites + client._transport.set_uri_pattern_document_data in client._transport._wrapped_methods ) @@ -9016,11 +10229,11 @@ def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.batch_verify_target_sites + client._transport.set_uri_pattern_document_data ] = mock_rpc request = {} - client.batch_verify_target_sites(request) + client.set_uri_pattern_document_data(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9029,20 +10242,20 @@ def test_batch_verify_target_sites_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.batch_verify_target_sites(request) + client.set_uri_pattern_document_data(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_batch_verify_target_sites_rest_required_fields( - request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, +def test_set_uri_pattern_document_data_rest_required_fields( + request_type=site_search_engine_service.SetUriPatternDocumentDataRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["site_search_engine"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9053,21 +10266,21 @@ def test_batch_verify_target_sites_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) + ).set_uri_pattern_document_data._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["siteSearchEngine"] = "site_search_engine_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_verify_target_sites._get_unset_required_fields(jsonified_request) + ).set_uri_pattern_document_data._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == "site_search_engine_value" client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9101,24 +10314,26 @@ def test_batch_verify_target_sites_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_verify_target_sites(request) + response = client.set_uri_pattern_document_data(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_verify_target_sites_rest_unset_required_fields(): +def test_set_uri_pattern_document_data_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_verify_target_sites._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent",))) + unset_fields = transport.set_uri_pattern_document_data._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_verify_target_sites_rest_interceptors(null_interceptor): +def test_set_uri_pattern_document_data_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9134,15 +10349,15 @@ def test_batch_verify_target_sites_rest_interceptors(null_interceptor): operation.Operation, "_set_result_from_operation" ), mock.patch.object( transports.SiteSearchEngineServiceRestInterceptor, - "post_batch_verify_target_sites", + "post_set_uri_pattern_document_data", ) as post, mock.patch.object( transports.SiteSearchEngineServiceRestInterceptor, - "pre_batch_verify_target_sites", + "pre_set_uri_pattern_document_data", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.BatchVerifyTargetSitesRequest.pb( - site_search_engine_service.BatchVerifyTargetSitesRequest() + pb_message = site_search_engine_service.SetUriPatternDocumentDataRequest.pb( + site_search_engine_service.SetUriPatternDocumentDataRequest() ) transcode.return_value = { "method": "post", @@ -9158,7 +10373,7 @@ def test_batch_verify_target_sites_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = site_search_engine_service.BatchVerifyTargetSitesRequest() + request = site_search_engine_service.SetUriPatternDocumentDataRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9166,7 +10381,7 @@ def test_batch_verify_target_sites_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.batch_verify_target_sites( + client.set_uri_pattern_document_data( request, metadata=[ ("key", "val"), @@ -9178,9 +10393,9 @@ def test_batch_verify_target_sites_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_verify_target_sites_rest_bad_request( +def test_set_uri_pattern_document_data_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.BatchVerifyTargetSitesRequest, + request_type=site_search_engine_service.SetUriPatternDocumentDataRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9189,7 +10404,7 @@ def test_batch_verify_target_sites_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" + "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" } request = request_type(**request_init) @@ -9202,10 +10417,10 @@ def test_batch_verify_target_sites_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_verify_target_sites(request) + client.set_uri_pattern_document_data(request) -def test_batch_verify_target_sites_rest_error(): +def test_set_uri_pattern_document_data_rest_error(): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9214,11 +10429,11 @@ def test_batch_verify_target_sites_rest_error(): @pytest.mark.parametrize( "request_type", [ - site_search_engine_service.FetchDomainVerificationStatusRequest, + site_search_engine_service.GetUriPatternDocumentDataRequest, dict, ], ) -def test_fetch_domain_verification_status_rest(request_type): +def test_get_uri_pattern_document_data_rest(request_type): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9233,33 +10448,28 @@ def test_fetch_domain_verification_status_rest(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.FetchDomainVerificationStatusResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) + return_value = site_search_engine_service.GetUriPatternDocumentDataResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - site_search_engine_service.FetchDomainVerificationStatusResponse.pb( - return_value - ) + return_value = site_search_engine_service.GetUriPatternDocumentDataResponse.pb( + return_value ) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_domain_verification_status(request) + response = client.get_uri_pattern_document_data(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDomainVerificationStatusPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance( + response, site_search_engine_service.GetUriPatternDocumentDataResponse + ) -def test_fetch_domain_verification_status_rest_use_cached_wrapped_rpc(): +def test_get_uri_pattern_document_data_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9274,7 +10484,7 @@ def test_fetch_domain_verification_status_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_domain_verification_status + client._transport.get_uri_pattern_document_data in client._transport._wrapped_methods ) @@ -9284,24 +10494,24 @@ def test_fetch_domain_verification_status_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_domain_verification_status + client._transport.get_uri_pattern_document_data ] = mock_rpc request = {} - client.fetch_domain_verification_status(request) + client.get_uri_pattern_document_data(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_domain_verification_status(request) + client.get_uri_pattern_document_data(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_fetch_domain_verification_status_rest_required_fields( - request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, +def test_get_uri_pattern_document_data_rest_required_fields( + request_type=site_search_engine_service.GetUriPatternDocumentDataRequest, ): transport_class = transports.SiteSearchEngineServiceRestTransport @@ -9317,7 +10527,7 @@ def test_fetch_domain_verification_status_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) + ).get_uri_pattern_document_data._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -9326,14 +10536,7 @@ def test_fetch_domain_verification_status_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).fetch_domain_verification_status._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).get_uri_pattern_document_data._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9347,7 +10550,7 @@ def test_fetch_domain_verification_status_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = site_search_engine_service.FetchDomainVerificationStatusResponse() + return_value = site_search_engine_service.GetUriPatternDocumentDataResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -9369,7 +10572,7 @@ def test_fetch_domain_verification_status_rest_required_fields( # Convert return value to protobuf type return_value = ( - site_search_engine_service.FetchDomainVerificationStatusResponse.pb( + site_search_engine_service.GetUriPatternDocumentDataResponse.pb( return_value ) ) @@ -9378,34 +10581,26 @@ def test_fetch_domain_verification_status_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.fetch_domain_verification_status(request) + response = client.get_uri_pattern_document_data(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_fetch_domain_verification_status_rest_unset_required_fields(): +def test_get_uri_pattern_document_data_rest_unset_required_fields(): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = ( - transport.fetch_domain_verification_status._get_unset_required_fields({}) - ) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("siteSearchEngine",)) + unset_fields = transport.get_uri_pattern_document_data._get_unset_required_fields( + {} ) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_domain_verification_status_rest_interceptors(null_interceptor): +def test_get_uri_pattern_document_data_rest_interceptors(null_interceptor): transport = transports.SiteSearchEngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9419,15 +10614,15 @@ def test_fetch_domain_verification_status_rest_interceptors(null_interceptor): path_template, "transcode" ) as transcode, mock.patch.object( transports.SiteSearchEngineServiceRestInterceptor, - "post_fetch_domain_verification_status", + "post_get_uri_pattern_document_data", ) as post, mock.patch.object( transports.SiteSearchEngineServiceRestInterceptor, - "pre_fetch_domain_verification_status", + "pre_get_uri_pattern_document_data", ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = site_search_engine_service.FetchDomainVerificationStatusRequest.pb( - site_search_engine_service.FetchDomainVerificationStatusRequest() + pb_message = site_search_engine_service.GetUriPatternDocumentDataRequest.pb( + site_search_engine_service.GetUriPatternDocumentDataRequest() ) transcode.return_value = { "method": "post", @@ -9440,22 +10635,22 @@ def test_fetch_domain_verification_status_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.request = PreparedRequest() req.return_value._content = ( - site_search_engine_service.FetchDomainVerificationStatusResponse.to_json( - site_search_engine_service.FetchDomainVerificationStatusResponse() + site_search_engine_service.GetUriPatternDocumentDataResponse.to_json( + site_search_engine_service.GetUriPatternDocumentDataResponse() ) ) - request = site_search_engine_service.FetchDomainVerificationStatusRequest() + request = site_search_engine_service.GetUriPatternDocumentDataRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = ( - site_search_engine_service.FetchDomainVerificationStatusResponse() + site_search_engine_service.GetUriPatternDocumentDataResponse() ) - client.fetch_domain_verification_status( + client.get_uri_pattern_document_data( request, metadata=[ ("key", "val"), @@ -9467,9 +10662,9 @@ def test_fetch_domain_verification_status_rest_interceptors(null_interceptor): post.assert_called_once() -def test_fetch_domain_verification_status_rest_bad_request( +def test_get_uri_pattern_document_data_rest_bad_request( transport: str = "rest", - request_type=site_search_engine_service.FetchDomainVerificationStatusRequest, + request_type=site_search_engine_service.GetUriPatternDocumentDataRequest, ): client = SiteSearchEngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9491,76 +10686,14 @@ def test_fetch_domain_verification_status_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.fetch_domain_verification_status(request) + client.get_uri_pattern_document_data(request) -def test_fetch_domain_verification_status_rest_pager(transport: str = "rest"): +def test_get_uri_pattern_document_data_rest_error(): client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - next_page_token="abc", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[], - next_page_token="def", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - ], - next_page_token="ghi", - ), - site_search_engine_service.FetchDomainVerificationStatusResponse( - target_sites=[ - site_search_engine.TargetSite(), - site_search_engine.TargetSite(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - site_search_engine_service.FetchDomainVerificationStatusResponse.to_json(x) - for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "site_search_engine": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/siteSearchEngine" - } - - pager = client.fetch_domain_verification_status(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, site_search_engine.TargetSite) for i in results) - - pages = list( - client.fetch_domain_verification_status(request=sample_request).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. @@ -9713,6 +10846,8 @@ def test_site_search_engine_service_base_transport(): "recrawl_uris", "batch_verify_target_sites", "fetch_domain_verification_status", + "set_uri_pattern_document_data", + "get_uri_pattern_document_data", "get_operation", "cancel_operation", "list_operations", @@ -10036,6 +11171,12 @@ def test_site_search_engine_service_client_transport_session_collision(transport session1 = client1.transport.fetch_domain_verification_status._session session2 = client2.transport.fetch_domain_verification_status._session assert session1 != session2 + session1 = client1.transport.set_uri_pattern_document_data._session + session2 = client2.transport.set_uri_pattern_document_data._session + assert session1 != session2 + session1 = client1.transport.get_uri_pattern_document_data._session + session2 = client2.transport.get_uri_pattern_document_data._session + assert session1 != session2 def test_site_search_engine_service_grpc_transport_channel(): diff --git a/packages/google-cloud-dlp/google/cloud/dlp/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp/__init__.py index 9ed37d2ac6c2..4a4594889a9c 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp/__init__.py @@ -207,6 +207,7 @@ OutputStorageConfig, PrimitiveTransformation, PrivacyMetric, + ProfileGeneration, ProfileStatus, ProjectDataProfile, QuasiId, @@ -541,6 +542,7 @@ "MatchingType", "MetadataType", "NullPercentageLevel", + "ProfileGeneration", "RelationalOperator", "ResourceVisibility", "StoredInfoTypeState", diff --git a/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py b/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py index c3ababdf3b1a..558c8aab67c5 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py +++ b/packages/google-cloud-dlp/google/cloud/dlp/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.20.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py index ab3f7238afee..80b0be2c935b 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/__init__.py @@ -206,6 +206,7 @@ OutputStorageConfig, PrimitiveTransformation, PrivacyMetric, + ProfileGeneration, ProfileStatus, ProjectDataProfile, QuasiId, @@ -506,6 +507,7 @@ "PartitionId", "PrimitiveTransformation", "PrivacyMetric", + "ProfileGeneration", "ProfileStatus", "ProjectDataProfile", "QuasiId", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py index c3ababdf3b1a..558c8aab67c5 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.20.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py index 12d714861cc0..b660eb26c59b 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/__init__.py @@ -200,6 +200,7 @@ OutputStorageConfig, PrimitiveTransformation, PrivacyMetric, + ProfileGeneration, ProfileStatus, ProjectDataProfile, QuasiId, @@ -532,6 +533,7 @@ "MatchingType", "MetadataType", "NullPercentageLevel", + "ProfileGeneration", "RelationalOperator", "ResourceVisibility", "StoredInfoTypeState", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py index 86c137397e6d..fe45d8719a30 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py @@ -35,6 +35,7 @@ "TransformationResultStatusType", "TransformationContainerType", "TransformationType", + "ProfileGeneration", "BigQueryTableTypeCollection", "BigQueryTableType", "DataProfileUpdateFrequency", @@ -390,6 +391,25 @@ class TransformationType(proto.Enum): REDACT_IMAGE = 14 +class ProfileGeneration(proto.Enum): + r"""Whether a profile being created is the first generation or an + update. + + Values: + PROFILE_GENERATION_UNSPECIFIED (0): + Unused. + PROFILE_GENERATION_NEW (1): + The profile is the first profile for the + resource. + PROFILE_GENERATION_UPDATE (2): + The profile is an update to a previous + profile. + """ + PROFILE_GENERATION_UNSPECIFIED = 0 + PROFILE_GENERATION_NEW = 1 + PROFILE_GENERATION_UPDATE = 2 + + class BigQueryTableTypeCollection(proto.Enum): r"""Over time new types may be added. Currently VIEW, MATERIALIZED_VIEW, and SNAPSHOT are not supported. @@ -7807,6 +7827,11 @@ class DataProfileAction(proto.Message): pub_sub_notification (google.cloud.dlp_v2.types.DataProfileAction.PubSubNotification): Publish a message into the Pub/Sub topic. + This field is a member of `oneof`_ ``action``. + tag_resources (google.cloud.dlp_v2.types.DataProfileAction.TagResources): + Tags the profiled resources with the + specified tag values. + This field is a member of `oneof`_ ``action``. """ @@ -7922,6 +7947,109 @@ class DetailLevel(proto.Enum): ) ) + class TagResources(proto.Message): + r"""If set, attaches the [tags] + (https://cloud.google.com/resource-manager/docs/tags/tags-overview) + provided to profiled resources. Tags support `access + control `__. + You can conditionally grant or deny access to a resource based on + whether the resource has a specific tag. + + Attributes: + tag_conditions (MutableSequence[google.cloud.dlp_v2.types.DataProfileAction.TagResources.TagCondition]): + The tags to associate with different + conditions. + profile_generations_to_tag (MutableSequence[google.cloud.dlp_v2.types.ProfileGeneration]): + The profile generations for which the tag should be attached + to resources. If you attach a tag to only new profiles, then + if the sensitivity score of a profile subsequently changes, + its tag doesn't change. By default, this field includes only + new profiles. To include both new and updated profiles for + tagging, this field should explicitly include both + ``PROFILE_GENERATION_NEW`` and + ``PROFILE_GENERATION_UPDATE``. + lower_data_risk_to_low (bool): + Whether applying a tag to a resource should lower the risk + of the profile for that resource. For example, in + conjunction with an `IAM deny + policy `__, + you can deny all principals a permission if a tag value is + present, mitigating the risk of the resource. This also + lowers the data risk of resources at the lower levels of the + resource hierarchy. For example, reducing the data risk of a + table data profile also reduces the data risk of the + constituent column data profiles. + """ + + class TagCondition(proto.Message): + r"""The tag to attach to profiles matching the condition. At most one + ``TagCondition`` can be specified per sensitivity level. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tag (google.cloud.dlp_v2.types.DataProfileAction.TagResources.TagValue): + The tag value to attach to resources. + sensitivity_score (google.cloud.dlp_v2.types.SensitivityScore): + Conditions attaching the tag to a resource on + its profile having this sensitivity score. + + This field is a member of `oneof`_ ``type``. + """ + + tag: "DataProfileAction.TagResources.TagValue" = proto.Field( + proto.MESSAGE, + number=1, + message="DataProfileAction.TagResources.TagValue", + ) + sensitivity_score: storage.SensitivityScore = proto.Field( + proto.MESSAGE, + number=2, + oneof="type", + message=storage.SensitivityScore, + ) + + class TagValue(proto.Message): + r"""A value of a tag. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + namespaced_value (str): + The namespaced name for the tag value to attach to + resources. Must be in the format + ``{parent_id}/{tag_key_short_name}/{short_name}``, for + example, "123456/environment/prod". + + This field is a member of `oneof`_ ``format``. + """ + + namespaced_value: str = proto.Field( + proto.STRING, + number=1, + oneof="format", + ) + + tag_conditions: MutableSequence[ + "DataProfileAction.TagResources.TagCondition" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DataProfileAction.TagResources.TagCondition", + ) + profile_generations_to_tag: MutableSequence[ + "ProfileGeneration" + ] = proto.RepeatedField( + proto.ENUM, + number=2, + enum="ProfileGeneration", + ) + lower_data_risk_to_low: bool = proto.Field( + proto.BOOL, + number=3, + ) + export_data: Export = proto.Field( proto.MESSAGE, number=1, @@ -7934,6 +8062,12 @@ class DetailLevel(proto.Enum): oneof="action", message=PubSubNotification, ) + tag_resources: TagResources = proto.Field( + proto.MESSAGE, + number=8, + oneof="action", + message=TagResources, + ) class DataProfileJobConfig(proto.Message): diff --git a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json index f25a53efeacd..4da85d5c6cd9 100644 --- a/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json +++ b/packages/google-cloud-dlp/samples/generated_samples/snippet_metadata_google.privacy.dlp.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-dlp", - "version": "3.20.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py index 2ddd49ed275f..558c8aab67c5 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py index 2ddd49ed275f..558c8aab67c5 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py index 2d3886dfb4d4..2f9f2e74d987 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/document_processor_service.py @@ -268,6 +268,9 @@ class ProcessRequest(proto.Message): underscores, and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter. + imageless_mode (bool): + Optional. Option to remove images from the + document. """ inline_document: gcd_document.Document = proto.Field( @@ -311,6 +314,10 @@ class ProcessRequest(proto.Message): proto.STRING, number=10, ) + imageless_mode: bool = proto.Field( + proto.BOOL, + number=11, + ) class HumanReviewStatus(proto.Message): diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/processor.py b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/processor.py index 7f6bea22ff3d..bf694ed59168 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1/types/processor.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1/types/processor.py @@ -76,6 +76,9 @@ class ProcessorVersion(proto.Message): Output only. Reserved for future use. satisfies_pzi (bool): Output only. Reserved for future use. + gen_ai_model_info (google.cloud.documentai_v1.types.ProcessorVersion.GenAiModelInfo): + Output only. Information about Generative AI + model-based processor versions. """ class State(proto.Enum): @@ -155,6 +158,102 @@ class DeprecationInfo(proto.Message): number=2, ) + class GenAiModelInfo(proto.Message): + r"""Information about Generative AI model-based processor + versions. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + foundation_gen_ai_model_info (google.cloud.documentai_v1.types.ProcessorVersion.GenAiModelInfo.FoundationGenAiModelInfo): + Information for a pretrained Google-managed + foundation model. + + This field is a member of `oneof`_ ``model_info``. + custom_gen_ai_model_info (google.cloud.documentai_v1.types.ProcessorVersion.GenAiModelInfo.CustomGenAiModelInfo): + Information for a custom Generative AI model + created by the user. + + This field is a member of `oneof`_ ``model_info``. + """ + + class FoundationGenAiModelInfo(proto.Message): + r"""Information for a pretrained Google-managed foundation model. + + Attributes: + finetuning_allowed (bool): + Whether finetuning is allowed for this base + processor version. + min_train_labeled_documents (int): + The minimum number of labeled documents in + the training dataset required for finetuning. + """ + + finetuning_allowed: bool = proto.Field( + proto.BOOL, + number=1, + ) + min_train_labeled_documents: int = proto.Field( + proto.INT32, + number=2, + ) + + class CustomGenAiModelInfo(proto.Message): + r"""Information for a custom Generative AI model created by the user. + These are created with ``Create New Version`` in either the + ``Call foundation model`` or ``Fine tuning`` tabs. + + Attributes: + custom_model_type (google.cloud.documentai_v1.types.ProcessorVersion.GenAiModelInfo.CustomGenAiModelInfo.CustomModelType): + The type of custom model created by the user. + base_processor_version_id (str): + The base processor version ID for the custom + model. + """ + + class CustomModelType(proto.Enum): + r"""The type of custom model created by the user. + + Values: + CUSTOM_MODEL_TYPE_UNSPECIFIED (0): + The model type is unspecified. + VERSIONED_FOUNDATION (1): + The model is a versioned foundation model. + FINE_TUNED (2): + The model is a finetuned foundation model. + """ + CUSTOM_MODEL_TYPE_UNSPECIFIED = 0 + VERSIONED_FOUNDATION = 1 + FINE_TUNED = 2 + + custom_model_type: "ProcessorVersion.GenAiModelInfo.CustomGenAiModelInfo.CustomModelType" = proto.Field( + proto.ENUM, + number=1, + enum="ProcessorVersion.GenAiModelInfo.CustomGenAiModelInfo.CustomModelType", + ) + base_processor_version_id: str = proto.Field( + proto.STRING, + number=2, + ) + + foundation_gen_ai_model_info: "ProcessorVersion.GenAiModelInfo.FoundationGenAiModelInfo" = proto.Field( + proto.MESSAGE, + number=1, + oneof="model_info", + message="ProcessorVersion.GenAiModelInfo.FoundationGenAiModelInfo", + ) + custom_gen_ai_model_info: "ProcessorVersion.GenAiModelInfo.CustomGenAiModelInfo" = proto.Field( + proto.MESSAGE, + number=2, + oneof="model_info", + message="ProcessorVersion.GenAiModelInfo.CustomGenAiModelInfo", + ) + name: str = proto.Field( proto.STRING, number=1, @@ -213,6 +312,11 @@ class DeprecationInfo(proto.Message): proto.BOOL, number=17, ) + gen_ai_model_info: GenAiModelInfo = proto.Field( + proto.MESSAGE, + number=18, + message=GenAiModelInfo, + ) class ProcessorVersionAlias(proto.Message): diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py index 2ddd49ed275f..558c8aab67c5 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta2/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py index 2ddd49ed275f..558c8aab67c5 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.30.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_service.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_service.py index 86af095d60ab..5fd1139ddcfb 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_service.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_service.py @@ -396,8 +396,10 @@ class ListDocumentsRequest(proto.Message): https://google.aip.dev/160. Currently support query strings are: + ------------------------------------ + + ``SplitType=DATASET_SPLIT_TEST|DATASET_SPLIT_TRAIN|DATASET_SPLIT_UNASSIGNED`` - - ``SplitType=DATASET_SPLIT_TEST|DATASET_SPLIT_TRAIN|DATASET_SPLIT_UNASSIGNED`` - ``LabelingState=DOCUMENT_LABELED|DOCUMENT_UNLABELED|DOCUMENT_AUTO_LABELED`` - ``DisplayName=\"file_name.pdf\"`` - ``EntityType=abc/def`` diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json index f5d1bc9baefd..96d60af285a2 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.30.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json index b00e756a165b..ef56bd7e3eb3 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.30.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json index 50a216990bae..f47545a8ed3e 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-documentai", - "version": "2.30.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-documentai/scripts/fixup_documentai_v1_keywords.py b/packages/google-cloud-documentai/scripts/fixup_documentai_v1_keywords.py index 6f1be661e967..97a9e91557e9 100644 --- a/packages/google-cloud-documentai/scripts/fixup_documentai_v1_keywords.py +++ b/packages/google-cloud-documentai/scripts/fixup_documentai_v1_keywords.py @@ -56,7 +56,7 @@ class documentaiCallTransformer(cst.CSTTransformer): 'list_processors': ('parent', 'page_size', 'page_token', ), 'list_processor_types': ('parent', 'page_size', 'page_token', ), 'list_processor_versions': ('parent', 'page_size', 'page_token', ), - 'process_document': ('name', 'inline_document', 'raw_document', 'gcs_document', 'skip_human_review', 'field_mask', 'process_options', 'labels', ), + 'process_document': ('name', 'inline_document', 'raw_document', 'gcs_document', 'skip_human_review', 'field_mask', 'process_options', 'labels', 'imageless_mode', ), 'review_document': ('human_review_config', 'inline_document', 'enable_schema_validation', 'priority', 'document_schema', ), 'set_default_processor_version': ('processor', 'default_processor_version', ), 'train_processor_version': ('parent', 'processor_version', 'custom_document_extraction_options', 'foundation_model_tuning_options', 'document_schema', 'input_data', 'base_processor_version', ), diff --git a/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py b/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py index c6ac98bede4c..558c8aab67c5 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py +++ b/packages/google-cloud-network-management/google/cloud/network_management/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.17.3" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py index c6ac98bede4c..558c8aab67c5 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py +++ b/packages/google-cloud-network-management/google/cloud/network_management_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.17.3" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py index 4f46fe720b10..b500fa10e786 100644 --- a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py +++ b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py @@ -221,7 +221,7 @@ class Endpoint(proto.Message): provide forwarding information in the control plane. Format: - projects/{project}/global/forwardingRules/{id} + projects/{project}/global/forwardingRules/{id} or projects/{project}/regions/{region}/forwardingRules/{id} forwarding_rule_target (google.cloud.network_management_v1.types.Endpoint.ForwardingRuleTarget): diff --git a/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json b/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json index 0347d916da81..21f45711959c 100644 --- a/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json +++ b/packages/google-cloud-network-management/samples/generated_samples/snippet_metadata_google.cloud.networkmanagement.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-management", - "version": "1.17.3" + "version": "0.1.0" }, "snippets": [ {