anonymization_unittest.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright 2024 The Chromium Authors
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Test the config and anonymizer utils."""
  5. import getpass
  6. import re
  7. import pytest
  8. from .proto import trace_span_pb2
  9. from . import anonymization
  10. def test_anonymizing_filter_to_redact_info_from_msg() -> None:
  11. """Test AnonymizingFilter to apply the passed anonymizer to msg."""
  12. msg = trace_span_pb2.TraceSpan()
  13. msg.name = "log-user-user1234"
  14. anonymizer = anonymization.Anonymizer([(re.escape("user1234"), "<user>")])
  15. f = anonymization.AnonymizingFilter(anonymizer)
  16. filtered_msg = f(msg)
  17. assert filtered_msg.name == "log-user-<user>"
  18. def test_default_anonymizer_to_remove_username_from_path(monkeypatch) -> None:
  19. """Test that default Anonymizer redacts username."""
  20. monkeypatch.setattr(getpass, "getuser", lambda: "user")
  21. a = anonymization.Anonymizer()
  22. output = a.apply("/home/user/docs")
  23. assert output == "/home/<user>/docs"
  24. def test_anonymizer_to_apply_passed_replacements() -> None:
  25. """Test anonymizer to apply the requested replacements."""
  26. text = "/home/%s/docs" % getpass.getuser()
  27. replacements = [(re.escape(getpass.getuser()), "<user>")]
  28. a = anonymization.Anonymizer(replacements=replacements)
  29. output = a.apply(text)
  30. assert output == "/home/<user>/docs"
  31. def test_anonymizer_to_apply_multiple_replacements() -> None:
  32. """Test anonymizer to apply the passed replacements in order."""
  33. replacements = [(re.escape("abc"), "x"), (re.escape("xyz"), "t")]
  34. text = "hello abcd. how is xyz. abcyz"
  35. a = anonymization.Anonymizer(replacements=replacements)
  36. output = a.apply(text)
  37. assert output == "hello xd. how is t. t"
  38. def test_default_anonymizer_skip_root(monkeypatch) -> None:
  39. """Test the anonymizer skips the root user."""
  40. monkeypatch.setattr(getpass, "getuser", lambda: "root")
  41. text = "/root/home service.sysroot.SetupBoard"
  42. a = anonymization.Anonymizer()
  43. output = a.apply(text)
  44. assert output == text