forked from JohnSundell/ShellOut
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellOutTests.swift
More file actions
241 lines (196 loc) · 9.72 KB
/
ShellOutTests.swift
File metadata and controls
241 lines (196 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/**
* ShellOut
* Copyright (c) John Sundell 2017
* Licensed under the MIT license. See LICENSE file.
*/
import XCTest
@testable import ShellOut
class ShellOutTests: XCTestCase {
func testWithoutArguments() throws {
let uptime = try shellOut(to: "uptime")
XCTAssertTrue(uptime.contains("load average"))
}
func testWithArguments() throws {
let echo = try shellOut(to: "echo", arguments: ["Hello world"])
XCTAssertEqual(echo, "Hello world")
}
func testWithInlineArguments() throws {
let echo = try shellOut(to: "echo \"Hello world\"")
XCTAssertEqual(echo, "Hello world")
}
func testSingleCommandAtPath() throws {
try shellOut(to: "echo \"Hello\" > \(NSTemporaryDirectory())ShellOutTests-SingleCommand.txt")
let textFileContent = try shellOut(to: "cat ShellOutTests-SingleCommand.txt",
at: NSTemporaryDirectory())
XCTAssertEqual(textFileContent, "Hello")
}
func testSingleCommandAtPathContainingSpace() throws {
try shellOut(to: "mkdir -p \"ShellOut Test Folder\"", at: NSTemporaryDirectory())
try shellOut(to: "echo \"Hello\" > File", at: NSTemporaryDirectory() + "ShellOut Test Folder")
let output = try shellOut(to: "cat \(NSTemporaryDirectory())ShellOut\\ Test\\ Folder/File")
XCTAssertEqual(output, "Hello")
}
func testSingleCommandAtPathContainingTilde() throws {
let homeContents = try shellOut(to: "ls", at: "~")
XCTAssertFalse(homeContents.isEmpty)
}
func testSeriesOfCommands() throws {
let echo = try shellOut(to: ["echo \"Hello\"", "echo \"world\""])
XCTAssertEqual(echo, "Hello\nworld")
}
func testSeriesOfCommandsAtPath() throws {
try shellOut(to: [
"cd \(NSTemporaryDirectory())",
"mkdir -p ShellOutTests",
"echo \"Hello again\" > ShellOutTests/MultipleCommands.txt"
])
let textFileContent = try shellOut(to: [
"cd ShellOutTests",
"cat MultipleCommands.txt"
], at: NSTemporaryDirectory())
XCTAssertEqual(textFileContent, "Hello again")
}
func testThrowingError() {
do {
try shellOut(to: "cd", arguments: ["notADirectory"])
XCTFail("Expected expression to throw")
} catch let error as ShellOutError {
XCTAssertTrue(error.message.contains("notADirectory"))
XCTAssertTrue(error.output.isEmpty)
XCTAssertTrue(error.terminationStatus != 0)
} catch {
XCTFail("Invalid error type: \(error)")
}
}
func testErrorDescription() {
let errorMessage = "Hey, I'm an error!"
let output = "Some output"
let error = ShellOutError(
terminationStatus: 7,
errorData: errorMessage.data(using: .utf8)!,
outputData: output.data(using: .utf8)!
)
let expectedErrorDescription = """
ShellOut encountered an error
Status code: 7
Message: "Hey, I'm an error!"
Output: "Some output"
"""
XCTAssertEqual("\(error)", expectedErrorDescription)
XCTAssertEqual(error.localizedDescription, expectedErrorDescription)
}
func testCapturingOutputWithFileHandle() throws {
let pipe = Pipe()
let output = try shellOut(to: "echo", arguments: ["Hello"], outputHandle: pipe.fileHandleForWriting)
let capturedData = pipe.fileHandleForReading.readDataToEndOfFile()
XCTAssertEqual(output, "Hello")
XCTAssertEqual(output + "\n", String(data: capturedData, encoding: .utf8))
}
func testMultipleCallsToStandardOut() throws {
let standardOut = FileHandle.standardOutput
/// Do not wrap these calls in XCTAssertNoThrow as it suppresses the error and the test will
/// always pass. These calls will trap if the standardOut FileHandle is closed.
try shellOut(to: "echo", arguments: ["Hello"], outputHandle: standardOut)
try shellOut(to: "echo", arguments: ["Hello"], outputHandle: standardOut)
}
func testMultipleCallsToStandardError() throws {
let standardError = FileHandle.standardError
/// Do not wrap these calls in XCTAssertNoThrow as it suppresses the error and the test will
/// always pass. These calls will trap if the standardError FileHandle is closed.
_ = try? shellOut(to: "bash 'exit 1'", arguments: [], errorHandle: standardError)
_ = try? shellOut(to: "bash 'exit 1'", arguments: [], errorHandle: standardError)
}
func testCapturingOutputWithStringHandle() throws {
var stringHandleOutput = ""
let stringHandle = TestStringHandle { stringHandleOutput.append($0) }
let output = try shellOut(to: "echo", arguments: ["Hello"], outputHandle: stringHandle)
XCTAssertEqual(output, "Hello")
XCTAssertEqual(output, stringHandleOutput)
}
func testCapturingErrorWithFileHandle() throws {
let pipe = Pipe()
do {
try shellOut(to: "cd", arguments: ["notADirectory"], errorHandle: pipe.fileHandleForWriting)
XCTFail("Expected expression to throw")
} catch let error as ShellOutError {
XCTAssertTrue(error.message.contains("notADirectory"))
XCTAssertTrue(error.output.isEmpty)
XCTAssertTrue(error.terminationStatus != 0)
let capturedData = pipe.fileHandleForReading.readDataToEndOfFile()
XCTAssertEqual(error.message + "\n", String(data: capturedData, encoding: .utf8))
} catch {
XCTFail("Invalid error type: \(error)")
}
}
func testCapturingErrorWithStringHandle() throws {
var stringHandleOutput = ""
let stringHandle = TestStringHandle { stringHandleOutput.append($0) }
do {
try shellOut(to: "cd", arguments: ["notADirectory"], errorHandle: stringHandle)
XCTFail("Expected expression to throw")
} catch let error as ShellOutError {
XCTAssertTrue(error.message.contains("notADirectory"))
XCTAssertTrue(error.output.isEmpty)
XCTAssertTrue(error.terminationStatus != 0)
XCTAssertEqual(error.message, stringHandleOutput)
} catch {
XCTFail("Invalid error type: \(error)")
}
}
func testGitCommands() throws {
// Setup & clear state
let tempFolderPath = NSTemporaryDirectory()
try shellOut(to: "rm -rf GitTestOrigin", at: tempFolderPath)
try shellOut(to: "rm -rf GitTestClone", at: tempFolderPath)
// Create a origin repository and make a commit with a file
let originPath = tempFolderPath + "/GitTestOrigin"
try shellOut(to: .createFolder(named: "GitTestOrigin"), at: tempFolderPath)
try shellOut(to: .gitInit(), at: originPath)
try shellOut(to: .createFile(named: "Test", contents: "Hello world"), at: originPath)
try shellOut(to: .gitCommit(message: "Commit"), at: originPath)
// Clone to a new repository and read the file
let clonePath = tempFolderPath + "/GitTestClone"
let cloneURL = URL(fileURLWithPath: originPath)
try shellOut(to: .gitClone(url: cloneURL, to: "GitTestClone"), at: tempFolderPath)
let filePath = clonePath + "/Test"
XCTAssertEqual(try shellOut(to: .readFile(at: filePath)), "Hello world")
// Make a new commit in the origin repository
try shellOut(to: .createFile(named: "Test", contents: "Hello again"), at: originPath)
try shellOut(to: .gitCommit(message: "Commit"), at: originPath)
// Pull the commit in the clone repository and read the file again
try shellOut(to: .gitPull(), at: clonePath)
XCTAssertEqual(try shellOut(to: .readFile(at: filePath)), "Hello again")
}
func testSwiftPackageManagerCommands() throws {
// Setup & clear state
let tempFolderPath = NSTemporaryDirectory()
try shellOut(to: "rm -rf SwiftPackageManagerTest", at: tempFolderPath)
try shellOut(to: .createFolder(named: "SwiftPackageManagerTest"), at: tempFolderPath)
// Create a Swift package and verify that it has a Package.swift file
let packagePath = tempFolderPath + "/SwiftPackageManagerTest"
try shellOut(to: .createSwiftPackage(), at: packagePath)
XCTAssertFalse(try shellOut(to: .readFile(at: packagePath + "/Package.swift")).isEmpty)
// Build the package and verify that there's a .build folder
try shellOut(to: .buildSwiftPackage(), at: packagePath)
XCTAssertTrue(try shellOut(to: "ls -a", at: packagePath).contains(".build"))
// Generate an Xcode project
try shellOut(to: .generateSwiftPackageXcodeProject(), at: packagePath)
XCTAssertTrue(try shellOut(to: "ls -a", at: packagePath).contains("SwiftPackageManagerTest.xcodeproj"))
}
}
/// Test Handle to get async output from the command. The `handlingClosure` will be called each time new output string appear.
struct TestStringHandle: Handle {
private let handlingClosure: (String) -> Void
/// Default initializer
///
/// - Parameter handlingClosure: closure called each time new output string is provided
public init(handlingClosure: @escaping (String) -> Void) {
self.handlingClosure = handlingClosure
}
public func handle(data: Data) {
guard !data.isEmpty else { return }
let trimmedOutput = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
guard let output = trimmedOutput, !output.isEmpty else { return }
handlingClosure(output)
}
}