diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index 24c08609..71b9ff52 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.6" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py36" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-talent/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index c3b001b0..455dc164 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.7" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py37" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-talent/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index ab18d8d2..998d2cb7 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -24,6 +24,12 @@ env_vars: { value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py38" +} + # Download secrets for samples gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" diff --git a/samples/snippets/README.rst b/samples/snippets/README.rst new file mode 100644 index 00000000..a7bfef3c --- /dev/null +++ b/samples/snippets/README.rst @@ -0,0 +1,6 @@ +To run the sample, you need to enable the API at: https://console.cloud.google.com/apis/library/jobs.googleapis.com + +To run the sample, you need to have the following roles: + +* `Talent Solution Job Editor` +* `Talent Solution Profile Editor` diff --git a/samples/snippets/conftest.py b/samples/snippets/conftest.py new file mode 100644 index 00000000..169a401b --- /dev/null +++ b/samples/snippets/conftest.py @@ -0,0 +1,87 @@ +# 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. + +import os +import uuid + +from google.api_core.exceptions import NotFound + +import pytest + +import job_search_create_company +import job_search_create_job +import job_search_create_tenant +import job_search_delete_company +import job_search_delete_job +import job_search_delete_tenant + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +@pytest.fixture(scope="module") +def tenant(): + tenant_ext_unique_id = "TEST_TENANT_{}".format(uuid.uuid4()) + # create a temporary tenant + tenant_name = job_search_create_tenant.create_tenant( + PROJECT_ID, tenant_ext_unique_id + ) + + # extract company id + tenant_id = tenant_name.split("/")[-1] + + yield tenant_id + + try: + job_search_delete_tenant.delete_tenant(PROJECT_ID, tenant_id) + except NotFound as e: + print("Ignoring NotFound upon cleanup, details: {}".format(e)) + + +@pytest.fixture(scope="module") +def company(tenant): + company_ext_id = "COMPANY_EXT_ID_{}".format(uuid.uuid4()) + + # create a temporary company + company_name = job_search_create_company.create_company( + PROJECT_ID, tenant, "Test Company Name", company_ext_id + ) + + # extract company id + company_id = company_name.split("/")[-1] + + yield company_id + + try: + job_search_delete_company.delete_company(PROJECT_ID, tenant, company_id) + except NotFound as e: + print("Ignoring NotFound upon cleanup, details: {}".format(e)) + + +@pytest.fixture(scope="module") +def job(tenant, company): + post_unique_id = "TEST_POST_{}".format(uuid.uuid4().hex)[:20] + # create a temporary job + job_name = job_search_create_job.create_job( + PROJECT_ID, tenant, company, post_unique_id, "www.jobUrl.com" + ) + + # extract company id + job_id = job_name.split("/")[-1] + + yield job_id + + try: + job_search_delete_job.delete_job(PROJECT_ID, tenant, job_id) + except NotFound as e: + print("Ignoring NotFound upon cleanup, details: {}".format(e)) diff --git a/samples/snippets/job_search_autocomplete_job_title.py b/samples/snippets/job_search_autocomplete_job_title.py new file mode 100644 index 00000000..e9f52868 --- /dev/null +++ b/samples/snippets/job_search_autocomplete_job_title.py @@ -0,0 +1,54 @@ +# 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 +# +# https://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. + +# [START job_search_autocomplete_job_title] + +from google.cloud import talent_v4beta1 +import six + + +def complete_query(project_id, tenant_id, query): + """Complete job title given partial text (autocomplete)""" + + client = talent_v4beta1.CompletionClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # query = '[partially typed job title]' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(query, six.binary_type): + query = query.decode("utf-8") + + parent = f"projects/{project_id}/tenants/{tenant_id}" + + request = talent_v4beta1.CompleteQueryRequest( + parent=parent, + query=query, + page_size=5, # limit for number of results + language_codes=["en-US"], # language code + ) + response = client.complete_query(request=request) + for result in response.completion_results: + print(f"Suggested title: {result.suggestion}") + # Suggestion type is JOB_TITLE or COMPANY_TITLE + print( + f"Suggestion type: {talent_v4beta1.CompleteQueryRequest.CompletionType(result.type).name}" + ) + + +# [END job_search_autocomplete_job_title] diff --git a/samples/snippets/job_search_autocomplete_job_title_test.py b/samples/snippets/job_search_autocomplete_job_title_test.py new file mode 100644 index 00000000..4fe24984 --- /dev/null +++ b/samples/snippets/job_search_autocomplete_job_title_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_autocomplete_job_title + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_autocomplete_job_title(capsys, tenant): + job_search_autocomplete_job_title.complete_query(PROJECT_ID, tenant, "Software") + out, _ = capsys.readouterr() + assert "Suggested title:" in out diff --git a/samples/snippets/job_search_batch_create_jobs.py b/samples/snippets/job_search_batch_create_jobs.py new file mode 100644 index 00000000..18d48ae9 --- /dev/null +++ b/samples/snippets/job_search_batch_create_jobs.py @@ -0,0 +1,133 @@ +# 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 +# +# https://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. + +# [START job_search_batch_create_jobs] + +from google.cloud import talent +import six + + +def batch_create_jobs( + project_id, + tenant_id, + company_name_one, + requisition_id_one, + title_one, + description_one, + job_application_url_one, + address_one, + language_code_one, + company_name_two, + requisition_id_two, + title_two, + description_two, + job_application_url_two, + address_two, + language_code_two, +): + """ + Batch Create Jobs + + Args: + project_id Your Google Cloud Project ID + tenant_id Identifier of the Tenant + """ + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # company_name_one = 'Company name, e.g. projects/your-project/companies/company-id' + # requisition_id_one = 'Job requisition ID, aka Posting ID. Unique per job.' + # title_one = 'Software Engineer' + # description_one = 'This is a description of this wonderful job!' + # job_application_url_one = 'https://www.example.org/job-posting/123' + # address_one = '1600 Amphitheatre Parkway, Mountain View, CA 94043' + # language_code_one = 'en-US' + # company_name_two = 'Company name, e.g. projects/your-project/companies/company-id' + # requisition_id_two = 'Job requisition ID, aka Posting ID. Unique per job.' + # title_two = 'Quality Assurance' + # description_two = 'This is a description of this wonderful job!' + # job_application_url_two = 'https://www.example.org/job-posting/123' + # address_two = '111 8th Avenue, New York, NY 10011' + # language_code_two = 'en-US' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(company_name_one, six.binary_type): + company_name_one = company_name_one.decode("utf-8") + if isinstance(requisition_id_one, six.binary_type): + requisition_id_one = requisition_id_one.decode("utf-8") + if isinstance(title_one, six.binary_type): + title_one = title_one.decode("utf-8") + if isinstance(description_one, six.binary_type): + description_one = description_one.decode("utf-8") + if isinstance(job_application_url_one, six.binary_type): + job_application_url_one = job_application_url_one.decode("utf-8") + if isinstance(address_one, six.binary_type): + address_one = address_one.decode("utf-8") + if isinstance(language_code_one, six.binary_type): + language_code_one = language_code_one.decode("utf-8") + if isinstance(company_name_two, six.binary_type): + company_name_two = company_name_two.decode("utf-8") + if isinstance(requisition_id_two, six.binary_type): + requisition_id_two = requisition_id_two.decode("utf-8") + if isinstance(title_two, six.binary_type): + title_two = title_two.decode("utf-8") + if isinstance(description_two, six.binary_type): + description_two = description_two.decode("utf-8") + if isinstance(job_application_url_two, six.binary_type): + job_application_url_two = job_application_url_two.decode("utf-8") + if isinstance(address_two, six.binary_type): + address_two = address_two.decode("utf-8") + if isinstance(language_code_two, six.binary_type): + language_code_two = language_code_two.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + uris = [job_application_url_one] + application_info = {"uris": uris} + addresses = [address_one] + jobs_element = { + "company": company_name_one, + "requisition_id": requisition_id_one, + "title": title_one, + "description": description_one, + "application_info": application_info, + "addresses": addresses, + "language_code": language_code_one, + } + uris_2 = [job_application_url_two] + application_info_2 = {"uris": uris_2} + addresses_2 = [address_two] + jobs_element_2 = { + "company": company_name_two, + "requisition_id": requisition_id_two, + "title": title_two, + "description": description_two, + "application_info": application_info_2, + "addresses": addresses_2, + "language_code": language_code_two, + } + jobs = [jobs_element, jobs_element_2] + + operation = client.batch_create_jobs(parent=parent, jobs=jobs) + + print("Waiting for operation to complete...") + response = operation.result(90) + + print("Batch response: {}".format(response)) + + +# [END job_search_batch_create_jobs] diff --git a/samples/snippets/job_search_batch_update_jobs.py b/samples/snippets/job_search_batch_update_jobs.py new file mode 100644 index 00000000..0aa576c4 --- /dev/null +++ b/samples/snippets/job_search_batch_update_jobs.py @@ -0,0 +1,145 @@ +# 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 +# +# https://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. + +# [START job_search_batch_update_jobs] + +from google.cloud import talent +import six + + +def batch_update_jobs( + project_id, + tenant_id, + job_name_one, + company_name_one, + requisition_id_one, + title_one, + description_one, + job_application_url_one, + address_one, + language_code_one, + job_name_two, + company_name_two, + requisition_id_two, + title_two, + description_two, + job_application_url_two, + address_two, + language_code_two, +): + """ + Batch Update Jobs + + Args: + project_id Your Google Cloud Project ID + tenant_id Identifier of the Tenant + """ + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # job_name_one = 'job name, projects/your-project/tenants/tenant-id/jobs/job-id' + # company_name_one = 'Company name, e.g. projects/your-project/companies/company-id' + # requisition_id_one = 'Job requisition ID, aka Posting ID. Unique per job.' + # title_one = 'Software Engineer' + # description_one = 'This is a description of this wonderful job!' + # job_application_url_one = 'https://www.example.org/job-posting/123' + # address_one = '1600 Amphitheatre Parkway, Mountain View, CA 94043' + # language_code_one = 'en-US' + # job_name_two = 'job name, projects/your-project/tenants/tenant-id/jobs/job-id' + # company_name_two = 'Company name, e.g. projects/your-project/companies/company-id' + # requisition_id_two = 'Job requisition ID, aka Posting ID. Unique per job.' + # title_two = 'Quality Assurance' + # description_two = 'This is a description of this wonderful job!' + # job_application_url_two = 'https://www.example.org/job-posting/123' + # address_two = '111 8th Avenue, New York, NY 10011' + # language_code_two = 'en-US' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(job_name_one, six.binary_type): + job_name_one = job_name_one.decode("utf-8") + if isinstance(company_name_one, six.binary_type): + company_name_one = company_name_one.decode("utf-8") + if isinstance(requisition_id_one, six.binary_type): + requisition_id_one = requisition_id_one.decode("utf-8") + if isinstance(title_one, six.binary_type): + title_one = title_one.decode("utf-8") + if isinstance(description_one, six.binary_type): + description_one = description_one.decode("utf-8") + if isinstance(job_application_url_one, six.binary_type): + job_application_url_one = job_application_url_one.decode("utf-8") + if isinstance(address_one, six.binary_type): + address_one = address_one.decode("utf-8") + if isinstance(language_code_one, six.binary_type): + language_code_one = language_code_one.decode("utf-8") + if isinstance(job_name_two, six.binary_type): + job_name_two = job_name_two.decode("utf-8") + if isinstance(company_name_two, six.binary_type): + company_name_two = company_name_two.decode("utf-8") + if isinstance(requisition_id_two, six.binary_type): + requisition_id_two = requisition_id_two.decode("utf-8") + if isinstance(title_two, six.binary_type): + title_two = title_two.decode("utf-8") + if isinstance(description_two, six.binary_type): + description_two = description_two.decode("utf-8") + if isinstance(job_application_url_two, six.binary_type): + job_application_url_two = job_application_url_two.decode("utf-8") + if isinstance(address_two, six.binary_type): + address_two = address_two.decode("utf-8") + if isinstance(language_code_two, six.binary_type): + language_code_two = language_code_two.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + uris = [job_application_url_one] + application_info = {"uris": uris} + addresses = [address_one] + jobs_element = talent.Job( + name=job_name_one, + company=company_name_one, + requisition_id=requisition_id_one, + title=title_one, + description=description_one, + application_info=application_info, + addresses=addresses, + language_code=language_code_one + ) + + uris_2 = [job_application_url_two] + application_info_2 = {"uris": uris_2} + addresses_2 = [address_two] + jobs_element_2 = talent.Job( + name=job_name_two, + company=company_name_two, + requisition_id=requisition_id_two, + title=title_two, + description=description_two, + application_info=application_info_2, + addresses=addresses_2, + language_code=language_code_two + ) + + jobs = [jobs_element, jobs_element_2] + + operation = client.batch_update_jobs(parent=parent, jobs=jobs) + + print("Waiting for operation to complete...") + response = operation.result(90) + + print("Batch response: {}".format(response)) + + +# [END job_search_batch_update_jobs] diff --git a/samples/snippets/job_search_commute_search.py b/samples/snippets/job_search_commute_search.py new file mode 100644 index 00000000..0b768441 --- /dev/null +++ b/samples/snippets/job_search_commute_search.py @@ -0,0 +1,72 @@ +# 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 +# +# https://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. + +# [START job_search_commute_search] + +from google.cloud import talent +import six + + +def search_jobs(project_id, tenant_id): + """Search Jobs using commute distance""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + domain = "www.example.com" + session_id = "Hashed session identifier" + user_id = "Hashed user identifier" + request_metadata = talent.RequestMetadata( + domain=domain, + session_id=session_id, + user_id=user_id + ) + commute_method = talent.CommuteMethod.TRANSIT + seconds = 1800 + travel_duration = {"seconds": seconds} + latitude = 37.422408 + longitude = -122.084068 + start_coordinates = {"latitude": latitude, "longitude": longitude} + commute_filter = talent.CommuteFilter( + commute_method=commute_method, + travel_duration=travel_duration, + start_coordinates=start_coordinates, + ) + job_query = talent.JobQuery(commute_filter=commute_filter) + + # Iterate over all results + results = [] + request = talent.SearchJobsRequest( + parent=parent, + request_metadata=request_metadata, + job_query=job_query, + ) + for response_item in client.search_jobs(request=request): + print(f"Job summary: {response_item.job_summary}") + print(f"Job title snippet: {response_item.job_title_snippet}") + job = response_item.job + results.append(job.name) + print(f"Job name: {job.name}") + print(f"Job title: {job.title}") + return results + + +# [END job_search_commute_search] diff --git a/samples/snippets/job_search_commute_search_test.py b/samples/snippets/job_search_commute_search_test.py new file mode 100644 index 00000000..91187501 --- /dev/null +++ b/samples/snippets/job_search_commute_search_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_commute_search + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_commute_search(tenant): + jobs = job_search_commute_search.search_jobs(PROJECT_ID, tenant) + for job in jobs: + assert "projects/" in job diff --git a/samples/snippets/job_search_create_client_event.py b/samples/snippets/job_search_create_client_event.py new file mode 100644 index 00000000..5b068570 --- /dev/null +++ b/samples/snippets/job_search_create_client_event.py @@ -0,0 +1,77 @@ +# 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 +# +# https://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. + +# [START job_search_create_client_event] + +from google.cloud import talent +from google.cloud.talent import enums +import six + + +def create_client_event(project_id, tenant_id, request_id, event_id): + """ + Creates a client event + + Args: + project_id Your Google Cloud Project ID + tenant_id Identifier of the Tenant + request_id A unique ID generated in the API responses. + Value should be set to the request_id from an API response. + event_id A unique identifier, generated by the client application + """ + + client = talent.EventServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # request_id = '[request_id from ResponseMetadata]' + # event_id = '[Set this to a unique identifier]' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(request_id, six.binary_type): + request_id = request_id.decode("utf-8") + if isinstance(event_id, six.binary_type): + event_id = event_id.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + + # The timestamp of the event as seconds of UTC time since Unix epoch + # For more information on how to create google.protobuf.Timestamps + # See: + # https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto + seconds = 0 + create_time = {"seconds": seconds} + + # The type of event attributed to the behavior of the end user + type_ = enums.JobEvent.JobEventType.VIEW + + # List of job names associated with this event + jobs_element = "projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]" + jobs_element_2 = "projects/[Project ID]/tenants/[Tenant ID]/jobs/[Job ID]" + jobs = [jobs_element, jobs_element_2] + job_event = {"type": type_, "jobs": jobs} + client_event = { + "request_id": request_id, + "event_id": event_id, + "create_time": create_time, + "job_event": job_event, + } + + response = client.create_client_event(parent=parent, client_event=client_event) + print(response) + + +# [END job_search_create_client_event] diff --git a/samples/snippets/job_search_create_company.py b/samples/snippets/job_search_create_company.py new file mode 100644 index 00000000..28619a37 --- /dev/null +++ b/samples/snippets/job_search_create_company.py @@ -0,0 +1,50 @@ +# 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 +# +# https://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. + +# [START job_search_create_company] + +from google.cloud import talent +import six + + +def create_company(project_id, tenant_id, display_name, external_id): + """Create Company""" + + client = talent.CompanyServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # display_name = 'My Company Name' + # external_id = 'Identifier of this company in my system' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(display_name, six.binary_type): + display_name = display_name.decode("utf-8") + if isinstance(external_id, six.binary_type): + external_id = external_id.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + company = {"display_name": display_name, "external_id": external_id} + + response = client.create_company(parent=parent, company=company) + print("Created Company") + print("Name: {}".format(response.name)) + print("Display Name: {}".format(response.display_name)) + print("External ID: {}".format(response.external_id)) + return response.name + + +# [END job_search_create_company] diff --git a/samples/snippets/job_search_create_company_test.py b/samples/snippets/job_search_create_company_test.py new file mode 100644 index 00000000..e78f6090 --- /dev/null +++ b/samples/snippets/job_search_create_company_test.py @@ -0,0 +1,48 @@ +# 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. + +import os +import uuid + +import pytest + +import job_search_create_company +import job_search_delete_company + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] +COMPANY_EXT_ID = "COMPANY_EXT_ID_{}".format(uuid.uuid4()) + + +def test_create_company(capsys, tenant, cleaner): + # create company + company_name = job_search_create_company.create_company( + PROJECT_ID, tenant, "Test Company Name", COMPANY_EXT_ID + ) + out, _ = capsys.readouterr() + assert "Created" in out + assert "Name:" in out + + # extract id + company_id = company_name.split("/")[-1] + cleaner.append(company_id) + + +@pytest.fixture(scope="module") +def cleaner(tenant): + companies = [] + + yield companies + + for company_id in companies: + job_search_delete_company.delete_company(PROJECT_ID, tenant, company_id) diff --git a/samples/snippets/job_search_create_job.py b/samples/snippets/job_search_create_job.py new file mode 100644 index 00000000..0252a3e0 --- /dev/null +++ b/samples/snippets/job_search_create_job.py @@ -0,0 +1,71 @@ +# 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 +# +# https://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. + +# [START job_search_create_job] + +from google.cloud import talent +import six + + +def create_job( + project_id, tenant_id, company_id, requisition_id, job_application_url, +): + """Create Job""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # company_id = 'Company name, e.g. projects/your-project/companies/company-id' + # requisition_id = 'Job requisition ID, aka Posting ID. Unique per job.' + # title = 'Software Engineer' + # description = 'This is a description of this wonderful job!' + # job_application_url = 'https://www.example.org/job-posting/123' + # address_one = '1600 Amphitheatre Parkway, Mountain View, CA 94043' + # address_two = '111 8th Avenue, New York, NY 10011' + # language_code = 'en-US' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(company_id, six.binary_type): + company_id = company_id.decode("utf-8") + if isinstance(requisition_id, six.binary_type): + requisition_id = requisition_id.decode("utf-8") + if isinstance(job_application_url, six.binary_type): + job_application_url = job_application_url.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + uris = [job_application_url] + application_info = {"uris": uris} + addresses = [ + "1600 Amphitheatre Parkway, Mountain View, CA 94043", + "111 8th Avenue, New York, NY 10011", + ] + job = { + "company": company_id, + "requisition_id": requisition_id, + "title": "Software Developer", + "description": "Develop, maintain the software solutions.", + "application_info": application_info, + "addresses": addresses, + "language_code": "en-US", + } + + response = client.create_job(parent=parent, job=job) + print("Created job: {}".format(response.name)) + return response.name + + +# [END job_search_create_job] diff --git a/samples/snippets/job_search_create_job_custom_attributes.py b/samples/snippets/job_search_create_job_custom_attributes.py new file mode 100644 index 00000000..1ae10f2c --- /dev/null +++ b/samples/snippets/job_search_create_job_custom_attributes.py @@ -0,0 +1,63 @@ +# 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 +# +# https://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. + +# [START job_search_create_job_custom_attributes] + +from google.cloud import talent +import six + + +def create_job(project_id, tenant_id, company_id, requisition_id): + """Create Job with Custom Attributes""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # company_id = 'Company name, e.g. projects/your-project/companies/company-id' + # requisition_id = 'Job requisition ID, aka Posting ID. Unique per job.' + # language_code = 'en-US' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(company_id, six.binary_type): + company_id = company_id.decode("utf-8") + + # Custom attribute can be string or numeric value, + # and can be filtered in search queries. + # https://cloud.google.com/talent-solution/job-search/docs/custom-attributes + custom_attribute = talent.CustomAttribute() + custom_attribute.filterable = True + custom_attribute.string_values.append("Intern") + custom_attribute.string_values.append("Apprenticeship") + + parent = f"projects/{project_id}/tenants/{tenant_id}" + + job = talent.Job( + company=company_id, + title="Software Engineer", + requisition_id=requisition_id, + description="This is a description of this job", + language_code="en-us", + custom_attributes={"FOR_STUDENTS": custom_attribute} + ) + + response = client.create_job(parent=parent, job=job) + print(f"Created job: {response.name}") + return response.name + + +# [END job_search_create_job_custom_attributes] diff --git a/samples/snippets/job_search_create_job_custom_attributes_test.py b/samples/snippets/job_search_create_job_custom_attributes_test.py new file mode 100644 index 00000000..028fedb7 --- /dev/null +++ b/samples/snippets/job_search_create_job_custom_attributes_test.py @@ -0,0 +1,46 @@ +# 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. + +import os +import uuid + +import pytest + +import job_search_create_job_custom_attributes +import job_search_delete_job + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] +JOB_EXT_UNIQUE_ID = "TEST_JOB_{}".format(uuid.uuid4()) + + +def test_create_job_with_attributes(capsys, tenant, company, cleaner): + job_name = job_search_create_job_custom_attributes.create_job( + PROJECT_ID, tenant, company, JOB_EXT_UNIQUE_ID + ) + out, _ = capsys.readouterr() + assert "Created job:" in out + + # extract job id + job_id = job_name.split("/")[-1] + cleaner.append(job_id) + + +@pytest.fixture(scope="module") +def cleaner(tenant): + jobs = [] + + yield jobs + + for job_id in jobs: + job_search_delete_job.delete_job(PROJECT_ID, tenant, job_id) diff --git a/samples/snippets/job_search_create_job_test.py b/samples/snippets/job_search_create_job_test.py new file mode 100644 index 00000000..505d27f6 --- /dev/null +++ b/samples/snippets/job_search_create_job_test.py @@ -0,0 +1,47 @@ +# 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. + +import os +import uuid + +import pytest + +import job_search_create_job +import job_search_delete_job + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] +JOB_EXT_UNIQUE_ID = "TEST_JOB_{}".format(uuid.uuid4()) + + +def test_create_job(capsys, tenant, company, cleaner): + # create a job + job_name = job_search_create_job.create_job( + PROJECT_ID, tenant, company, JOB_EXT_UNIQUE_ID, "www.example.com" + ) + out, _ = capsys.readouterr() + assert "Created job:" in out + + # extract job id + job_id = job_name.split("/")[-1] + cleaner.append(job_id) + + +@pytest.fixture(scope="module") +def cleaner(tenant): + jobs = [] + + yield jobs + + for job_id in jobs: + job_search_delete_job.delete_job(PROJECT_ID, tenant, job_id) diff --git a/samples/snippets/job_search_create_tenant.py b/samples/snippets/job_search_create_tenant.py new file mode 100644 index 00000000..4d9760e0 --- /dev/null +++ b/samples/snippets/job_search_create_tenant.py @@ -0,0 +1,43 @@ +# 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 +# +# https://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. + +# [START job_search_create_tenant] + +from google.cloud import talent +import six + + +def create_tenant(project_id, external_id): + """Create Tenant for scoping resources, e.g. companies and jobs""" + + client = talent.TenantServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # external_id = 'Your Unique Identifier for Tenant' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(external_id, six.binary_type): + external_id = external_id.decode("utf-8") + parent = f"projects/{project_id}" + tenant = talent.Tenant(external_id=external_id) + + response = client.create_tenant(parent=parent, tenant=tenant) + print("Created Tenant") + print(f"Name: {response.name}") + print(f"External ID: {response.external_id}") + return response.name + + +# [END job_search_create_tenant] diff --git a/samples/snippets/job_search_create_tenant_test.py b/samples/snippets/job_search_create_tenant_test.py new file mode 100644 index 00000000..e8c9c049 --- /dev/null +++ b/samples/snippets/job_search_create_tenant_test.py @@ -0,0 +1,48 @@ +# 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. + +import os +import uuid + +import pytest + +import job_search_create_tenant +import job_search_delete_tenant + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] +TENANT_EXT_UNIQUE_ID = "TEST_TENANT_{}".format(uuid.uuid4()) + + +def test_create_tenant(capsys, cleaner): + # create tenant + tenant_name = job_search_create_tenant.create_tenant( + PROJECT_ID, TENANT_EXT_UNIQUE_ID + ) + out, _ = capsys.readouterr() + assert "Created Tenant" in out + assert "Name:" in out + + # extract tenant id + tenant_id = tenant_name.split("/")[-1] + cleaner.append(tenant_id) + + +@pytest.fixture(scope="module") +def cleaner(): + tenants = [] + + yield tenants + + for tenant_id in tenants: + job_search_delete_tenant.delete_tenant(PROJECT_ID, tenant_id) diff --git a/samples/snippets/job_search_custom_ranking_search.py b/samples/snippets/job_search_custom_ranking_search.py new file mode 100644 index 00000000..015291e4 --- /dev/null +++ b/samples/snippets/job_search_custom_ranking_search.py @@ -0,0 +1,68 @@ +# 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 +# +# https://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. + +# [START job_search_custom_ranking_search] + +from google.cloud import talent +import six + + +def search_jobs(project_id, tenant_id): + """Search Jobs using custom rankings""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + domain = "www.example.com" + session_id = "Hashed session identifier" + user_id = "Hashed user identifier" + request_metadata = talent.RequestMetadata( + domain=domain, + session_id=session_id, + user_id=user_id + ) + importance_level = talent.SearchJobsRequest.CustomRankingInfo.ImportanceLevel.EXTREME + ranking_expression = "(someFieldLong + 25) * 0.25" + custom_ranking_info = { + "importance_level": importance_level, + "ranking_expression": ranking_expression, + } + order_by = "custom_ranking desc" + + # Iterate over all results + results = [] + request = talent.SearchJobsRequest( + parent=parent, + request_metadata=request_metadata, + custom_ranking_info=custom_ranking_info, + order_by=order_by + ) + for response_item in client.search_jobs(request=request): + print(f"Job summary: {response_item.job_summary}") + print(f"Job title snippet: {response_item.job_title_snippet}") + job = response_item.job + results.append(job.name) + print(f"Job name: {job.name}") + print(f"Job title: {job.title}") + return results + + +# [END job_search_custom_ranking_search] diff --git a/samples/snippets/job_search_custom_ranking_search_test.py b/samples/snippets/job_search_custom_ranking_search_test.py new file mode 100644 index 00000000..3a8e80bc --- /dev/null +++ b/samples/snippets/job_search_custom_ranking_search_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_custom_ranking_search + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_search_jobs_custom_ranking(tenant): + jobs = job_search_custom_ranking_search.search_jobs(PROJECT_ID, tenant) + for job in jobs: + assert "projects/" in job diff --git a/samples/snippets/job_search_delete_company.py b/samples/snippets/job_search_delete_company.py new file mode 100644 index 00000000..98174db5 --- /dev/null +++ b/samples/snippets/job_search_delete_company.py @@ -0,0 +1,42 @@ +# 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 +# +# https://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. + +# [START job_search_delete_company] + +from google.cloud import talent +import six + + +def delete_company(project_id, tenant_id, company_id): + """Delete Company""" + + client = talent.CompanyServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # company_id = 'ID of the company to delete' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(company_id, six.binary_type): + company_id = company_id.decode("utf-8") + name = client.company_path(project_id, tenant_id, company_id) + + client.delete_company(name=name) + print("Deleted company") + + +# [END job_search_delete_company] diff --git a/samples/snippets/job_search_delete_company_test.py b/samples/snippets/job_search_delete_company_test.py new file mode 100644 index 00000000..f581935b --- /dev/null +++ b/samples/snippets/job_search_delete_company_test.py @@ -0,0 +1,27 @@ +# 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. + +import os + +import job_search_delete_company + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_delete_company(capsys, tenant, company): + out, _ = capsys.readouterr() + + job_search_delete_company.delete_company(PROJECT_ID, tenant, company) + out, _ = capsys.readouterr() + assert "Deleted" in out diff --git a/samples/snippets/job_search_delete_job.py b/samples/snippets/job_search_delete_job.py new file mode 100644 index 00000000..ba165590 --- /dev/null +++ b/samples/snippets/job_search_delete_job.py @@ -0,0 +1,42 @@ +# 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 +# +# https://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. + +# [START job_search_delete_job] + +from google.cloud import talent +import six + + +def delete_job(project_id, tenant_id, job_id): + """Delete Job""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # job_id = 'Company ID' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(job_id, six.binary_type): + job_id = job_id.decode("utf-8") + name = client.job_path(project_id, tenant_id, job_id) + + client.delete_job(name=name) + print("Deleted job.") + + +# [END job_search_delete_job] diff --git a/samples/snippets/job_search_delete_job_test.py b/samples/snippets/job_search_delete_job_test.py new file mode 100644 index 00000000..ef151a2b --- /dev/null +++ b/samples/snippets/job_search_delete_job_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_delete_job + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_delete_job(capsys, tenant, job): + job_search_delete_job.delete_job(PROJECT_ID, tenant, job) + out, _ = capsys.readouterr() + assert "Deleted" in out diff --git a/samples/snippets/job_search_delete_tenant.py b/samples/snippets/job_search_delete_tenant.py new file mode 100644 index 00000000..5db49c1c --- /dev/null +++ b/samples/snippets/job_search_delete_tenant.py @@ -0,0 +1,39 @@ +# 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 +# +# https://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. + +# [START job_search_delete_tenant] + +from google.cloud import talent +import six + + +def delete_tenant(project_id, tenant_id): + """Delete Tenant""" + + client = talent.TenantServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID)' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + name = client.tenant_path(project_id, tenant_id) + + client.delete_tenant(name=name) + print("Deleted Tenant.") + + +# [END job_search_delete_tenant] diff --git a/samples/snippets/job_search_delete_tenant_test.py b/samples/snippets/job_search_delete_tenant_test.py new file mode 100644 index 00000000..a2fc490b --- /dev/null +++ b/samples/snippets/job_search_delete_tenant_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_delete_tenant + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_delete_tenant(capsys, tenant): + job_search_delete_tenant.delete_tenant(PROJECT_ID, tenant) + out, _ = capsys.readouterr() + assert "Deleted" in out diff --git a/samples/snippets/job_search_get_company.py b/samples/snippets/job_search_get_company.py new file mode 100644 index 00000000..f597da89 --- /dev/null +++ b/samples/snippets/job_search_get_company.py @@ -0,0 +1,43 @@ +# 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 +# +# https://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. + +# [START job_search_get_company] + +from google.cloud import talent +import six + + +def get_company(project_id, tenant_id, company_id): + """Get Company""" + + client = talent.CompanyServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # company_id = 'Company ID' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(company_id, six.binary_type): + company_id = company_id.decode("utf-8") + name = client.company_path(project_id, tenant_id, company_id) + + response = client.get_company(name=name) + print(f"Company name: {response.name}") + print(f"Display name: {response.display_name}") + + +# [END job_search_get_company] diff --git a/samples/snippets/job_search_get_company_test.py b/samples/snippets/job_search_get_company_test.py new file mode 100644 index 00000000..f1126330 --- /dev/null +++ b/samples/snippets/job_search_get_company_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_get_company + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_job_search_get_company(capsys, tenant, company): + job_search_get_company.get_company(PROJECT_ID, tenant, company) + out, _ = capsys.readouterr() + assert "Company name:" in out diff --git a/samples/snippets/job_search_get_job.py b/samples/snippets/job_search_get_job.py new file mode 100644 index 00000000..cef60889 --- /dev/null +++ b/samples/snippets/job_search_get_job.py @@ -0,0 +1,52 @@ +# 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 +# +# https://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. + +# [START job_search_get_job] + +from google.cloud import talent +import six + + +def get_job(project_id, tenant_id, job_id): + """Get Job""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # job_id = 'Job ID' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(job_id, six.binary_type): + job_id = job_id.decode("utf-8") + name = client.job_path(project_id, tenant_id, job_id) + + response = client.get_job(name=name) + print(f"Job name: {response.name}") + print(f"Requisition ID: {response.requisition_id}") + print(f"Title: {response.title}") + print(f"Description: {response.description}") + print(f"Posting language: {response.language_code}") + for address in response.addresses: + print(f"Address: {address}") + for email in response.application_info.emails: + print(f"Email: {email}") + for website_uri in response.application_info.uris: + print(f"Website: {website_uri}") + + +# [END job_search_get_job] diff --git a/samples/snippets/job_search_get_job_test.py b/samples/snippets/job_search_get_job_test.py new file mode 100644 index 00000000..264c5772 --- /dev/null +++ b/samples/snippets/job_search_get_job_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_get_job + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_job_search_get_job(capsys, tenant, job): + job_search_get_job.get_job(PROJECT_ID, tenant, job) + out, _ = capsys.readouterr() + assert "Job name:" in out diff --git a/samples/snippets/job_search_get_tenant.py b/samples/snippets/job_search_get_tenant.py new file mode 100644 index 00000000..1799c556 --- /dev/null +++ b/samples/snippets/job_search_get_tenant.py @@ -0,0 +1,40 @@ +# 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 +# +# https://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. + +# [START job_search_get_tenant] + +from google.cloud import talent +import six + + +def get_tenant(project_id, tenant_id): + """Get Tenant by name""" + + client = talent.TenantServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + name = client.tenant_path(project_id, tenant_id) + + response = client.get_tenant(name=name) + print(f"Name: {response.name}") + print(f"External ID: {response.external_id}") + + +# [END job_search_get_tenant] diff --git a/samples/snippets/job_search_get_tenant_test.py b/samples/snippets/job_search_get_tenant_test.py new file mode 100644 index 00000000..d1f8c1cd --- /dev/null +++ b/samples/snippets/job_search_get_tenant_test.py @@ -0,0 +1,26 @@ +# 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. + + +import os + +import job_search_get_tenant + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_get_tenant(capsys, tenant): + job_search_get_tenant.get_tenant(PROJECT_ID, tenant) + out, _ = capsys.readouterr() + assert "Name: " in out diff --git a/samples/snippets/job_search_histogram_search.py b/samples/snippets/job_search_histogram_search.py new file mode 100644 index 00000000..73bbc974 --- /dev/null +++ b/samples/snippets/job_search_histogram_search.py @@ -0,0 +1,68 @@ +# 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 +# +# https://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. + +# [START job_search_histogram_search] + +from google.cloud import talent +import six + + +def search_jobs(project_id, tenant_id, query): + """ + Search Jobs with histogram queries + + Args: + query Histogram query + More info on histogram facets, constants, and built-in functions: + https://godoc.org/google.golang.org/genproto/googleapis/cloud/talent/v4beta1#SearchJobsRequest + """ + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # query = 'count(base_compensation, [bucket(12, 20)])' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(query, six.binary_type): + query = query.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + domain = "www.example.com" + session_id = "Hashed session identifier" + user_id = "Hashed user identifier" + request_metadata = {"domain": domain, "session_id": session_id, "user_id": user_id} + histogram_queries_element = {"histogram_query": query} + histogram_queries = [histogram_queries_element] + + # Iterate over all results + results = [] + request = talent.SearchJobsRequest( + parent=parent, + request_metadata=request_metadata, + histogram_queries=histogram_queries, + ) + for response_item in client.search_jobs(request=request): + print("Job summary: {response_item.job_summary}") + print("Job title snippet: {response_item.job_title_snippet}") + job = response_item.job + results.append(job) + print("Job name: {job.name}") + print("Job title: {job.title}") + return results + + +# [END job_search_histogram_search] diff --git a/samples/snippets/job_search_histogram_search_test.py b/samples/snippets/job_search_histogram_search_test.py new file mode 100644 index 00000000..1f6594de --- /dev/null +++ b/samples/snippets/job_search_histogram_search_test.py @@ -0,0 +1,26 @@ +# 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. + +import os + +import job_search_histogram_search + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_search_jobs_histogram(tenant): + query = "count(base_compensation, [bucket(12, 20)])" + jobs = job_search_histogram_search.search_jobs(PROJECT_ID, tenant, query) + for job in jobs: + assert "projects/" in job diff --git a/samples/snippets/job_search_list_companies.py b/samples/snippets/job_search_list_companies.py new file mode 100644 index 00000000..4cad5a4d --- /dev/null +++ b/samples/snippets/job_search_list_companies.py @@ -0,0 +1,45 @@ +# 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 +# +# https://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. + +# [START job_search_list_companies] + +from google.cloud import talent +import six + + +def list_companies(project_id, tenant_id): + """List Companies""" + + client = talent.CompanyServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + + # Iterate over all results + results = [] + for company in client.list_companies(parent=parent): + results.append(company.name) + print(f"Company Name: {company.name}") + print(f"Display Name: {company.display_name}") + print(f"External ID: {company.external_id}") + return results + + +# [END job_search_list_companies] diff --git a/samples/snippets/job_search_list_companies_test.py b/samples/snippets/job_search_list_companies_test.py new file mode 100644 index 00000000..c8d71a85 --- /dev/null +++ b/samples/snippets/job_search_list_companies_test.py @@ -0,0 +1,25 @@ +# 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. + +import os + +import job_search_list_companies + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_list_companies(tenant): + results = job_search_list_companies.list_companies(PROJECT_ID, tenant) + for company in results: + assert "projects/" in company.name diff --git a/samples/snippets/job_search_list_jobs.py b/samples/snippets/job_search_list_jobs.py new file mode 100644 index 00000000..fd164bf7 --- /dev/null +++ b/samples/snippets/job_search_list_jobs.py @@ -0,0 +1,49 @@ +# 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 +# +# https://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. + +# [START job_search_list_jobs] + +from google.cloud import talent +import six + + +def list_jobs(project_id, tenant_id, filter_): + """List Jobs""" + + client = talent.JobServiceClient() + + # project_id = 'Your Google Cloud Project ID' + # tenant_id = 'Your Tenant ID (using tenancy is optional)' + # filter_ = 'companyName=projects/my-project/companies/company-id' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + if isinstance(tenant_id, six.binary_type): + tenant_id = tenant_id.decode("utf-8") + if isinstance(filter_, six.binary_type): + filter_ = filter_.decode("utf-8") + parent = f"projects/{project_id}/tenants/{tenant_id}" + + # Iterate over all results + results = [] + for job in client.list_jobs(parent=parent, filter=filter_): + results.append(job.name) + print("Job name: {job.name}") + print("Job requisition ID: {job.requisition_id}") + print("Job title: {job.title}") + print("Job description: {job.description}") + return results + + +# [END job_search_list_jobs] diff --git a/samples/snippets/job_search_list_jobs_test.py b/samples/snippets/job_search_list_jobs_test.py new file mode 100644 index 00000000..a2187fd9 --- /dev/null +++ b/samples/snippets/job_search_list_jobs_test.py @@ -0,0 +1,26 @@ +# 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. + +import os + +import job_search_list_jobs + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_list_jobs(capsys, tenant, company): + filter = 'companyName="projects/{}/companies/{}"'.format(PROJECT_ID, company) + jobs = job_search_list_jobs.list_jobs(PROJECT_ID, tenant, filter) + for job in jobs: + assert "projects/" in job diff --git a/samples/snippets/job_search_list_tenants.py b/samples/snippets/job_search_list_tenants.py new file mode 100644 index 00000000..65239855 --- /dev/null +++ b/samples/snippets/job_search_list_tenants.py @@ -0,0 +1,38 @@ +# 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 +# +# https://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. + +# [START job_search_list_tenants] + +from google.cloud import talent +import six + + +def list_tenants(project_id): + """List Tenants""" + + client = talent.TenantServiceClient() + + # project_id = 'Your Google Cloud Project ID' + + if isinstance(project_id, six.binary_type): + project_id = project_id.decode("utf-8") + parent = f"projects/{project_id}" + + # Iterate over all results + for response_item in client.list_tenants(parent=parent): + print(f"Tenant Name: {response_item.name}") + print(f"External ID: {response_item.external_id}") + + +# [END job_search_list_tenants] diff --git a/samples/snippets/job_search_list_tenants_test.py b/samples/snippets/job_search_list_tenants_test.py new file mode 100644 index 00000000..b12f2605 --- /dev/null +++ b/samples/snippets/job_search_list_tenants_test.py @@ -0,0 +1,42 @@ +# 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. + +import os +import uuid + +from google.cloud import talent +import pytest + +import job_search_list_tenants + +PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] + + +@pytest.fixture(scope="module") +def test_tenant(): + client = talent.TenantServiceClient() + external_id = f'test_tenant_{uuid.uuid4().hex}' + parent = f"projects/{PROJECT_ID}" + tenant = {"external_id": external_id} + resp = client.create_tenant(parent=parent, tenant=tenant) + + yield resp + + client.delete_tenant(name=resp.name) + + +def test_list_tenants(capsys, test_tenant): + job_search_list_tenants.list_tenants(PROJECT_ID) + out, _ = capsys.readouterr() + assert "Tenant Name:" in out diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py new file mode 100644 index 00000000..ba55d7ce --- /dev/null +++ b/samples/snippets/noxfile.py @@ -0,0 +1,224 @@ +# 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. +# 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] + + # 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) + + +# +# 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/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py new file mode 100644 index 00000000..cfd0d439 --- /dev/null +++ b/samples/snippets/noxfile_config.py @@ -0,0 +1,37 @@ +# 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. + +# Default TEST_CONFIG_OVERRIDE for python repos. + +# You can copy this file into your directory, then it will be inported from +# the noxfile.py. + +# The source of truth: +# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py + +TEST_CONFIG_OVERRIDE = { + # 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': {}, +} diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt new file mode 100644 index 00000000..7e460c8c --- /dev/null +++ b/samples/snippets/requirements-test.txt @@ -0,0 +1 @@ +pytest==6.0.1 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt new file mode 100755 index 00000000..9db6aba9 --- /dev/null +++ b/samples/snippets/requirements.txt @@ -0,0 +1 @@ +google.cloud.talent==0.6.1 \ No newline at end of file diff --git a/synth.py b/synth.py index 529dad28..78cbbc9e 100644 --- a/synth.py +++ b/synth.py @@ -16,6 +16,7 @@ import synthtool as s from synthtool import gcp +from synthtool.languages import python gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() @@ -51,7 +52,7 @@ # Add templated files # ---------------------------------------------------------------------------- templated_files = common.py_library( - samples=False, # set to True only if there are samples + samples=True, # set to True only if there are samples microgenerator=True, cov_level=99, ) @@ -61,4 +62,10 @@ # https://github.com/googleapis/gapic-generator-python/issues/525 s.replace("noxfile.py", '[\"\']-W[\"\']', '# "-W"') +# ---------------------------------------------------------------------------- +# Samples templates +# ---------------------------------------------------------------------------- + +python.py_samples(skip_readmes=True) + s.shell.run(["nox", "-s", "blacken"], hide_output=False)