diff --git a/google/cloud/ndb/_cache.py b/google/cloud/ndb/_cache.py index bab0341f..cc5fca09 100644 --- a/google/cloud/ndb/_cache.py +++ b/google/cloud/ndb/_cache.py @@ -49,6 +49,9 @@ def get_and_validate(self, key): del self.data[key] raise KeyError(key) + def __repr__(self): + return "ContextCache()" + def _future_result(result): """Returns a completed Future with the given result. diff --git a/tests/system/test_misc.py b/tests/system/test_misc.py index 5f37a4f8..de0f177a 100644 --- a/tests/system/test_misc.py +++ b/tests/system/test_misc.py @@ -17,11 +17,18 @@ """ import os import pickle +import traceback + +try: + from unittest import mock +except ImportError: # pragma: NO PY3 COVER + import mock import pytest import test_utils.system +from google.api_core import exceptions as core_exceptions from google.cloud import ndb from . import eventually, length_equals, KIND @@ -315,3 +322,27 @@ class SomeKind(ndb.Model): entity = key.get() assert entity.bar == 42 + + +@mock.patch("google.cloud.ndb._datastore_api.begin_transaction") +def test_do_not_disclose_cache_contents(begin_transaction, client_context): + """Regression test for #482. + + https://github.com/googleapis/python-ndb/issues/482 + """ + begin_transaction.side_effect = core_exceptions.ServiceUnavailable( + "Spurious Error" + ) + + client_context.cache["hello dad"] = "i'm in jail" + + @ndb.transactional() + def callback(): + pass + + with pytest.raises(Exception) as error_info: + callback() + + error = error_info.value + message = "".join(traceback.format_exception_only(type(error), error)) + assert "hello dad" not in message diff --git a/tests/unit/test__cache.py b/tests/unit/test__cache.py index c3c8e85b..cd6afb1e 100644 --- a/tests/unit/test__cache.py +++ b/tests/unit/test__cache.py @@ -58,6 +58,12 @@ def test_get_and_validate_miss(): with pytest.raises(KeyError): cache.get_and_validate("nonexistent_key") + @staticmethod + def test___repr__(): + cache = _cache.ContextCache() + cache["hello dad"] = "i'm in jail" + assert repr(cache) == "ContextCache()" + class Test_GlobalCacheBatch: @staticmethod