|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2026 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | + |
| 17 | +import builtins |
| 18 | +import sys |
| 19 | + |
| 20 | +import mock |
| 21 | +import pytest |
| 22 | + |
| 23 | +from {{ api.naming.module_namespace }} import _compat |
| 24 | + |
| 25 | + |
| 26 | +def test_setup_request_id_fallback(): |
| 27 | + with mock.patch("sys.modules", dict(sys.modules)): |
| 28 | + if "google.api_core.gapic_v1.request" in sys.modules: |
| 29 | + del sys.modules["google.api_core.gapic_v1.request"] |
| 30 | + |
| 31 | + real_import = builtins.__import__ |
| 32 | + |
| 33 | + def mock_import(name, globals=None, locals=None, fromlist=(), level=0): |
| 34 | + if name == "google.api_core.gapic_v1.request": |
| 35 | + raise ImportError("Mocked ImportError for gapic_v1.request") |
| 36 | + return real_import(name, globals, locals, fromlist, level) |
| 37 | + |
| 38 | + with mock.patch("builtins.__import__", side_effect=mock_import): |
| 39 | + # Reload _compat to trigger the fallback path |
| 40 | + import importlib |
| 41 | + importlib.reload(_compat) |
| 42 | + |
| 43 | + # The fallback method should be defined |
| 44 | + assert hasattr(_compat, "setup_request_id") |
| 45 | + |
| 46 | + # Test it works on a dict |
| 47 | + request = {} |
| 48 | + _compat.setup_request_id(request, "request_id", True) |
| 49 | + assert "request_id" in request |
| 50 | + |
| 51 | + # Test it works on a dict when proto3 optional is False |
| 52 | + request = {} |
| 53 | + _compat.setup_request_id(request, "request_id", False) |
| 54 | + assert "request_id" in request |
| 55 | + |
| 56 | + # Reset the module state |
| 57 | + importlib.reload(_compat) |
0 commit comments