|
| 1 | +import pytest |
| 2 | + |
| 3 | +import pandas as pd |
| 4 | +import pandas._testing as tm |
| 5 | + |
| 6 | + |
| 7 | +class TestFormat: |
| 8 | + @pytest.mark.parametrize("format_str", ["Value: {}", "Value: {A}"]) |
| 9 | + @pytest.mark.parametrize("how_na", ["all", "any"]) |
| 10 | + def test_basic(self, format_str, how_na): |
| 11 | + ser = pd.Series([1, 2, 3], name="A") |
| 12 | + expected = pd.Series( |
| 13 | + ["Value: 1", "Value: 2", "Value: 3"], dtype="string", name="X" |
| 14 | + ) |
| 15 | + |
| 16 | + result = ser.format(format_str, how_na=how_na, name="X") |
| 17 | + tm.assert_series_equal(result, expected) |
| 18 | + |
| 19 | + @pytest.mark.parametrize("format_str", ["{Index}-{}", "{Index}-{A}"]) |
| 20 | + def test_with_index(self, format_str): |
| 21 | + ser = pd.Series([1, 2, 3], name="A") |
| 22 | + expected = pd.Series(["0-1", "1-2", "2-3"], dtype="string", name="X") |
| 23 | + |
| 24 | + result = ser.format(format_str, name="X") |
| 25 | + tm.assert_series_equal(result, expected) |
| 26 | + |
| 27 | + @pytest.mark.parametrize("format_str", ["Value: {}"]) |
| 28 | + @pytest.mark.parametrize("positional_only", [True, False]) |
| 29 | + def test_positional_only(self, format_str, positional_only): |
| 30 | + ser = pd.Series([1, 2, 3], name="A") |
| 31 | + expected = pd.Series(["Value: 1", "Value: 2", "Value: 3"], dtype="string") |
| 32 | + |
| 33 | + result = ser.format(format_str, positional_only=positional_only) |
| 34 | + tm.assert_series_equal(result, expected) |
| 35 | + |
| 36 | + @pytest.mark.parametrize("format_str", ["{A}-{}", "{Index}-{}"]) |
| 37 | + def test_positional_only_raises(self, format_str): |
| 38 | + ser = pd.Series([1, 2, 3], name="A") |
| 39 | + with pytest.raises(KeyError): |
| 40 | + ser.format(format_str, positional_only=True) |
| 41 | + |
| 42 | + @pytest.mark.parametrize( |
| 43 | + "how_na, expected", |
| 44 | + [("any", ["Value: 1", pd.NA, pd.NA]), ("all", ["Value: 1", pd.NA, pd.NA])], |
| 45 | + ) |
| 46 | + @pytest.mark.parametrize("format_str", ["Value: {}", "Value: {A}"]) |
| 47 | + def test_na_how(self, how_na, expected, format_str): |
| 48 | + ser = pd.Series([1, pd.NA, pd.NA], name="A") |
| 49 | + expected = pd.Series(expected, dtype="string") |
| 50 | + |
| 51 | + result = ser.format("Value: {}", how_na=how_na) |
| 52 | + tm.assert_series_equal(result, expected) |
| 53 | + |
| 54 | + @pytest.mark.parametrize("format_string", ["{}-{}", "{0}-{1}"]) |
| 55 | + def test_too_many_positional_args(self, format_string): |
| 56 | + ser = pd.Series([1, 2, 3], name="A") |
| 57 | + with pytest.raises(IndexError): |
| 58 | + ser.format(format_string) |
| 59 | + |
| 60 | + @pytest.mark.parametrize("format_string", ["{A}-{B}", "{B}"]) |
| 61 | + def test_unknown_named_args(self, format_string): |
| 62 | + ser = pd.Series([1, 2, 3], name="A") |
| 63 | + with pytest.raises(KeyError): |
| 64 | + ser.format(format_string) |
0 commit comments