test_to_markdown.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from io import StringIO
  2. import pytest
  3. import pandas as pd
  4. pytest.importorskip("tabulate")
  5. def test_simple():
  6. buf = StringIO()
  7. df = pd.DataFrame([1, 2, 3])
  8. df.to_markdown(buf=buf)
  9. result = buf.getvalue()
  10. assert (
  11. result == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
  12. )
  13. def test_empty_frame():
  14. buf = StringIO()
  15. df = pd.DataFrame({"id": [], "first_name": [], "last_name": []}).set_index("id")
  16. df.to_markdown(buf=buf)
  17. result = buf.getvalue()
  18. assert result == (
  19. "| id | first_name | last_name |\n"
  20. "|------|--------------|-------------|"
  21. )
  22. def test_other_tablefmt():
  23. buf = StringIO()
  24. df = pd.DataFrame([1, 2, 3])
  25. df.to_markdown(buf=buf, tablefmt="jira")
  26. result = buf.getvalue()
  27. assert result == "|| || 0 ||\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
  28. def test_other_headers():
  29. buf = StringIO()
  30. df = pd.DataFrame([1, 2, 3])
  31. df.to_markdown(buf=buf, headers=["foo", "bar"])
  32. result = buf.getvalue()
  33. assert result == (
  34. "| foo | bar |\n|------:|------:|\n| 0 "
  35. "| 1 |\n| 1 | 2 |\n| 2 | 3 |"
  36. )
  37. def test_series():
  38. buf = StringIO()
  39. s = pd.Series([1, 2, 3], name="foo")
  40. s.to_markdown(buf=buf)
  41. result = buf.getvalue()
  42. assert result == (
  43. "| | foo |\n|---:|------:|\n| 0 | 1 "
  44. "|\n| 1 | 2 |\n| 2 | 3 |"
  45. )
  46. def test_no_buf():
  47. df = pd.DataFrame([1, 2, 3])
  48. result = df.to_markdown()
  49. assert (
  50. result == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
  51. )
  52. @pytest.mark.parametrize("index", [True, False])
  53. def test_index(index):
  54. # GH 32667
  55. df = pd.DataFrame([1, 2, 3])
  56. result = df.to_markdown(index=index)
  57. if index:
  58. expected = (
  59. "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
  60. )
  61. else:
  62. expected = "| 0 |\n|----:|\n| 1 |\n| 2 |\n| 3 |"
  63. assert result == expected
  64. def test_showindex_disallowed_in_kwargs():
  65. # GH 32667; disallowing showindex in kwargs enforced in 2.0
  66. df = pd.DataFrame([1, 2, 3])
  67. with pytest.raises(ValueError, match="Pass 'index' instead of 'showindex"):
  68. df.to_markdown(index=True, showindex=True)