Skip to content

Commit

Permalink
py: implement str.lower and str.upper
Browse files Browse the repository at this point in the history
Updates #232
  • Loading branch information
wdq112 authored Feb 26, 2024
1 parent 23c0aa2 commit 149d52c
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
16 changes: 16 additions & 0 deletions py/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,14 @@ replaced.`)
return self.(String).LStrip(args)
}, 0, "lstrip(chars) -> replace chars from begining of string")

StringType.Dict["upper"] = MustNewMethod("upper", func(self Object, args Tuple, kwargs StringDict) (Object, error) {
return self.(String).Upper()
}, 0, "upper() -> a copy of the string converted to uppercase")

StringType.Dict["lower"] = MustNewMethod("lower", func(self Object, args Tuple, kwargs StringDict) (Object, error) {
return self.(String).Lower()
}, 0, "lower() -> a copy of the string converted to lowercase")

}

// Type of this object
Expand Down Expand Up @@ -739,6 +747,14 @@ func (s String) RStrip(args Tuple) (Object, error) {
return String(strings.TrimRightFunc(string(s), f)), nil
}

func (s String) Upper() (Object, error) {
return String(strings.ToUpper(string(s))), nil
}

func (s String) Lower() (Object, error) {
return String(strings.ToLower(string(s))), nil
}

// Check stringerface is satisfied
var (
_ richComparison = String("")
Expand Down
46 changes: 46 additions & 0 deletions py/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,49 @@ func TestStringFind(t *testing.T) {
})
}
}

func TestStringUpper(t *testing.T) {
tests := []struct {
name string
s String
want Object
}{{
name: "abc",
s: String("abc"),
want: String("ABC")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.s.Upper()
if err != nil {
t.Fatalf("Upper() error = %v", err)
}
if got.(String) != tt.want.(String) {
t.Fatalf("Upper() got = %v, want %v", got, tt.want)
}
})
}
}

func TestStringLower(t *testing.T) {
tests := []struct {
name string
s String
want Object
}{{
name: "ABC",
s: String("ABC"),
want: String("abc")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.s.Lower()
if err != nil {
t.Fatalf("Lower() error = %v", err)
}
if got.(String) != tt.want.(String) {
t.Fatalf("Lower() got = %v, want %v", got, tt.want)
}
})
}
}
8 changes: 8 additions & 0 deletions py/tests/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,14 @@ def index(s, i):
assert a.lstrip("a ") == "bada a"
assert a.strip("a ") == "bad"

doc="upper"
a = "abc"
assert a.upper() == "ABC"

doc="lower"
a = "ABC"
assert a.lower() == "abc"

class Index:
def __index__(self):
return 1
Expand Down

0 comments on commit 149d52c

Please sign in to comment.