From 8ef3f5590a21c8e06617a2623921b123ab9a39bf Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Fri, 7 May 2021 14:00:46 -0700 Subject: [PATCH 01/10] docs: add Admin API samples for account management methods --- samples/account_summaries_list.py | 55 ++++ samples/account_summaries_list_test.py | 21 ++ samples/accounts_delete.py | 52 ++++ samples/accounts_delete_test.py | 27 ++ samples/accounts_get.py | 57 +++++ samples/accounts_get_data_sharing_settings.py | 60 +++++ ...accounts_get_data_sharing_settings_test.py | 24 ++ samples/accounts_get_test.py | 24 ++ samples/accounts_list.py | 48 ++++ samples/accounts_list_test.py | 20 ++ samples/accounts_provision_account_ticket.py | 89 +++++++ .../accounts_provision_account_ticket_test.py | 23 ++ samples/accounts_update.py | 69 +++++ samples/accounts_update_test.py | 26 ++ samples/noxfile.py | 236 ++++++++++++++++++ samples/noxfile_config.py | 23 ++ samples/noxfile_config_test.py | 0 samples/requirements.txt | 2 + 18 files changed, 856 insertions(+) create mode 100644 samples/account_summaries_list.py create mode 100644 samples/account_summaries_list_test.py create mode 100644 samples/accounts_delete.py create mode 100644 samples/accounts_delete_test.py create mode 100644 samples/accounts_get.py create mode 100644 samples/accounts_get_data_sharing_settings.py create mode 100644 samples/accounts_get_data_sharing_settings_test.py create mode 100644 samples/accounts_get_test.py create mode 100644 samples/accounts_list.py create mode 100644 samples/accounts_list_test.py create mode 100644 samples/accounts_provision_account_ticket.py create mode 100644 samples/accounts_provision_account_ticket_test.py create mode 100644 samples/accounts_update.py create mode 100644 samples/accounts_update_test.py create mode 100644 samples/noxfile.py create mode 100644 samples/noxfile_config.py create mode 100644 samples/noxfile_config_test.py create mode 100644 samples/requirements.txt diff --git a/samples/account_summaries_list.py b/samples/account_summaries_list.py new file mode 100644 index 00000000..faf5c929 --- /dev/null +++ b/samples/account_summaries_list.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints summaries of +all accounts accessible by the caller. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accountSummaries/list +for more information. +""" +# [START analyticsadmin_account_summaries_list] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + list_account_summaries() + + +def list_account_summaries(): + """Returns summaries of all accounts accessible by the caller.""" + client = AnalyticsAdminServiceClient() + results = client.list_account_summaries() + + print("Result:") + for account_summary in results: + print("-- Account --") + print(f"Resource name: {account_summary.name}") + print(f"Account name: {account_summary.account}") + print(f"Display name: {account_summary.display_name}") + print() + for property_summary in account_summary.property_summaries: + print("-- Property --") + print(f"Property resource name: {property_summary.property}") + print(f"Property display name: {property_summary.display_name}") + print() + + +# [END analyticsadmin_account_summaries_list] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/account_summaries_list_test.py b/samples/account_summaries_list_test.py new file mode 100644 index 00000000..46a490c1 --- /dev/null +++ b/samples/account_summaries_list_test.py @@ -0,0 +1,21 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +import account_summaries_list + + +def test_account_summaries_list(capsys): + account_summaries_list.list_account_summaries() + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_delete.py b/samples/accounts_delete.py new file mode 100644 index 00000000..d8f21536 --- /dev/null +++ b/samples/accounts_delete.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which deletes a Google +Analytics account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/delete +for more information. +""" +# [START analyticsadmin_accounts_delete] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + delete_account(account_id) + + +def delete_account(account_id): + """Deletes the Google Analytics account.""" + client = AnalyticsAdminServiceClient() + client.delete_account(name=f"accounts/{account_id}") + print("Account deleted") + + +# [END analyticsadmin_accounts_delete] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_delete_test.py b/samples/accounts_delete_test.py new file mode 100644 index 00000000..5df9cc7f --- /dev/null +++ b/samples/accounts_delete_test.py @@ -0,0 +1,27 @@ +# +# 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. + +import pytest + +import accounts_delete + + +FAKE_ACCOUNT_ID = "1" + + +def test_accounts_delete(): + # This test ensures that the call is valid and reaches the server. No + # account is being deleted during the test as it is not trivial to + # provision a new account for testing. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_delete.delete_account(FAKE_ACCOUNT_ID) diff --git a/samples/accounts_get.py b/samples/accounts_get.py new file mode 100644 index 00000000..f23521ae --- /dev/null +++ b/samples/accounts_get.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints the Google +Analytics account data. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/get +for more information. +""" +# [START analyticsadmin_accounts_get] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + get_account(account_id) + + +def get_account(account_id): + """Retrieves the Google Analytics account data.""" + client = AnalyticsAdminServiceClient() + account = client.get_account(name=f"accounts/{account_id}") + + print("Result:") + print_account(account) + + +def print_account(account): + """Prints account data.""" + print(f"Resource name: {account.name}") + print(f"Display name: {account.display_name}") + print(f"Region code: {account.region_code}") + print(f"Create time: {account.create_time}") + print(f"Update time: {account.update_time}") + + +# [END analyticsadmin_accounts_get] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_get_data_sharing_settings.py b/samples/accounts_get_data_sharing_settings.py new file mode 100644 index 00000000..4fe707c0 --- /dev/null +++ b/samples/accounts_get_data_sharing_settings.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints the data sharing +settings on an account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/getDataSharingSettings +for more information. +""" +# [START analyticsadmin_accounts_get_data_sharing_settings] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + get_data_sharing_settings(account_id) + + +def get_data_sharing_settings(account_id): + """Gets data sharing settings on an account.""" + client = AnalyticsAdminServiceClient() + data_sharing_settings = client.get_data_sharing_settings( + name=f"accounts/{account_id}/dataSharingSettings" + ) + + print("Result:") + print(f"Resource name: {data_sharing_settings.name}") + print( + f"Sharing with Google support enabled: {data_sharing_settings.sharing_with_google_support_enabled}" + ) + print( + f"Sharing with Google assigned sales enabled: {data_sharing_settings.sharing_with_google_assigned_sales_enabled}" + ) + print( + f"Sharing with others enabled: {data_sharing_settings.sharing_with_others_enabled}" + ) + + +# [END analyticsadmin_accounts_get_data_sharing_settings] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_get_data_sharing_settings_test.py b/samples/accounts_get_data_sharing_settings_test.py new file mode 100644 index 00000000..efedd6bb --- /dev/null +++ b/samples/accounts_get_data_sharing_settings_test.py @@ -0,0 +1,24 @@ +# +# 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. + +import os + +import accounts_get_data_sharing_settings + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") + + +def test_accounts_get_data_sharing_settings(capsys): + accounts_get_data_sharing_settings.get_data_sharing_settings(TEST_ACCOUNT_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_get_test.py b/samples/accounts_get_test.py new file mode 100644 index 00000000..4c180838 --- /dev/null +++ b/samples/accounts_get_test.py @@ -0,0 +1,24 @@ +# +# 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. + +import os + +import accounts_get + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") + + +def test_accounts_get(capsys): + accounts_get.get_account(TEST_ACCOUNT_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_list.py b/samples/accounts_list.py new file mode 100644 index 00000000..39d4d0b4 --- /dev/null +++ b/samples/accounts_list.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints the Google +Analytics accounts available to the current user. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/list +for more information. +""" +# [START analyticsadmin_accounts_list] +from google.analytics.admin import AnalyticsAdminServiceClient + +from accounts_get import print_account + + +def run_sample(): + """Runs the sample.""" + list_accounts() + + +def list_accounts(): + """Lists the Google Analytics accounts available to the current user.""" + client = AnalyticsAdminServiceClient() + results = client.list_accounts() + + print("Result:") + for account in results: + print_account(account) + + +# [END analyticsadmin_accounts_list] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_list_test.py b/samples/accounts_list_test.py new file mode 100644 index 00000000..33598158 --- /dev/null +++ b/samples/accounts_list_test.py @@ -0,0 +1,20 @@ +# +# 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. + +import accounts_list + + +def test_accounts_list(capsys): + accounts_list.list_accounts() + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_provision_account_ticket.py b/samples/accounts_provision_account_ticket.py new file mode 100644 index 00000000..8741cfcc --- /dev/null +++ b/samples/accounts_provision_account_ticket.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which provisions the Google +Analytics account creation ticket and prints the Terms of Service link that +can be used by an end user to complete the account creation flow. + +This sample invokes the provision_account_ticket() method of the Google +Analytics Admin API to start the Google Analytics account creation +process for a user. This method returns an account ticket which shall be used +to generate the Terms Of Service url that an end user should visit in order +to accept the Terms and complete the account creation flow. + +You have to authenticate as an end user in order to run this sample. Only +the authenticated user will be able to use the Terms of Service url generated +as part of the account provisioning flow. + +To authenticate as an end user prior to running this sample, use the +gcloud tool: + + gcloud auth application-default login --scopes=https://www.googleapis.com/auth/analytics.edit --client-id-file=PATH_TO_YOUR_CLIENT_SECRET_JSON + + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/provisionAccountTicket +for more information. +""" +# [START analyticsadmin_accounts_provision_account_ticket] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import Account +from google.analytics.admin_v1alpha.types import ProvisionAccountTicketRequest + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with a redirect URI where the user + # will be sent after accepting Terms of Service. Must be configured in + # Developers Console as a Redirect URI + redirect_uri = "YOUR-REDIRECT-URI" + + provision_account_ticket(redirect_uri) + + +def provision_account_ticket(redirect_uri): + """Provisions the Google Analytics account creation ticket.""" + client = AnalyticsAdminServiceClient() + response = client.provision_account_ticket( + ProvisionAccountTicketRequest( + account=Account(display_name="Test Account", region_code="US"), + redirect_uri=redirect_uri, + ) + ) + + print("Result:") + print(f"Account ticket id: {response.account_ticket_id}") + print( + f"You can now open the following URL to complete the account creation:" + f"https://analytics.google.com/analytics/web/?provisioningSignup=false#/termsofservice/{response.account_ticket_id}" + ) + print() + print( + "Attention: make sure your browser is signed in to the same user " + "account that was used to provision the ticket." + ) + + +# [END analyticsadmin_accounts_provision_account_ticket] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_provision_account_ticket_test.py b/samples/accounts_provision_account_ticket_test.py new file mode 100644 index 00000000..45771966 --- /dev/null +++ b/samples/accounts_provision_account_ticket_test.py @@ -0,0 +1,23 @@ +# +# 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. + +import accounts_provision_account_ticket + + +TEST_REDIRECT_URL = "https://www.google.com" + + +def test_accounts_provision_account_ticket(capsys): + accounts_provision_account_ticket.provision_account_ticket(TEST_REDIRECT_URL) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_update.py b/samples/accounts_update.py new file mode 100644 index 00000000..52ca5371 --- /dev/null +++ b/samples/accounts_update.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which updates the Google +Analytics account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/update +for more information. +""" +# [START analyticsadmin_accounts_update] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import Account +from google.protobuf.field_mask_pb2 import FieldMask + +from accounts_get import print_account + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + update_account(account_id) + + +def update_account(account_id): + """Updates the Google Analytics account.""" + client = AnalyticsAdminServiceClient() + # This call updates the display name and region code of the account, as + # indicated by the value of the `update_mask` field. + # The account to update is specified in the `name` field of the `Account` + # instance. + account = client.update_account( + account=Account( + name=f"accounts/{account_id}", + display_name="This is a test account", + region_code="US", + ), + update_mask=FieldMask(paths=["display_name", "region_code"]), + ) + + print("Result:") + print_account(account) + + +# [END analyticsadmin_accounts_update] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_update_test.py b/samples/accounts_update_test.py new file mode 100644 index 00000000..abc36ecb --- /dev/null +++ b/samples/accounts_update_test.py @@ -0,0 +1,26 @@ +# +# 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. + +import pytest + +import accounts_update + + +FAKE_ACCOUNT_ID = "1" + + +def test_accounts_update(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_update.update_account(FAKE_ACCOUNT_ID) diff --git a/samples/noxfile.py b/samples/noxfile.py new file mode 100644 index 00000000..841b8c90 --- /dev/null +++ b/samples/noxfile.py @@ -0,0 +1,236 @@ +# Copyright 2020 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. + +from __future__ import print_function + +import os +from pathlib import Path +import sys + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +# Copy `noxfile_config.py` to your directory and modify it instead. + + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append(".") + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars(): + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG["gcloud_project_env"] + # This should error out if not set. + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] + ret["GCLOUD_PROJECT"] = os.environ[env_key] # deprecated + + # Apply user supplied envs. + ret.update(TEST_CONFIG["envs"]) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to tested samples. +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +# +# Style Checks +# + + +def _determine_local_import_names(start_dir): + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session): + session.install("flake8", "flake8-import-order") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + ".", + ] + session.run("flake8", *args) + + +# +# Black +# + + +@nox.session +def blacken(session): + session.install("black") + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + session.run("black", *python_files) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests(session, post_install=None): + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars() + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session): + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) + + +# +# Readmegen +# + + +def _get_repo_root(): + """Returns the root folder of the project.""" + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session, path): + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/samples/noxfile_config.py b/samples/noxfile_config.py new file mode 100644 index 00000000..b883a88e --- /dev/null +++ b/samples/noxfile_config.py @@ -0,0 +1,23 @@ +TEST_CONFIG_OVERRIDE = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": True, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": { + "GA_TEST_PROPERTY_ID": "222596558", + "GA_TEST_ACCOUNT_ID": "123", + "GA_TEST_USER_LINK_ID": "123", + "GA_TEST_ANDROID_APP_DATA_STREAM_ID": "123", + "GA_TEST_IOS_APP_DATA_STREAM_ID": "123", + "GA_TEST_WEB_DATA_STREAM_ID": "123", + }, +} diff --git a/samples/noxfile_config_test.py b/samples/noxfile_config_test.py new file mode 100644 index 00000000..e69de29b diff --git a/samples/requirements.txt b/samples/requirements.txt new file mode 100644 index 00000000..11e7e0fe --- /dev/null +++ b/samples/requirements.txt @@ -0,0 +1,2 @@ +google-analytics-admin==0.2.0 +google-auth-oauthlib==0.4.4 \ No newline at end of file From 43686341ff316c93171fa860e460b9706bdf06b0 Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Fri, 14 May 2021 14:28:31 -0700 Subject: [PATCH 02/10] update copyright and remove redundant run_sample method --- samples/account_summaries_list.py | 9 ++------- samples/account_summaries_list_test.py | 2 +- samples/accounts_delete.py | 2 +- samples/accounts_delete_test.py | 1 + samples/accounts_get.py | 2 +- samples/accounts_get_data_sharing_settings.py | 2 +- samples/accounts_get_data_sharing_settings_test.py | 1 + samples/accounts_get_test.py | 1 + samples/accounts_list.py | 9 ++------- samples/accounts_list_test.py | 1 + samples/accounts_provision_account_ticket.py | 2 +- samples/accounts_provision_account_ticket_test.py | 1 + samples/accounts_update.py | 2 +- samples/accounts_update_test.py | 1 + 14 files changed, 16 insertions(+), 20 deletions(-) diff --git a/samples/account_summaries_list.py b/samples/account_summaries_list.py index faf5c929..cb608168 100644 --- a/samples/account_summaries_list.py +++ b/samples/account_summaries_list.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -24,11 +24,6 @@ from google.analytics.admin import AnalyticsAdminServiceClient -def run_sample(): - """Runs the sample.""" - list_account_summaries() - - def list_account_summaries(): """Returns summaries of all accounts accessible by the caller.""" client = AnalyticsAdminServiceClient() @@ -52,4 +47,4 @@ def list_account_summaries(): if __name__ == "__main__": - run_sample() + list_account_summaries() diff --git a/samples/account_summaries_list_test.py b/samples/account_summaries_list_test.py index 46a490c1..d97ef6dc 100644 --- a/samples/account_summaries_list_test.py +++ b/samples/account_summaries_list_test.py @@ -1,4 +1,4 @@ -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_delete.py b/samples/accounts_delete.py index d8f21536..a7dc3f8c 100644 --- a/samples/accounts_delete.py +++ b/samples/accounts_delete.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_delete_test.py b/samples/accounts_delete_test.py index 5df9cc7f..0458fefc 100644 --- a/samples/accounts_delete_test.py +++ b/samples/accounts_delete_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_get.py b/samples/accounts_get.py index f23521ae..2d7982fb 100644 --- a/samples/accounts_get.py +++ b/samples/accounts_get.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_get_data_sharing_settings.py b/samples/accounts_get_data_sharing_settings.py index 4fe707c0..7fbee3d3 100644 --- a/samples/accounts_get_data_sharing_settings.py +++ b/samples/accounts_get_data_sharing_settings.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_get_data_sharing_settings_test.py b/samples/accounts_get_data_sharing_settings_test.py index efedd6bb..6232fc72 100644 --- a/samples/accounts_get_data_sharing_settings_test.py +++ b/samples/accounts_get_data_sharing_settings_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_get_test.py b/samples/accounts_get_test.py index 4c180838..5c0c1313 100644 --- a/samples/accounts_get_test.py +++ b/samples/accounts_get_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_list.py b/samples/accounts_list.py index 39d4d0b4..f69869e4 100644 --- a/samples/accounts_list.py +++ b/samples/accounts_list.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -26,11 +26,6 @@ from accounts_get import print_account -def run_sample(): - """Runs the sample.""" - list_accounts() - - def list_accounts(): """Lists the Google Analytics accounts available to the current user.""" client = AnalyticsAdminServiceClient() @@ -45,4 +40,4 @@ def list_accounts(): if __name__ == "__main__": - run_sample() + list_accounts() diff --git a/samples/accounts_list_test.py b/samples/accounts_list_test.py index 33598158..379c73b3 100644 --- a/samples/accounts_list_test.py +++ b/samples/accounts_list_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_provision_account_ticket.py b/samples/accounts_provision_account_ticket.py index 8741cfcc..f79e7e03 100644 --- a/samples/accounts_provision_account_ticket.py +++ b/samples/accounts_provision_account_ticket.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_provision_account_ticket_test.py b/samples/accounts_provision_account_ticket_test.py index 45771966..e08f9402 100644 --- a/samples/accounts_provision_account_ticket_test.py +++ b/samples/accounts_provision_account_ticket_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_update.py b/samples/accounts_update.py index 52ca5371..d3f3b1af 100644 --- a/samples/accounts_update.py +++ b/samples/accounts_update.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Copyright 2021 Google Inc. All Rights Reserved. +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_update_test.py b/samples/accounts_update_test.py index abc36ecb..18c5f551 100644 --- a/samples/accounts_update_test.py +++ b/samples/accounts_update_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 381a8d925628cb1f8fe5a081a27ad6245b81859e Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Fri, 14 May 2021 14:29:13 -0700 Subject: [PATCH 03/10] update noxfile template and set enforce_type_hints=False --- samples/noxfile.py | 78 +++++++++++++++++++++++---------------- samples/noxfile_config.py | 2 +- 2 files changed, 48 insertions(+), 32 deletions(-) diff --git a/samples/noxfile.py b/samples/noxfile.py index 841b8c90..804f957e 100644 --- a/samples/noxfile.py +++ b/samples/noxfile.py @@ -1,4 +1,4 @@ -# Copyright 2020 Google LLC +# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ import os from pathlib import Path import sys +from typing import Callable, Dict, List, Optional import nox @@ -37,22 +38,28 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - "ignored_versions": ["2.7"], + 'ignored_versions': ["2.7"], + + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + 'enforce_type_hints': False, + # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - "envs": {}, + 'envs': {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") + sys.path.append('.') from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -62,27 +69,27 @@ TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) -def get_pytest_env_vars(): +def get_pytest_env_vars() -> Dict[str, str]: """Returns a dict for pytest invocation.""" ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] + env_key = TEST_CONFIG['gcloud_project_env'] # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - ret["GCLOUD_PROJECT"] = os.environ[env_key] # deprecated + ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] + ret['GCLOUD_PROJECT'] = os.environ[env_key] # deprecated # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) + ret.update(TEST_CONFIG['envs']) return ret # DO NOT EDIT - automatically generated. # All versions used to tested samples. -ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8", "3.9"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] +IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) @@ -92,7 +99,7 @@ def get_pytest_env_vars(): # -def _determine_local_import_names(start_dir): +def _determine_local_import_names(start_dir: str) -> List[str]: """Determines all import names that should be considered "local". This is used when running the linter to insure that import order is @@ -103,8 +110,8 @@ def _determine_local_import_names(start_dir): basename for basename, extension in file_ext_pairs if extension == ".py" - or os.path.isdir(os.path.join(start_dir, basename)) - and basename not in ("__pycache__") + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") ] @@ -130,14 +137,17 @@ def _determine_local_import_names(start_dir): @nox.session -def lint(session): - session.install("flake8", "flake8-import-order") +def lint(session: nox.sessions.Session) -> None: + if not TEST_CONFIG['enforce_type_hints']: + session.install("flake8", "flake8-import-order") + else: + session.install("flake8", "flake8-import-order", "flake8-annotations") local_names = _determine_local_import_names(".") args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - ".", + "." ] session.run("flake8", *args) @@ -146,9 +156,8 @@ def lint(session): # Black # - @nox.session -def blacken(session): +def blacken(session: nox.sessions.Session) -> None: session.install("black") python_files = [path for path in os.listdir(".") if path.endswith(".py")] @@ -163,13 +172,19 @@ def blacken(session): PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session, post_install=None): +def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) @@ -189,14 +204,14 @@ def _session_tests(session, post_install=None): @nox.session(python=ALL_VERSIONS) -def py(session): +def py(session: nox.sessions.Session) -> None: """Runs py.test for a sample using the specified version of Python.""" if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) + session.skip("SKIPPED: {} tests are disabled for this sample.".format( + session.python + )) # @@ -204,9 +219,10 @@ def py(session): # -def _get_repo_root(): - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. +def _get_repo_root() -> Optional[str]: + """ Returns the root folder of the project. """ + # Get root of this repository. + # Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) for i in range(10): if p is None: @@ -222,7 +238,7 @@ def _get_repo_root(): @nox.session @nox.parametrize("path", GENERATED_READMES) -def readmegen(session, path): +def readmegen(session: nox.sessions.Session, path: str) -> None: """(Re-)generates the readme for a sample.""" session.install("jinja2", "pyyaml") dir_ = os.path.dirname(path) diff --git a/samples/noxfile_config.py b/samples/noxfile_config.py index b883a88e..59eca522 100644 --- a/samples/noxfile_config.py +++ b/samples/noxfile_config.py @@ -3,7 +3,7 @@ "ignored_versions": ["2.7"], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - "enforce_type_hints": True, + "enforce_type_hints": False, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string From 85a38ec3a8288c4d5f3541f38b4130af555aef0e Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Fri, 14 May 2021 14:58:47 -0700 Subject: [PATCH 04/10] add type annotations --- samples/accounts_delete.py | 2 +- samples/accounts_get.py | 4 ++-- samples/accounts_get_data_sharing_settings.py | 2 +- samples/accounts_provision_account_ticket.py | 2 +- samples/accounts_update.py | 2 +- samples/noxfile_config.py | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/samples/accounts_delete.py b/samples/accounts_delete.py index a7dc3f8c..7c6f7afa 100644 --- a/samples/accounts_delete.py +++ b/samples/accounts_delete.py @@ -38,7 +38,7 @@ def run_sample(): delete_account(account_id) -def delete_account(account_id): +def delete_account(account_id: str): """Deletes the Google Analytics account.""" client = AnalyticsAdminServiceClient() client.delete_account(name=f"accounts/{account_id}") diff --git a/samples/accounts_get.py b/samples/accounts_get.py index 2d7982fb..d7cbf927 100644 --- a/samples/accounts_get.py +++ b/samples/accounts_get.py @@ -32,7 +32,7 @@ def run_sample(): get_account(account_id) -def get_account(account_id): +def get_account(account_id: str): """Retrieves the Google Analytics account data.""" client = AnalyticsAdminServiceClient() account = client.get_account(name=f"accounts/{account_id}") @@ -41,7 +41,7 @@ def get_account(account_id): print_account(account) -def print_account(account): +def print_account(account: str): """Prints account data.""" print(f"Resource name: {account.name}") print(f"Display name: {account.display_name}") diff --git a/samples/accounts_get_data_sharing_settings.py b/samples/accounts_get_data_sharing_settings.py index 7fbee3d3..66a8ef29 100644 --- a/samples/accounts_get_data_sharing_settings.py +++ b/samples/accounts_get_data_sharing_settings.py @@ -33,7 +33,7 @@ def run_sample(): get_data_sharing_settings(account_id) -def get_data_sharing_settings(account_id): +def get_data_sharing_settings(account_id: str): """Gets data sharing settings on an account.""" client = AnalyticsAdminServiceClient() data_sharing_settings = client.get_data_sharing_settings( diff --git a/samples/accounts_provision_account_ticket.py b/samples/accounts_provision_account_ticket.py index f79e7e03..3a574224 100644 --- a/samples/accounts_provision_account_ticket.py +++ b/samples/accounts_provision_account_ticket.py @@ -59,7 +59,7 @@ def run_sample(): provision_account_ticket(redirect_uri) -def provision_account_ticket(redirect_uri): +def provision_account_ticket(redirect_uri: str): """Provisions the Google Analytics account creation ticket.""" client = AnalyticsAdminServiceClient() response = client.provision_account_ticket( diff --git a/samples/accounts_update.py b/samples/accounts_update.py index d3f3b1af..e3ae56ed 100644 --- a/samples/accounts_update.py +++ b/samples/accounts_update.py @@ -42,7 +42,7 @@ def run_sample(): update_account(account_id) -def update_account(account_id): +def update_account(account_id: str): """Updates the Google Analytics account.""" client = AnalyticsAdminServiceClient() # This call updates the display name and region code of the account, as diff --git a/samples/noxfile_config.py b/samples/noxfile_config.py index 59eca522..b883a88e 100644 --- a/samples/noxfile_config.py +++ b/samples/noxfile_config.py @@ -3,7 +3,7 @@ "ignored_versions": ["2.7"], # Old samples are opted out of enforcing Python type hints # All new samples should feature them - "enforce_type_hints": False, + "enforce_type_hints": True, # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string From 42f158fd897e789accdbf97d7a2106096fdff164 Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Wed, 19 May 2021 13:51:27 -0700 Subject: [PATCH 05/10] docs: add Admin API samples for account user link management methods --- samples/accounts_user_links_audit.py | 59 ++++++++++++++ samples/accounts_user_links_audit_test.py | 26 ++++++ samples/accounts_user_links_batch_create.py | 79 ++++++++++++++++++ .../accounts_user_links_batch_create_test.py | 32 ++++++++ samples/accounts_user_links_batch_delete.py | 68 ++++++++++++++++ .../accounts_user_links_batch_delete_test.py | 30 +++++++ samples/accounts_user_links_batch_get.py | 63 +++++++++++++++ samples/accounts_user_links_batch_get_test.py | 28 +++++++ samples/accounts_user_links_batch_update.py | 81 +++++++++++++++++++ .../accounts_user_links_batch_update_test.py | 29 +++++++ samples/accounts_user_links_create.py | 71 ++++++++++++++++ samples/accounts_user_links_create_test.py | 31 +++++++ samples/accounts_user_links_delete.py | 62 ++++++++++++++ samples/accounts_user_links_delete_test.py | 29 +++++++ samples/accounts_user_links_get.py | 63 +++++++++++++++ samples/accounts_user_links_get_test.py | 25 ++++++ samples/accounts_user_links_list.py | 52 ++++++++++++ samples/accounts_user_links_list_test.py | 24 ++++++ samples/accounts_user_links_update.py | 70 ++++++++++++++++ samples/accounts_user_links_update_test.py | 29 +++++++ samples/noxfile_config_test.py | 0 21 files changed, 951 insertions(+) create mode 100644 samples/accounts_user_links_audit.py create mode 100644 samples/accounts_user_links_audit_test.py create mode 100644 samples/accounts_user_links_batch_create.py create mode 100644 samples/accounts_user_links_batch_create_test.py create mode 100644 samples/accounts_user_links_batch_delete.py create mode 100644 samples/accounts_user_links_batch_delete_test.py create mode 100644 samples/accounts_user_links_batch_get.py create mode 100644 samples/accounts_user_links_batch_get_test.py create mode 100644 samples/accounts_user_links_batch_update.py create mode 100644 samples/accounts_user_links_batch_update_test.py create mode 100644 samples/accounts_user_links_create.py create mode 100644 samples/accounts_user_links_create_test.py create mode 100644 samples/accounts_user_links_delete.py create mode 100644 samples/accounts_user_links_delete_test.py create mode 100644 samples/accounts_user_links_get.py create mode 100644 samples/accounts_user_links_get_test.py create mode 100644 samples/accounts_user_links_list.py create mode 100644 samples/accounts_user_links_list_test.py create mode 100644 samples/accounts_user_links_update.py create mode 100644 samples/accounts_user_links_update_test.py delete mode 100644 samples/noxfile_config_test.py diff --git a/samples/accounts_user_links_audit.py b/samples/accounts_user_links_audit.py new file mode 100644 index 00000000..106906a0 --- /dev/null +++ b/samples/accounts_user_links_audit.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints all user links on +an account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/audit +for more information. +""" +# [START analyticsadmin_accounts_user_links_audit] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import AuditUserLinksRequest + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + audit_account_user_links(account_id) + + +def audit_account_user_links(account_id): + """Lists all user links on an account, including implicit ones that come + from effective permissions granted by groups or organization admin roles.""" + client = AnalyticsAdminServiceClient() + + print("Result:") + for user_link in client.audit_user_links( + AuditUserLinksRequest(parent=f"accounts/{account_id}") + ): + print(f"Resource name: {user_link.name}") + print(f"Email address: {user_link.email_address}") + for direct_role in user_link.direct_roles: + print(f"Direct role: {direct_role}") + + for effective_role in user_link.effective_roles: + print(f"Effective role: {effective_role}") + print() + + +# [END analyticsadmin_accounts_user_links_audit] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_audit_test.py b/samples/accounts_user_links_audit_test.py new file mode 100644 index 00000000..d717c6c8 --- /dev/null +++ b/samples/accounts_user_links_audit_test.py @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import accounts_user_links_audit + + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") + + +def test_accounts_user_links_audit(capsys): + accounts_user_links_audit.audit_account_user_links(TEST_ACCOUNT_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_user_links_batch_create.py b/samples/accounts_user_links_batch_create.py new file mode 100644 index 00000000..600d35c8 --- /dev/null +++ b/samples/accounts_user_links_batch_create.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which creates a user link for +the account using a batch call. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/batchCreate +for more information. +""" +# [START analyticsadmin_accounts_user_links_batch_create] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import BatchCreateUserLinksRequest +from google.analytics.admin_v1alpha.types import CreateUserLinkRequest +from google.analytics.admin_v1alpha.types import UserLink + +from accounts_user_links_get import print_user_link + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with an email address of the user to + # link. This user will be given access to your account after running the + # sample. + email_address = "TEST-EMAIL-ADDRESS" + + batch_create_account_user_link(account_id, email_address) + + +def batch_create_account_user_link(account_id, email_address): + """Creates a user link for the account using a batch call.""" + client = AnalyticsAdminServiceClient() + response = client.batch_create_user_links( + BatchCreateUserLinksRequest( + parent=f"accounts/{account_id}", + requests=[ + CreateUserLinkRequest( + user_link=UserLink( + email_address=email_address, + direct_roles=["predefinedRoles/read"], + ) + ) + ], + notify_new_users=True, + ) + ) + + print("Result:") + for user_link in response.user_links: + print_user_link(user_link) + print() + + +# [END analyticsadmin_accounts_user_links_batch_create] + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_batch_create_test.py b/samples/accounts_user_links_batch_create_test.py new file mode 100644 index 00000000..5141c174 --- /dev/null +++ b/samples/accounts_user_links_batch_create_test.py @@ -0,0 +1,32 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import pytest + +import accounts_user_links_batch_create + + +FAKE_ACCOUNT_ID = "1" +TEST_EMAIL_ADDRESS = os.getenv("GA_TEST_EMAIL_ADDRESS") + + +def test_accounts_user_links_batch_create(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_user_links_batch_create.batch_create_account_user_link( + FAKE_ACCOUNT_ID, TEST_EMAIL_ADDRESS + ) diff --git a/samples/accounts_user_links_batch_delete.py b/samples/accounts_user_links_batch_delete.py new file mode 100644 index 00000000..102ad9e2 --- /dev/null +++ b/samples/accounts_user_links_batch_delete.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which deletes the user link +using a batch call. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/batchDelete +for more information. +""" +# [START analyticsadmin_accounts_user_links_batch_delete] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import BatchDeleteUserLinksRequest +from google.analytics.admin_v1alpha.types import DeleteUserLinkRequest + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics + # account user link ID (e.g. "123456") before running the sample. + account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID" + + batch_delete_account_user_link(account_id, account_user_link_id) + + +def batch_delete_account_user_link(account_id, account_user_link_id): + """Deletes the user link using a batch call.""" + client = AnalyticsAdminServiceClient() + client.batch_delete_user_links( + BatchDeleteUserLinksRequest( + parent=f"accounts/{account_id}", + requests=[ + DeleteUserLinkRequest( + name=f"accounts/{account_id}/userLinks/{account_user_link_id}" + ) + ], + ) + ) + print("User link deleted") + + +# [END analyticsadmin_accounts_user_links_batch_delete] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_batch_delete_test.py b/samples/accounts_user_links_batch_delete_test.py new file mode 100644 index 00000000..3b9eac24 --- /dev/null +++ b/samples/accounts_user_links_batch_delete_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import accounts_user_links_batch_delete + + +FAKE_ACCOUNT_ID = "1" +FAKE_ACCOUNT_USER_LINK_ID = "1" + + +def test_accounts_user_links_batch_delete(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_user_links_batch_delete.batch_delete_account_user_link( + FAKE_ACCOUNT_ID, FAKE_ACCOUNT_USER_LINK_ID + ) diff --git a/samples/accounts_user_links_batch_get.py b/samples/accounts_user_links_batch_get.py new file mode 100644 index 00000000..bbafc076 --- /dev/null +++ b/samples/accounts_user_links_batch_get.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints the details for +the account user link using a batch call. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/batchGet +for more information. +""" +# [START analyticsadmin_accounts_user_links_batch_get] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import BatchGetUserLinksRequest + +from accounts_user_links_get import print_user_link + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics + # account user link ID (e.g. "123456") before running the sample. + account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID" + + batch_get_account_user_link(account_id, account_user_link_id) + + +def batch_get_account_user_link(account_id, account_user_link_id): + """Retrieves details for the account user link using a batch call.""" + client = AnalyticsAdminServiceClient() + response = client.batch_get_user_links( + BatchGetUserLinksRequest( + parent=f"accounts/{account_id}", + names=[f"accounts/{account_id}/userLinks/{account_user_link_id}"], + ) + ) + + print("Result:") + for user_link in response.user_links: + print_user_link(user_link) + print() + + +# [END analyticsadmin_accounts_user_links_batch_get] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_batch_get_test.py b/samples/accounts_user_links_batch_get_test.py new file mode 100644 index 00000000..29775cb6 --- /dev/null +++ b/samples/accounts_user_links_batch_get_test.py @@ -0,0 +1,28 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import accounts_user_links_batch_get + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") +TEST_USER_LINK_ID = os.getenv("GA_TEST_USER_LINK_ID") + + +def test_accounts_user_links_batch_get(capsys): + accounts_user_links_batch_get.batch_get_account_user_link( + TEST_ACCOUNT_ID, TEST_USER_LINK_ID + ) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_user_links_batch_update.py b/samples/accounts_user_links_batch_update.py new file mode 100644 index 00000000..eb9e3e5c --- /dev/null +++ b/samples/accounts_user_links_batch_update.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which updates the account +user link using a batch call. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/batchUpdate +for more information. +""" +# [START analyticsadmin_accounts_user_links_batch_update] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import BatchUpdateUserLinksRequest +from google.analytics.admin_v1alpha.types import UpdateUserLinkRequest +from google.analytics.admin_v1alpha.types import UserLink + +from accounts_user_links_get import print_user_link + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics + # account user link ID (e.g. "123456") before running the sample. + account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID" + + batch_update_account_user_link(account_id, account_user_link_id) + + +def batch_update_account_user_link(account_id, account_user_link_id): + """Updates the account user link using a batch call.""" + client = AnalyticsAdminServiceClient() + # This call updates the email address and direct roles of the user link. + # The user link to update is specified in the `name` field of the `UserLink` + # instance. + response = client.batch_update_user_links( + BatchUpdateUserLinksRequest( + parent=f"accounts/{account_id}", + requests=[ + UpdateUserLinkRequest( + user_link=UserLink( + name=f"accounts/{account_id}/userLinks/{account_user_link_id}", + direct_roles=["predefinedRoles/collaborate"], + ), + ) + ], + ) + ) + + print("Result:") + for user_link in response.user_links: + print_user_link(user_link) + print() + + +# [END analyticsadmin_accounts_user_links_batch_update] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_batch_update_test.py b/samples/accounts_user_links_batch_update_test.py new file mode 100644 index 00000000..0bd9d155 --- /dev/null +++ b/samples/accounts_user_links_batch_update_test.py @@ -0,0 +1,29 @@ +# +# 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. + +import pytest + +import accounts_user_links_batch_update + + +FAKE_ACCOUNT_ID = "1" +FAKE_ACCOUNT_USER_LINK_ID = "1" + + +def test_accounts_user_links_batch_update(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_user_links_batch_update.batch_update_account_user_link( + FAKE_ACCOUNT_ID, FAKE_ACCOUNT_USER_LINK_ID + ) diff --git a/samples/accounts_user_links_create.py b/samples/accounts_user_links_create.py new file mode 100644 index 00000000..7262df35 --- /dev/null +++ b/samples/accounts_user_links_create.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which creates a user link +for the account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/create +for more information. +""" +# [START analyticsadmin_accounts_user_links_create] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import CreateUserLinkRequest +from google.analytics.admin_v1alpha.types import UserLink + +from accounts_user_links_get import print_user_link + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with an email address of the user to + # link. This user will be given access to your account after running the + # sample. + email_address = "TEST-EMAIL-ADDRESS" + + create_account_user_link(account_id, email_address) + + +def create_account_user_link(account_id, email_address): + """Creates a user link for the account.""" + client = AnalyticsAdminServiceClient() + user_link = client.create_user_link( + CreateUserLinkRequest( + parent=f"accounts/{account_id}", + user_link=UserLink( + email_address=email_address, direct_roles=["predefinedRoles/read"] + ), + notify_new_user=True, + ) + ) + + print("Result:") + print_user_link(user_link) + + +# [END analyticsadmin_accounts_user_links_create] + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_create_test.py b/samples/accounts_user_links_create_test.py new file mode 100644 index 00000000..f9ea731f --- /dev/null +++ b/samples/accounts_user_links_create_test.py @@ -0,0 +1,31 @@ +# +# 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. + +import os + +import pytest + +import accounts_user_links_create + + +FAKE_ACCOUNT_ID = "1" +TEST_EMAIL_ADDRESS = os.getenv("GA_TEST_EMAIL_ADDRESS") + + +def test_accounts_user_links_create(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_user_links_create.create_account_user_link( + FAKE_ACCOUNT_ID, TEST_EMAIL_ADDRESS + ) diff --git a/samples/accounts_user_links_delete.py b/samples/accounts_user_links_delete.py new file mode 100644 index 00000000..1263d962 --- /dev/null +++ b/samples/accounts_user_links_delete.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which deletes the user link +for the account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/delete +for more information. +""" +# [START analyticsadmin_accounts_user_links_delete] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import DeleteUserLinkRequest + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics + # account user link ID (e.g. "123456") before running the sample. + account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID" + + delete_account_user_link(account_id, account_user_link_id) + + +def delete_account_user_link(account_id, account_user_link_id): + """Deletes the user link for the account.""" + client = AnalyticsAdminServiceClient() + client.delete_user_link( + DeleteUserLinkRequest( + name=f"accounts/{account_id}/userLinks/{account_user_link_id}" + ) + ) + print("User link deleted") + + +# [END analyticsadmin_accounts_user_links_delete] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_delete_test.py b/samples/accounts_user_links_delete_test.py new file mode 100644 index 00000000..52eff4a6 --- /dev/null +++ b/samples/accounts_user_links_delete_test.py @@ -0,0 +1,29 @@ +# +# 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. + +import pytest + +import accounts_user_links_delete + + +FAKE_ACCOUNT_ID = "1" +FAKE_ACCOUNT_USER_LINK_ID = "1" + + +def test_accounts_user_links_delete(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_user_links_delete.delete_account_user_link( + FAKE_ACCOUNT_ID, FAKE_ACCOUNT_USER_LINK_ID + ) diff --git a/samples/accounts_user_links_get.py b/samples/accounts_user_links_get.py new file mode 100644 index 00000000..a9fc8b3d --- /dev/null +++ b/samples/accounts_user_links_get.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints the account user +link details. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/get +for more information. +""" +# [START analyticsadmin_accounts_user_links_get] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics + # account user link ID (e.g. "123456") before running the sample. + account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID" + + get_account_user_link(account_id, account_user_link_id) + + +def get_account_user_link(account_id, account_user_link_id): + """Retrieves the account user link details.""" + client = AnalyticsAdminServiceClient() + user_link = client.get_user_link( + name=f"accounts/{account_id}/userLinks/{account_user_link_id}" + ) + + print("Result:") + print_user_link(user_link) + + +def print_user_link(user_link): + """Prints the user link details.""" + print(f"Resource name: {user_link.name}") + print(f"Email address: {user_link.email_address}") + for direct_role in user_link.direct_roles: + print(f"Direct role: {direct_role}") + + +# [END analyticsadmin_accounts_user_links_get] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_get_test.py b/samples/accounts_user_links_get_test.py new file mode 100644 index 00000000..41d4b57a --- /dev/null +++ b/samples/accounts_user_links_get_test.py @@ -0,0 +1,25 @@ +# +# 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. + +import os + +import accounts_user_links_get + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") +TEST_USER_LINK_ID = os.getenv("GA_TEST_USER_LINK_ID") + + +def test_accounts_user_links_get(capsys): + accounts_user_links_get.get_account_user_link(TEST_ACCOUNT_ID, TEST_USER_LINK_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_user_links_list.py b/samples/accounts_user_links_list.py new file mode 100644 index 00000000..1166b25e --- /dev/null +++ b/samples/accounts_user_links_list.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints user links +under the specified parent account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/list +for more information. +""" +# [START analyticsadmin_accounts_user_links_list] +from google.analytics.admin import AnalyticsAdminServiceClient + +from accounts_user_links_get import print_user_link + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + list_account_user_links(account_id) + + +def list_account_user_links(account_id): + """Lists user links under the specified parent account.""" + client = AnalyticsAdminServiceClient() + results = client.list_user_links(parent=f"accounts/{account_id}") + + print("Result:") + for user_link in results: + print_user_link(user_link) + print() + + +# [END analyticsadmin_accounts_user_links_list] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_list_test.py b/samples/accounts_user_links_list_test.py new file mode 100644 index 00000000..550fa790 --- /dev/null +++ b/samples/accounts_user_links_list_test.py @@ -0,0 +1,24 @@ +# +# 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. + +import os + +import accounts_user_links_list + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") + + +def test_accounts_user_links_list(capsys): + accounts_user_links_list.list_account_user_links(TEST_ACCOUNT_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/accounts_user_links_update.py b/samples/accounts_user_links_update.py new file mode 100644 index 00000000..b2d3da6d --- /dev/null +++ b/samples/accounts_user_links_update.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which updates the account +user link. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/update +for more information. +""" +# [START analyticsadmin_accounts_user_links_update] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import UserLink + +from accounts_user_links_get import print_user_link + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics + # account user link ID (e.g. "123456") before running the sample. + account_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID" + + update_account_user_link(account_id, account_user_link_id) + + +def update_account_user_link(account_id, account_user_link_id): + """Updates the account user link.""" + client = AnalyticsAdminServiceClient() + # This call updates the email address and direct roles of the user link. + # The user link to update is specified in the `name` field of the `UserLink` + # instance. + user_link = client.update_user_link( + user_link=UserLink( + name=f"accounts/{account_id}/userLinks/{account_user_link_id}", + direct_roles=["predefinedRoles/collaborate"], + ), + ) + + print("Result:") + print_user_link(user_link) + + +# [END analyticsadmin_accounts_user_links_update] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_user_links_update_test.py b/samples/accounts_user_links_update_test.py new file mode 100644 index 00000000..d0531bc4 --- /dev/null +++ b/samples/accounts_user_links_update_test.py @@ -0,0 +1,29 @@ +# +# 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. + +import pytest + +import accounts_user_links_update + + +FAKE_ACCOUNT_ID = "1" +FAKE_ACCOUNT_USER_LINK_ID = "1" + + +def test_accounts_user_links_update(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + accounts_user_links_update.update_account_user_link( + FAKE_ACCOUNT_ID, FAKE_ACCOUNT_USER_LINK_ID + ) diff --git a/samples/noxfile_config_test.py b/samples/noxfile_config_test.py deleted file mode 100644 index e69de29b..00000000 From c1919a78539ca133017b78bf2f23d885b775bc51 Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Mon, 24 May 2021 17:55:15 -0700 Subject: [PATCH 06/10] fix the copyright string, avoid importing functions from other samples --- samples/accounts_user_links_batch_create.py | 4 +--- samples/accounts_user_links_batch_get.py | 4 +--- samples/accounts_user_links_batch_update.py | 4 +--- samples/accounts_user_links_batch_update_test.py | 1 + samples/accounts_user_links_create.py | 4 +--- samples/accounts_user_links_create_test.py | 1 + samples/accounts_user_links_delete_test.py | 1 + samples/accounts_user_links_get_test.py | 1 + samples/accounts_user_links_list.py | 4 +--- samples/accounts_user_links_list_test.py | 1 + samples/accounts_user_links_update.py | 4 +--- samples/accounts_user_links_update_test.py | 1 + 12 files changed, 12 insertions(+), 18 deletions(-) diff --git a/samples/accounts_user_links_batch_create.py b/samples/accounts_user_links_batch_create.py index 600d35c8..56d619e3 100644 --- a/samples/accounts_user_links_batch_create.py +++ b/samples/accounts_user_links_batch_create.py @@ -26,8 +26,6 @@ from google.analytics.admin_v1alpha.types import CreateUserLinkRequest from google.analytics.admin_v1alpha.types import UserLink -from accounts_user_links_get import print_user_link - def run_sample(): """Runs the sample.""" @@ -69,7 +67,7 @@ def batch_create_account_user_link(account_id, email_address): print("Result:") for user_link in response.user_links: - print_user_link(user_link) + print(user_link) print() diff --git a/samples/accounts_user_links_batch_get.py b/samples/accounts_user_links_batch_get.py index bbafc076..d5506d30 100644 --- a/samples/accounts_user_links_batch_get.py +++ b/samples/accounts_user_links_batch_get.py @@ -24,8 +24,6 @@ from google.analytics.admin import AnalyticsAdminServiceClient from google.analytics.admin_v1alpha.types import BatchGetUserLinksRequest -from accounts_user_links_get import print_user_link - def run_sample(): """Runs the sample.""" @@ -52,7 +50,7 @@ def batch_get_account_user_link(account_id, account_user_link_id): print("Result:") for user_link in response.user_links: - print_user_link(user_link) + print(user_link) print() diff --git a/samples/accounts_user_links_batch_update.py b/samples/accounts_user_links_batch_update.py index eb9e3e5c..9778a506 100644 --- a/samples/accounts_user_links_batch_update.py +++ b/samples/accounts_user_links_batch_update.py @@ -26,8 +26,6 @@ from google.analytics.admin_v1alpha.types import UpdateUserLinkRequest from google.analytics.admin_v1alpha.types import UserLink -from accounts_user_links_get import print_user_link - def run_sample(): """Runs the sample.""" @@ -70,7 +68,7 @@ def batch_update_account_user_link(account_id, account_user_link_id): print("Result:") for user_link in response.user_links: - print_user_link(user_link) + print(user_link) print() diff --git a/samples/accounts_user_links_batch_update_test.py b/samples/accounts_user_links_batch_update_test.py index 0bd9d155..b709c4f8 100644 --- a/samples/accounts_user_links_batch_update_test.py +++ b/samples/accounts_user_links_batch_update_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_user_links_create.py b/samples/accounts_user_links_create.py index 7262df35..5fe6ac35 100644 --- a/samples/accounts_user_links_create.py +++ b/samples/accounts_user_links_create.py @@ -25,8 +25,6 @@ from google.analytics.admin_v1alpha.types import CreateUserLinkRequest from google.analytics.admin_v1alpha.types import UserLink -from accounts_user_links_get import print_user_link - def run_sample(): """Runs the sample.""" @@ -62,7 +60,7 @@ def create_account_user_link(account_id, email_address): ) print("Result:") - print_user_link(user_link) + print(user_link) # [END analyticsadmin_accounts_user_links_create] diff --git a/samples/accounts_user_links_create_test.py b/samples/accounts_user_links_create_test.py index f9ea731f..13c72129 100644 --- a/samples/accounts_user_links_create_test.py +++ b/samples/accounts_user_links_create_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_user_links_delete_test.py b/samples/accounts_user_links_delete_test.py index 52eff4a6..e8bd0a5d 100644 --- a/samples/accounts_user_links_delete_test.py +++ b/samples/accounts_user_links_delete_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_user_links_get_test.py b/samples/accounts_user_links_get_test.py index 41d4b57a..0e717d37 100644 --- a/samples/accounts_user_links_get_test.py +++ b/samples/accounts_user_links_get_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_user_links_list.py b/samples/accounts_user_links_list.py index 1166b25e..f42f8ffc 100644 --- a/samples/accounts_user_links_list.py +++ b/samples/accounts_user_links_list.py @@ -23,8 +23,6 @@ # [START analyticsadmin_accounts_user_links_list] from google.analytics.admin import AnalyticsAdminServiceClient -from accounts_user_links_get import print_user_link - def run_sample(): """Runs the sample.""" @@ -41,7 +39,7 @@ def list_account_user_links(account_id): print("Result:") for user_link in results: - print_user_link(user_link) + print(user_link) print() diff --git a/samples/accounts_user_links_list_test.py b/samples/accounts_user_links_list_test.py index 550fa790..6eb0806e 100644 --- a/samples/accounts_user_links_list_test.py +++ b/samples/accounts_user_links_list_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/accounts_user_links_update.py b/samples/accounts_user_links_update.py index b2d3da6d..1a9424ab 100644 --- a/samples/accounts_user_links_update.py +++ b/samples/accounts_user_links_update.py @@ -24,8 +24,6 @@ from google.analytics.admin import AnalyticsAdminServiceClient from google.analytics.admin_v1alpha.types import UserLink -from accounts_user_links_get import print_user_link - def run_sample(): """Runs the sample.""" @@ -60,7 +58,7 @@ def update_account_user_link(account_id, account_user_link_id): ) print("Result:") - print_user_link(user_link) + print(user_link) # [END analyticsadmin_accounts_user_links_update] diff --git a/samples/accounts_user_links_update_test.py b/samples/accounts_user_links_update_test.py index d0531bc4..a7229307 100644 --- a/samples/accounts_user_links_update_test.py +++ b/samples/accounts_user_links_update_test.py @@ -1,3 +1,4 @@ +# Copyright 2021 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 259d530c4f3dbded299091d8489c8897b6f74cc0 Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Tue, 1 Jun 2021 16:22:16 -0700 Subject: [PATCH 07/10] docs: add samples for Google Analytics property management methods --- samples/properties_create.py | 63 ++++++++++++++++ samples/properties_create_test.py | 27 +++++++ samples/properties_delete.py | 52 ++++++++++++++ samples/properties_delete_test.py | 27 +++++++ samples/properties_firebase_links_create.py | 65 +++++++++++++++++ .../properties_firebase_links_create_test.py | 30 ++++++++ samples/properties_firebase_links_delete.py | 59 +++++++++++++++ .../properties_firebase_links_delete_test.py | 30 ++++++++ samples/properties_firebase_links_list.py | 63 ++++++++++++++++ .../properties_firebase_links_list_test.py | 25 +++++++ samples/properties_firebase_links_update.py | 71 +++++++++++++++++++ .../properties_firebase_links_update_test.py | 30 ++++++++ samples/properties_get.py | 66 +++++++++++++++++ samples/properties_get_test.py | 26 +++++++ samples/properties_google_ads_links_create.py | 63 ++++++++++++++++ ...properties_google_ads_links_create_test.py | 30 ++++++++ samples/properties_google_ads_links_delete.py | 59 +++++++++++++++ ...properties_google_ads_links_delete_test.py | 30 ++++++++ samples/properties_google_ads_links_list.py | 62 ++++++++++++++++ .../properties_google_ads_links_list_test.py | 25 +++++++ samples/properties_google_ads_links_update.py | 70 ++++++++++++++++++ ...properties_google_ads_links_update_test.py | 30 ++++++++ samples/properties_list.py | 55 ++++++++++++++ samples/properties_list_test.py | 25 +++++++ samples/properties_update.py | 67 +++++++++++++++++ samples/properties_update_test.py | 27 +++++++ 26 files changed, 1177 insertions(+) create mode 100644 samples/properties_create.py create mode 100644 samples/properties_create_test.py create mode 100644 samples/properties_delete.py create mode 100644 samples/properties_delete_test.py create mode 100644 samples/properties_firebase_links_create.py create mode 100644 samples/properties_firebase_links_create_test.py create mode 100644 samples/properties_firebase_links_delete.py create mode 100644 samples/properties_firebase_links_delete_test.py create mode 100644 samples/properties_firebase_links_list.py create mode 100644 samples/properties_firebase_links_list_test.py create mode 100644 samples/properties_firebase_links_update.py create mode 100644 samples/properties_firebase_links_update_test.py create mode 100644 samples/properties_get.py create mode 100644 samples/properties_get_test.py create mode 100644 samples/properties_google_ads_links_create.py create mode 100644 samples/properties_google_ads_links_create_test.py create mode 100644 samples/properties_google_ads_links_delete.py create mode 100644 samples/properties_google_ads_links_delete_test.py create mode 100644 samples/properties_google_ads_links_list.py create mode 100644 samples/properties_google_ads_links_list_test.py create mode 100644 samples/properties_google_ads_links_update.py create mode 100644 samples/properties_google_ads_links_update_test.py create mode 100644 samples/properties_list.py create mode 100644 samples/properties_list_test.py create mode 100644 samples/properties_update.py create mode 100644 samples/properties_update_test.py diff --git a/samples/properties_create.py b/samples/properties_create.py new file mode 100644 index 00000000..a7bbd796 --- /dev/null +++ b/samples/properties_create.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which creates a Google +Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties/create +for more information. +""" +# [START analyticsadmin_properties_create] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import Property + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + create_property(account_id) + + +def create_property(account_id): + """Creates a Google Analytics 4 property.""" + client = AnalyticsAdminServiceClient() + property_ = client.create_property( + property=Property( + parent=f"accounts/{account_id}", + currency_code="USD", + display_name="Test property", + industry_category="OTHER", + time_zone="America/Los_Angeles", + ) + ) + + print("Result:") + print(property_) + + +# [END analyticsadmin_properties_create] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_create_test.py b/samples/properties_create_test.py new file mode 100644 index 00000000..43b0b106 --- /dev/null +++ b/samples/properties_create_test.py @@ -0,0 +1,27 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_create + + +FAKE_ACCOUNT_ID = "1" + + +def test_properties_create(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_create.create_property(FAKE_ACCOUNT_ID) diff --git a/samples/properties_delete.py b/samples/properties_delete.py new file mode 100644 index 00000000..e6defc6c --- /dev/null +++ b/samples/properties_delete.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which deletes the Google +Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties/delete +for more information. +""" +# [START analyticsadmin_properties_delete] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + delete_property(property_id) + + +def delete_property(property_id): + """Deletes the Google Analytics 4 property.""" + client = AnalyticsAdminServiceClient() + client.delete_property(name=f"properties/{property_id}") + print("Property deleted") + + +# [END analyticsadmin_properties_delete] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_delete_test.py b/samples/properties_delete_test.py new file mode 100644 index 00000000..5d3cf741 --- /dev/null +++ b/samples/properties_delete_test.py @@ -0,0 +1,27 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_delete + + +FAKE_PROPERTY_ID = "1" + + +def test_properties_delete(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_delete.delete_property(FAKE_PROPERTY_ID) diff --git a/samples/properties_firebase_links_create.py b/samples/properties_firebase_links_create.py new file mode 100644 index 00000000..d259612d --- /dev/null +++ b/samples/properties_firebase_links_create.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which creates a Firebase link +for the Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.firebaseLinks/create +for more information. +""" +# [START analyticsadmin_properties_firebase_links_create] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import FirebaseLink + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + + # TODO(developer): Replace this variable with a Firebase project id. + # This project will be linked to the GA4 property. + firebase_project_id = "YOUR-FIREBASE-PROJECT-ID" + + create_firebase_link(property_id, firebase_project_id) + + +def create_firebase_link(property_id, firebase_project_id): + """Creates a Firebase link for the Google Analytics 4 property.""" + client = AnalyticsAdminServiceClient() + firebase_link = client.create_firebase_link( + parent=f"properties/{property_id}", + firebase_link=FirebaseLink( + project=f"projects/{firebase_project_id}", + maximum_user_access="READ_AND_ANALYZE", + ), + ) + + print("Result:") + print(firebase_link) + + +# [END analyticsadmin_properties_firebase_links_create] + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_firebase_links_create_test.py b/samples/properties_firebase_links_create_test.py new file mode 100644 index 00000000..85f468a3 --- /dev/null +++ b/samples/properties_firebase_links_create_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_firebase_links_create + + +FAKE_PROPERTY_ID = "1" +FAKE_FIREBASE_PROJECT_ID = "1" + + +def test_properties_firebase_links_create(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_firebase_links_create.create_firebase_link( + FAKE_PROPERTY_ID, FAKE_FIREBASE_PROJECT_ID + ) diff --git a/samples/properties_firebase_links_delete.py b/samples/properties_firebase_links_delete.py new file mode 100644 index 00000000..9ef1edd3 --- /dev/null +++ b/samples/properties_firebase_links_delete.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which deletes the Firebase +link from the Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.firebaseLinks/delete +for more information. +""" +# [START analyticsadmin_properties_firebase_links_delete] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + + # TODO(developer): Replace this variable with your Firebase link ID + # (e.g. "123456") before running the sample. + firebase_link_id = "YOUR-FIREBASE-LINK-ID" + + delete_firebase_link(property_id, firebase_link_id) + + +def delete_firebase_link(property_id, firebase_link_id): + """Deletes the Firebase link.""" + client = AnalyticsAdminServiceClient() + client.delete_firebase_link( + name=f"properties/{property_id}/firebaseLinks/{firebase_link_id}" + ) + print("Firebase link deleted") + + +# [END analyticsadmin_properties_firebase_links_delete] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_firebase_links_delete_test.py b/samples/properties_firebase_links_delete_test.py new file mode 100644 index 00000000..e55860ed --- /dev/null +++ b/samples/properties_firebase_links_delete_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_firebase_links_delete + + +FAKE_PROPERTY_ID = "1" +FAKE_FIREBASE_LINK_ID = "1" + + +def test_properties_firebase_links_delete(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_firebase_links_delete.delete_firebase_link( + FAKE_PROPERTY_ID, FAKE_FIREBASE_LINK_ID + ) diff --git a/samples/properties_firebase_links_list.py b/samples/properties_firebase_links_list.py new file mode 100644 index 00000000..0d5c2f17 --- /dev/null +++ b/samples/properties_firebase_links_list.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints Firebase links +under the specified parent Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.firebaseLinks/list +for more information. +""" +# [START analyticsadmin_properties_firebase_links_list] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import MaximumUserAccess + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + list_firebase_links(property_id) + + +def list_firebase_links(property_id): + """Lists Firebase links under the specified parent Google Analytics 4 + property.""" + client = AnalyticsAdminServiceClient() + results = client.list_firebase_links(parent=f"properties/{property_id}") + + print("Result:") + for firebase_link in results: + print_firebase_link(firebase_link) + print() + + +def print_firebase_link(firebase_link): + """Prints the Firebase link details.""" + print(f"Resource name: {firebase_link.name}") + print(f"Firebase project: {firebase_link.project}") + print( + f"Maximum user access to the GA4 property: " + f"{MaximumUserAccess(firebase_link.maximum_user_access).name}" + ) + print(f"Create time: {firebase_link.create_time}") + + +# [END analyticsadmin_properties_firebase_links_list] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_firebase_links_list_test.py b/samples/properties_firebase_links_list_test.py new file mode 100644 index 00000000..b3e1f0ac --- /dev/null +++ b/samples/properties_firebase_links_list_test.py @@ -0,0 +1,25 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import properties_firebase_links_list + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_properties_firebase_links_list(capsys): + properties_firebase_links_list.list_firebase_links(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/properties_firebase_links_update.py b/samples/properties_firebase_links_update.py new file mode 100644 index 00000000..085f74d5 --- /dev/null +++ b/samples/properties_firebase_links_update.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which updates the Firebase +link on the specified Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.firebaseLinks/update +for more information. +""" +# [START analyticsadmin_properties_firebase_links_update] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import FirebaseLink +from google.protobuf.field_mask_pb2 import FieldMask + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + + # TODO(developer): Replace this variable with your Firebase link ID + # (e.g. "123456") before running the sample. + firebase_link_id = "YOUR-FIREBASE-LINK-ID" + + update_firebase_link(property_id, firebase_link_id) + + +def update_firebase_link(property_id, firebase_link_id): + """Updates the Firebase link.""" + client = AnalyticsAdminServiceClient() + # This call updates the maximum user access to the GA4 property of the + # Firebase link as indicated by the value of the `update_mask` field. + # The Firebase link to update is specified in the `name` field of the + # `FirebaseLink` instance. + firebase_link = client.update_firebase_link( + firebase_link=FirebaseLink( + name=f"properties/{property_id}/firebaseLinks/{firebase_link_id}", + maximum_user_access="EDITOR_WITHOUT_LINK_MANAGEMENT", + ), + update_mask=FieldMask(paths=["maximum_user_access"]), + ) + + print("Result:") + print(firebase_link) + + +# [END analyticsadmin_properties_firebase_links_update] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_firebase_links_update_test.py b/samples/properties_firebase_links_update_test.py new file mode 100644 index 00000000..dc07fb60 --- /dev/null +++ b/samples/properties_firebase_links_update_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_firebase_links_update + + +FAKE_PROPERTY_ID = "1" +FAKE_FIREBASE_LINK_ID = "1" + + +def test_properties_firebase_links_update(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_firebase_links_update.update_firebase_link( + FAKE_PROPERTY_ID, FAKE_FIREBASE_LINK_ID + ) diff --git a/samples/properties_get.py b/samples/properties_get.py new file mode 100644 index 00000000..e63ec3ac --- /dev/null +++ b/samples/properties_get.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which print the Google +Analytics 4 property details. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties/get +for more information. +""" +# [START analyticsadmin_properties_get] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import IndustryCategory + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + get_property(property_id) + + +def get_property(property_id): + """Retrieves the Google Analytics 4 property details.""" + client = AnalyticsAdminServiceClient() + property_ = client.get_property(name=f"properties/{property_id}") + + print("Result:") + print_property(property_) + + +def print_property(property): + """Prints the Google Analytics 4 property details.""" + print(f"Resource name: {property.name}") + print(f"Parent: {property.parent}") + print(f"Display name: {property.display_name}") + print(f"Create time: {property.create_time}") + print(f"Update time: {property.update_time}") + # print(f"Delete time: {property.delete_time}") + # print(f"Expire time: {property.expire_time}") + + if property.industry_category: + print(f"Industry category: {IndustryCategory(property.industry_category).name}") + + print(f"Time zone: {property.time_zone}") + print(f"Currency code: {property.currency_code}") + + +# [END analyticsadmin_properties_get] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_get_test.py b/samples/properties_get_test.py new file mode 100644 index 00000000..90350552 --- /dev/null +++ b/samples/properties_get_test.py @@ -0,0 +1,26 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import properties_get + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") +TEST_USER_LINK_ID = os.getenv("GA_USER_LINK_ID") + + +def test_properties_get(capsys): + properties_get.get_property(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/properties_google_ads_links_create.py b/samples/properties_google_ads_links_create.py new file mode 100644 index 00000000..443b1515 --- /dev/null +++ b/samples/properties_google_ads_links_create.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which creates a Google Ads +link for the Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.googleAdsLinks/create +for more information. +""" +# [START analyticsadmin_properties_google_ads_links_create] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import GoogleAdsLink + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics account ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + + # TODO(developer): Replace this variable with a ten-digit Google Ads + # customer ID (digits only, e.g. "1234567890"). + # This Google Ads account will be linked to the GA4 property. + google_ads_customer_id = "YOUR-GOOGLE-ADS-CUSTOMER-ID" + + create_google_ads_link(property_id, google_ads_customer_id) + + +def create_google_ads_link(property_id, google_ads_customer_id): + """Creates a Google Ads link for the Google Analytics 4 property.""" + client = AnalyticsAdminServiceClient() + google_ads_link = client.create_google_ads_link( + parent=f"properties/{property_id}", + google_ads_link=GoogleAdsLink(customer_id=f"{google_ads_customer_id}"), + ) + + print("Result:") + print(google_ads_link) + + +# [END analyticsadmin_properties_google_ads_links_create] + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_google_ads_links_create_test.py b/samples/properties_google_ads_links_create_test.py new file mode 100644 index 00000000..07ae5dde --- /dev/null +++ b/samples/properties_google_ads_links_create_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_google_ads_links_create + + +FAKE_PROPERTY_ID = "1" +FAKE_ADS_CUSTOMER_ID = "1234567890" + + +def test_properties_google_ads_links_create(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_google_ads_links_create.create_google_ads_link( + FAKE_PROPERTY_ID, FAKE_ADS_CUSTOMER_ID + ) diff --git a/samples/properties_google_ads_links_delete.py b/samples/properties_google_ads_links_delete.py new file mode 100644 index 00000000..74dd3ba0 --- /dev/null +++ b/samples/properties_google_ads_links_delete.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application deletes the Google Ads link +from the specified Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.googleAdsLinks/delete +for more information. +""" +# [START analyticsadmin_properties_google_ads_links_delete] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + + # TODO(developer): Replace this variable with your Google Analytics Ads + # link ID (e.g. "123456") before running the sample. + google_ads_link_id = "YOUR-GOOGLE-ADS-LINK-ID" + + delete_google_ads_link(property_id, google_ads_link_id) + + +def delete_google_ads_link(property_id, google_ads_link_id): + """Deletes the Google Ads link.""" + client = AnalyticsAdminServiceClient() + client.delete_google_ads_link( + name=f"properties/{property_id}/googleAdsLinks/{google_ads_link_id}" + ) + print("Google Ads link deleted") + + +# [END analyticsadmin_properties_google_ads_links_delete] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_google_ads_links_delete_test.py b/samples/properties_google_ads_links_delete_test.py new file mode 100644 index 00000000..25c2768d --- /dev/null +++ b/samples/properties_google_ads_links_delete_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_google_ads_links_delete + + +FAKE_PROPERTY_ID = "1" +FAKE_GOOGLE_ADS_LINK_ID = "1" + + +def test_properties_google_ads_links_delete(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_google_ads_links_delete.delete_google_ads_link( + FAKE_PROPERTY_ID, FAKE_GOOGLE_ADS_LINK_ID + ) diff --git a/samples/properties_google_ads_links_list.py b/samples/properties_google_ads_links_list.py new file mode 100644 index 00000000..1aa7e065 --- /dev/null +++ b/samples/properties_google_ads_links_list.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints Google Ads links +under the specified parent Google Analytics 4 property. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.googleAdsLinks/list +for more information. +""" +# [START analyticsadmin_properties_google_ads_links_list] +from google.analytics.admin import AnalyticsAdminServiceClient + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + list_google_ads_links(property_id) + + +def list_google_ads_links(property_id): + """Lists Google Ads links under the specified parent Google Analytics 4 + property.""" + client = AnalyticsAdminServiceClient() + results = client.list_google_ads_links(parent=f"properties/{property_id}") + + print("Result:") + for google_ads_link in results: + print_google_ads_link(google_ads_link) + print() + + +def print_google_ads_link(google_ads_link): + """Prints the Google Ads link details.""" + print(f"Resource name: {google_ads_link.name}") + print(f"Google Ads customer ID: {google_ads_link.customer_id}") + print(f"Can manage clients: {google_ads_link.can_manage_clients}") + print(f"Ads personalization enabled: {google_ads_link.ads_personalization_enabled}") + print(f"Email address of the link creator: {google_ads_link.email_address}") + print(f"Create time: {google_ads_link.create_time}") + print(f"Update time: {google_ads_link.update_time}") + + +# [END analyticsadmin_properties_google_ads_links_list] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_google_ads_links_list_test.py b/samples/properties_google_ads_links_list_test.py new file mode 100644 index 00000000..1f850a4f --- /dev/null +++ b/samples/properties_google_ads_links_list_test.py @@ -0,0 +1,25 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import properties_google_ads_links_list + +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_properties_firebase_links_list(capsys): + properties_google_ads_links_list.list_google_ads_links(TEST_PROPERTY_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/properties_google_ads_links_update.py b/samples/properties_google_ads_links_update.py new file mode 100644 index 00000000..8959cfc3 --- /dev/null +++ b/samples/properties_google_ads_links_update.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application updates the Google Ads link. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties.googleAdsLinks/update +for more information. +""" +# [START analyticsadmin_properties_google_ads_links_update] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import GoogleAdsLink +from google.protobuf.field_mask_pb2 import FieldMask + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + + # TODO(developer): Replace this variable with your Google Analytics Ads + # link ID (e.g. "123456") before running the sample. + google_ads_link_id = "YOUR-GOOGLE-ADS-LINK-ID" + + update_google_ads_link(property_id, google_ads_link_id) + + +def update_google_ads_link(property_id, google_ads_link_id): + """Updates the Google Ads link.""" + client = AnalyticsAdminServiceClient() + # This call updates the adsPersonalizationEnabled setting of the + # Google Ads link as indicated by the value of the `update_mask` field. + # The Google Ads link to update is specified in the `name` field of the + # `Google AdsLink` instance. + google_ads_link = client.update_google_ads_link( + google_ads_link=GoogleAdsLink( + name=f"properties/{property_id}/googleAdsLinks/{google_ads_link_id}", + ads_personalization_enabled=False, + ), + update_mask=FieldMask(paths=["ads_personalization_enabled"]), + ) + + print("Result:") + print(google_ads_link) + + +# [END analyticsadmin_properties_google_ads_links_update] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_google_ads_links_update_test.py b/samples/properties_google_ads_links_update_test.py new file mode 100644 index 00000000..b734c379 --- /dev/null +++ b/samples/properties_google_ads_links_update_test.py @@ -0,0 +1,30 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_google_ads_links_update + + +FAKE_PROPERTY_ID = "1" +FAKE_GOOGLE_ADS_LINK_ID = "1" + + +def test_properties_google_ads_links_update(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_google_ads_links_update.update_google_ads_link( + FAKE_PROPERTY_ID, FAKE_GOOGLE_ADS_LINK_ID + ) diff --git a/samples/properties_list.py b/samples/properties_list.py new file mode 100644 index 00000000..19bfcef8 --- /dev/null +++ b/samples/properties_list.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which prints Google Analytics 4 +properties under the specified parent account that are available to the +current user. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties/list +for more information. +""" +# [START analyticsadmin_properties_list] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import ListPropertiesRequest + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + list_properties(account_id) + + +def list_properties(account_id): + """Lists Google Analytics 4 properties under the specified parent account + that are available to the current user.""" + client = AnalyticsAdminServiceClient() + results = client.list_properties( + ListPropertiesRequest(filter=f"parent:accounts/{account_id}", show_deleted=True) + ) + + print("Result:") + for property_ in results: + print(property_) + print() + + +# [END analyticsadmin_properties_list] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_list_test.py b/samples/properties_list_test.py new file mode 100644 index 00000000..97bf47dd --- /dev/null +++ b/samples/properties_list_test.py @@ -0,0 +1,25 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import properties_list + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") + + +def test_properties_get(capsys): + properties_list.list_properties(TEST_ACCOUNT_ID) + out, _ = capsys.readouterr() + assert "Result" in out diff --git a/samples/properties_update.py b/samples/properties_update.py new file mode 100644 index 00000000..8700440d --- /dev/null +++ b/samples/properties_update.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python + +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/properties/update +for more information. +""" +# [START analyticsadmin_properties_update] +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.types import Property +from google.protobuf.field_mask_pb2 import FieldMask + + +def run_sample(): + """Runs the sample.""" + + # !!! ATTENTION !!! + # Running this sample may change/delete your Google Analytics account + # configuration. Make sure to not use the Google Analytics property ID from + # your production environment below. + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + update_property(property_id) + + +def update_property(property_id): + """Updates the Google Analytics 4 property.""" + client = AnalyticsAdminServiceClient() + # This call updates the display name, industry category and time zone of the + # property, as indicated by the value of the `update_mask` field. + # The property to update is specified in the `name` field of the `Property` + # instance. + property_ = client.update_property( + property=Property( + name=f"properties/{property_id}", + display_name="This is an updated test property", + industry_category="GAMES", + time_zone="America/New_York", + ), + update_mask=FieldMask(paths=["display_name", "time_zone", "industry_category"]), + ) + + print("Result:") + print(property_) + + +# [END analyticsadmin_properties_update] + + +if __name__ == "__main__": + run_sample() diff --git a/samples/properties_update_test.py b/samples/properties_update_test.py new file mode 100644 index 00000000..9d94bb09 --- /dev/null +++ b/samples/properties_update_test.py @@ -0,0 +1,27 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import pytest + +import properties_update + + +FAKE_PROPERTY_ID = "1" + + +def test_properties_update(): + # This test ensures that the call is valid and reaches the server, even + # though the operation does not succeed due to permission error. + with pytest.raises(Exception, match="403 The caller does not have permission"): + properties_update.update_property(FAKE_PROPERTY_ID) From 8b7a53f4f47650ffd736be8a865929062980d9f2 Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Tue, 28 Sep 2021 23:12:59 -0700 Subject: [PATCH 08/10] add samples for accounts.search_change_hostory_events method --- .../accounts_search_change_history_events.py | 122 ++++++++++++++++++ ...ounts_search_change_history_events_test.py | 28 ++++ 2 files changed, 150 insertions(+) create mode 100644 samples/accounts_search_change_history_events.py create mode 100644 samples/accounts_search_change_history_events_test.py diff --git a/samples/accounts_search_change_history_events.py b/samples/accounts_search_change_history_events.py new file mode 100644 index 00000000..30a7eee4 --- /dev/null +++ b/samples/accounts_search_change_history_events.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python + +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +"""Google Analytics Admin API sample application which displays the change +history for the Google Analytics account. + +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/searchChangeHistoryEvents +for more information. +""" +# [START analyticsadmin_properties_conversion_events_create] +from google.protobuf.timestamp_pb2 import Timestamp +from datetime import datetime +from datetime import timedelta + +from google.analytics.admin import AnalyticsAdminServiceClient +from google.analytics.admin import SearchChangeHistoryEventsRequest +from google.analytics.admin_v1alpha.types import ActorType +from google.analytics.admin_v1alpha.types import ActionType + + +def run_sample(): + """Runs the sample.""" + # TODO(developer): Replace this variable with your Google Analytics + # account ID (e.g. "123456") before running the sample. + account_id = "YOUR-GA-ACCOUNT-ID" + + # TODO(developer): Replace this variable with your Google Analytics 4 + # property ID (e.g. "123456") before running the sample. + property_id = "YOUR-GA4-PROPERTY-ID" + search_change_history_events(account_id, property_id) + + +def search_change_history_events(account_id: str, property_id: str): + """Lists the Google Analytics accounts available to the current user.""" + client = AnalyticsAdminServiceClient() + # Create a timestamp object and subtract 7 days from the current date/time. + earliest_change_time = Timestamp() + earliest_change_time.FromDatetime(datetime.now() - timedelta(days=7)) + + results = client.search_change_history_events( + SearchChangeHistoryEventsRequest( + account=f"accounts/{account_id}", + property=f"properties/{property_id}", + action=["CREATED", "UPDATED"], + earliest_change_time=earliest_change_time, + ) + ) + + print("Result:") + for event in results: + print(f"Event ID: {event.id}") + print(f"Change time: {event.change_time}") + print(f"Actor type: {ActorType(event.actor_type).name}") + print(f"User actor e-mail: {event.user_actor_email}") + print(f"Changes filtered: {event.changes_filtered}") + for change in event.changes: + print(" Change details") + print(f" Resource name: {change.resource}") + print(f" Action: {ActionType(change.action).name}") + print(" Resource before change: ") + print_resource(change.resource_before_change) + print(" Resource after change: ") + print_resource(change.resource_after_change) + print() + + +def print_resource(resource): + """Prints the change history resource.""" + # Detect the type of the resource by checking value of a oneof field. + if resource.property: + print(" Property resource") + elif resource.account: + print(" Account resource") + elif resource.web_data_stream: + print(" WebDataStream resource") + elif resource.android_app_data_stream: + print(" AndroidAppDataStream resource") + elif resource.ios_app_data_stream: + print(" IosAppDataStream resource") + elif resource.firebase_link: + print(" FirebaseLink resource") + elif resource.google_ads_link: + print(" GoogleAdsLink resource") + elif resource.google_signals_settings: + print(" GoogleSignalsSettings resource") + elif resource.display_video_360_advertiser_link: + print(" DisplayVideo360AdvertiserLink resource") + elif resource.display_video_360_advertiser_link_proposal: + print(" DisplayVideo360AdvertiserLinkProposal resource") + elif resource.conversion_event: + print(" ConversionEvent resource") + elif resource.measurement_protocol_secret: + print(" MeasurementProtocolSecret resource") + elif resource.custom_dimension: + print(" CustomDimension resource") + elif resource.custom_metric: + print(" CustomMetric resource") + elif resource.data_retention_settings: + print(" DataRetentionSettings resource") + else: + print(" Resource not set") + print(f" Resource value: {resource}") + print() + + +# [END analyticsadmin_properties_conversion_events_create] + +if __name__ == "__main__": + run_sample() diff --git a/samples/accounts_search_change_history_events_test.py b/samples/accounts_search_change_history_events_test.py new file mode 100644 index 00000000..9a3e63cf --- /dev/null +++ b/samples/accounts_search_change_history_events_test.py @@ -0,0 +1,28 @@ +# Copyright 2021 Google LLC All Rights Reserved. +# +# 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. + +import os + +import accounts_search_change_history_events + +TEST_ACCOUNT_ID = os.getenv("GA_TEST_ACCOUNT_ID") +TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID") + + +def test_accounts_search_change_history_events(capsys): + accounts_search_change_history_events.search_change_history_events( + TEST_ACCOUNT_ID, TEST_PROPERTY_ID + ) + out, _ = capsys.readouterr() + assert "Result" in out From b9bbc8603e7ac6dee8d489ccba0dc819b5c2d80f Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Tue, 28 Sep 2021 23:14:04 -0700 Subject: [PATCH 09/10] fix broken documentation urls --- samples/accounts_update.py | 2 +- samples/accounts_user_links_update.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/accounts_update.py b/samples/accounts_update.py index e3ae56ed..b87142c4 100644 --- a/samples/accounts_update.py +++ b/samples/accounts_update.py @@ -17,7 +17,7 @@ """Google Analytics Admin API sample application which updates the Google Analytics account. -See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/update +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/patch for more information. """ # [START analyticsadmin_accounts_update] diff --git a/samples/accounts_user_links_update.py b/samples/accounts_user_links_update.py index 1a9424ab..868403f0 100644 --- a/samples/accounts_user_links_update.py +++ b/samples/accounts_user_links_update.py @@ -17,7 +17,7 @@ """Google Analytics Admin API sample application which updates the account user link. -See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/update +See https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts.userLinks/patch for more information. """ # [START analyticsadmin_accounts_user_links_update] From 868fdfea89e2dd2208054188ca10f369f3fe41ad Mon Sep 17 00:00:00 2001 From: ikuleshov Date: Tue, 5 Oct 2021 23:37:44 -0700 Subject: [PATCH 10/10] fix imports --- samples/accounts_search_change_history_events.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/samples/accounts_search_change_history_events.py b/samples/accounts_search_change_history_events.py index 2df9ffd9..38f0fec9 100644 --- a/samples/accounts_search_change_history_events.py +++ b/samples/accounts_search_change_history_events.py @@ -21,14 +21,15 @@ for more information. """ # [START analyticsadmin_properties_conversion_events_create] -from google.protobuf.timestamp_pb2 import Timestamp from datetime import datetime from datetime import timedelta from google.analytics.admin import AnalyticsAdminServiceClient from google.analytics.admin import SearchChangeHistoryEventsRequest -from google.analytics.admin_v1alpha.types import ActorType from google.analytics.admin_v1alpha.types import ActionType +from google.analytics.admin_v1alpha.types import ActorType + +from google.protobuf.timestamp_pb2 import Timestamp def run_sample(): @@ -45,7 +46,7 @@ def run_sample(): def search_change_history_events(account_id: str, property_id: str): """Lists the change history events for the Google Analytics 4 property - within the specified date range.""" + within the specified date range.""" client = AnalyticsAdminServiceClient() # Create a timestamp object and subtract 7 days from the current date/time. earliest_change_time = Timestamp()