test_console.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import locale
  2. import pytest
  3. from pandas._config import detect_console_encoding
  4. class MockEncoding:
  5. """
  6. Used to add a side effect when accessing the 'encoding' property. If the
  7. side effect is a str in nature, the value will be returned. Otherwise, the
  8. side effect should be an exception that will be raised.
  9. """
  10. def __init__(self, encoding) -> None:
  11. super().__init__()
  12. self.val = encoding
  13. @property
  14. def encoding(self):
  15. return self.raise_or_return(self.val)
  16. @staticmethod
  17. def raise_or_return(val):
  18. if isinstance(val, str):
  19. return val
  20. else:
  21. raise val
  22. @pytest.mark.parametrize("empty,filled", [["stdin", "stdout"], ["stdout", "stdin"]])
  23. def test_detect_console_encoding_from_stdout_stdin(monkeypatch, empty, filled):
  24. # Ensures that when sys.stdout.encoding or sys.stdin.encoding is used when
  25. # they have values filled.
  26. # GH 21552
  27. with monkeypatch.context() as context:
  28. context.setattr(f"sys.{empty}", MockEncoding(""))
  29. context.setattr(f"sys.{filled}", MockEncoding(filled))
  30. assert detect_console_encoding() == filled
  31. @pytest.mark.parametrize("encoding", [AttributeError, OSError, "ascii"])
  32. def test_detect_console_encoding_fallback_to_locale(monkeypatch, encoding):
  33. # GH 21552
  34. with monkeypatch.context() as context:
  35. context.setattr("locale.getpreferredencoding", lambda: "foo")
  36. context.setattr("sys.stdout", MockEncoding(encoding))
  37. assert detect_console_encoding() == "foo"
  38. @pytest.mark.parametrize(
  39. "std,locale",
  40. [
  41. ["ascii", "ascii"],
  42. ["ascii", locale.Error],
  43. [AttributeError, "ascii"],
  44. [AttributeError, locale.Error],
  45. [OSError, "ascii"],
  46. [OSError, locale.Error],
  47. ],
  48. )
  49. def test_detect_console_encoding_fallback_to_default(monkeypatch, std, locale):
  50. # When both the stdout/stdin encoding and locale preferred encoding checks
  51. # fail (or return 'ascii', we should default to the sys default encoding.
  52. # GH 21552
  53. with monkeypatch.context() as context:
  54. context.setattr(
  55. "locale.getpreferredencoding", lambda: MockEncoding.raise_or_return(locale)
  56. )
  57. context.setattr("sys.stdout", MockEncoding(std))
  58. context.setattr("sys.getdefaultencoding", lambda: "sysDefaultEncoding")
  59. assert detect_console_encoding() == "sysDefaultEncoding"