Skip to content

Commit e0b4d5e

Browse files
committed
Add tests for trim methods
1 parent b7a021f commit e0b4d5e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Tests/RegexTests/AlgorithmsTests.swift

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ func output<T>(_ s: @autoclosure () -> T) {
2424
}
2525
}
2626

27+
func makeSingleUseSequence<T>(element: T, count: Int) -> UnfoldSequence<T, Void> {
28+
var count = count
29+
return sequence(state: ()) { _ in
30+
defer { count -= 1 }
31+
return count > 0 ? element : nil
32+
}
33+
}
34+
2735
class RegexConsumerTests: XCTestCase {
2836
func testRanges() {
2937
func expectRanges(
@@ -79,6 +87,53 @@ class RegexConsumerTests: XCTestCase {
7987
expectSplit("a", "", ["", "a", ""])
8088
expectSplit("a", "x", ["a"])
8189
expectSplit("a", "a", ["", ""])
90+
91+
func testTrim() {
92+
func expectTrim(
93+
_ string: String,
94+
_ regex: String,
95+
_ expected: Substring,
96+
file: StaticString = #file, line: UInt = #line
97+
) {
98+
let regex = try! Regex(regex)
99+
let actual = string.trimmingPrefix(regex)
100+
XCTAssertEqual(actual, expected, file: file, line: line)
101+
}
102+
103+
expectTrim("", "", "")
104+
expectTrim("", "x", "")
105+
expectTrim("a", "", "a")
106+
expectTrim("a", "x", "a")
107+
expectTrim("___a", "_", "__a")
108+
expectTrim("___a", "_+", "a")
109+
110+
XCTAssertEqual("".trimmingPrefix("a"), "")
111+
XCTAssertEqual("a".trimmingPrefix("a"), "")
112+
XCTAssertEqual("b".trimmingPrefix("a"), "b")
113+
XCTAssertEqual("a".trimmingPrefix(""), "a")
114+
XCTAssertEqual("___a".trimmingPrefix("_"), "__a")
115+
XCTAssertEqual("___a".trimmingPrefix("___"), "a")
116+
XCTAssertEqual("___a".trimmingPrefix("____"), "___a")
117+
XCTAssertEqual("___a".trimmingPrefix("___a"), "")
118+
119+
do {
120+
let prefix = makeSingleUseSequence(element: "_" as Character, count: 5)
121+
XCTAssertEqual("_____a".trimmingPrefix(prefix), "a")
122+
XCTAssertEqual("_____a".trimmingPrefix(prefix), "_____a")
123+
}
124+
do {
125+
let prefix = makeSingleUseSequence(element: "_" as Character, count: 5)
126+
XCTAssertEqual("a".trimmingPrefix(prefix), "a")
127+
// The result of this next call is technically undefined, so this
128+
// is just to test that it doesn't crash.
129+
XCTAssertNotEqual("_____a".trimmingPrefix(prefix), "")
130+
}
131+
132+
XCTAssertEqual("".trimmingPrefix(while: \.isWhitespace), "")
133+
XCTAssertEqual("a".trimmingPrefix(while: \.isWhitespace), "a")
134+
XCTAssertEqual(" ".trimmingPrefix(while: \.isWhitespace), "")
135+
XCTAssertEqual(" a".trimmingPrefix(while: \.isWhitespace), "a")
136+
XCTAssertEqual("a ".trimmingPrefix(while: \.isWhitespace), "a ")
82137
}
83138

84139
func testReplace() {

0 commit comments

Comments
 (0)