File: BasicTests.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (386 lines) | stat: -rw-r--r-- 16,159 bytes parent folder | download
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
 This source file is part of the Swift.org open source project

 Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors
 Licensed under Apache License v2.0 with Runtime Library Exception

 See http://swift.org/LICENSE.txt for license information
 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
 */

import Foundation
import _IntegrationTestSupport
import _InternalTestSupport
import Testing
import struct TSCBasic.ByteString
import Basics
@Suite(
    .tags(Tag.TestSize.large)
)
private struct BasicTests {

    @Test(
        .bug("https://github.com/swiftlang/swift-package-manager/issues/8409"),
        .requireUnrestrictedNetworkAccess("Test requires access to https://github.com"),
        .tags(
            Tag.UserWorkflow,
            Tag.Feature.Command.Build,
        ),
    )
    func testExamplePackageDealer() throws {
        try withTemporaryDirectory { tempDir in
            let packagePath = tempDir.appending(component: "dealer")
            withKnownIssue(isIntermittent: true) {
                // marking as withKnownIssue(intermittent: trye) as git operation can fail.
                try sh("git\(ProcessInfo.exeSuffix)", "clone", "https://github.com/apple/example-package-dealer", packagePath)
            }
            let build1Output = try await executeSwiftBuild(packagePath).stdout

            // Check the build log.
            #expect(build1Output.contains("Build complete"))

            // Verify that the app works.
            let dealerOutput = try sh(
                AbsolutePath(validating: ".build/debug/dealer", relativeTo: packagePath), "10"
            ).stdout
            #expect(dealerOutput.filter(\.isPlayingCardSuit).count == 10)

            // Verify that the 'git status' is clean after a build.
            try localFileSystem.changeCurrentWorkingDirectory(to: packagePath)
            let gitOutput = try sh("git\(ProcessInfo.exeSuffix)", "status").stdout
            #expect(gitOutput.contains("nothing to commit, working tree clean"))

            // Verify that another 'swift build' does nothing.
            let build2Output = try await executeSwiftBuild(packagePath).stdout
            #expect(build2Output.contains("Build complete"))
            #expect(build2Output.contains("Compiling") == false)
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Build,
        ),
    )
    func testSwiftBuild() async throws {
        try await withTemporaryDirectory { tempDir in
            let packagePath = tempDir.appending(component: "tool")
            try localFileSystem.createDirectory(packagePath)
            try localFileSystem.writeFileContents(
                packagePath.appending(component: "Package.swift"),
                bytes: ByteString(
                    encodingAsUTF8: """
                    // swift-tools-version:4.2
                    import PackageDescription

                    let package = Package(
                        name: "tool",
                        targets: [
                            .target(name: "tool", path: "./"),
                        ]
                    )
                    """
                )
            )
            try localFileSystem.writeFileContents(
                packagePath.appending(component: "main.swift"),
                bytes: ByteString(encodingAsUTF8: #"print("HI")"#)
            )

            // Check the build.
            let buildOutput = try await executeSwiftBuild(packagePath, extraArgs: ["-v"]).stdout
            #expect(try #/swiftc.* -module-name tool/#.firstMatch(in: buildOutput) != nil)

            // Verify that the tool exists and works.
            let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "tool"))
                .stdout
            #expect(toolOutput == "HI\(ProcessInfo.EOL)")
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Package.Init,
            Tag.Feature.Command.Build,
            Tag.Feature.PackageType.Executable,
        ),
    )
    func testSwiftPackageInitExec() async throws {
        try await withTemporaryDirectory { tempDir in
            // Create a new package with an executable target.
            let packagePath = tempDir.appending(component: "Project")
            try localFileSystem.createDirectory(packagePath)
            try await executeSwiftPackage(packagePath, extraArgs: ["init", "--type", "executable"])
            let packageOutput = try await executeSwiftBuild(packagePath)

            // Check the build log.
            let compilingRegex = try Regex("Compiling .*Project.*")
            let linkingRegex = try Regex("Linking .*Project")
            #expect(packageOutput.stdout.contains(compilingRegex), "stdout: '\(packageOutput.stdout)'\n stderr:'\(packageOutput.stderr)'")
            #expect(packageOutput.stdout.contains(linkingRegex), "stdout: '\(packageOutput.stdout)'\n stderr:'\(packageOutput.stderr)'")
            #expect(packageOutput.stdout.contains("Build complete"), "stdout: '\(packageOutput.stdout)'\n stderr:'\(packageOutput.stderr)'")

            // Verify that the tool was built and works.
            let toolOutput = try sh(packagePath.appending(components: ".build", "debug", "Project"))
                .stdout
            #expect(toolOutput.lowercased().contains("hello, world!"))

            // Check there were no compile errors or warnings.
            #expect(packageOutput.stdout.contains("error") == false)
            #expect(packageOutput.stdout.contains("warning") == false)
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Package.Init,
            Tag.Feature.Command.Test,
            Tag.Feature.PackageType.Executable,
        ),
    )
    func testSwiftPackageInitExecTests() async throws {
        try await withTemporaryDirectory { tempDir in
            // Create a new package with an executable target.
            let packagePath = tempDir.appending(component: "Project")
            try localFileSystem.createDirectory(packagePath)
            await withKnownIssue("error: no tests found; create a target in the 'Tests' directory") {
                try await executeSwiftPackage(packagePath, extraArgs: ["init", "--type", "executable"])
                let packageOutput = try await executeSwiftTest(packagePath, extraArgs: ["--vv"])

                // Check the test log.
                let compilingRegex = try Regex("Compiling .*ProjectTests.*")
                #expect(packageOutput.stdout.contains(compilingRegex), "stdout: '\(packageOutput.stdout)'\n stderr:'\(packageOutput.stderr)'")
                #expect(packageOutput.stdout.contains("Executed 1 test"), "stdout: '\(packageOutput.stdout)'\n stderr:'\(packageOutput.stderr)'")

                // Check there were no compile errors or warnings.
                #expect(packageOutput.stdout.contains("error") == false)
                #expect(packageOutput.stdout.contains("warning") == false)
            }
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Package.Init,
            Tag.Feature.Command.Build,
            Tag.Feature.PackageType.Library,
        ),
    )
    func testSwiftPackageInitLib() throws {
        try withTemporaryDirectory { tempDir in
            // Create a new package with an executable target.
            let packagePath = tempDir.appending(component: "Project")
            try localFileSystem.createDirectory(packagePath)
            try await executeSwiftPackage(packagePath, extraArgs: ["init", "--type", "library"])
            let buildOutput = try await executeSwiftBuild(packagePath).stdout

            // Check the build log.
            #expect(try #/Compiling .*Project.*/#.firstMatch(in: buildOutput) != nil)
            #expect(buildOutput.contains("Build complete"))

            // Check there were no compile errors or warnings.
            #expect(buildOutput.contains("error") == false)
            #expect(buildOutput.contains("warning") == false)
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Package.Init,
            Tag.Feature.Command.Test,
            Tag.Feature.PackageType.Library,
            Tag.Feature.SpecialCharacters,
        ),
    )
    func testSwiftPackageLibsTests() throws {
        try withTemporaryDirectory { tempDir in
            // Create a new package with an executable target.
            let packagePath = tempDir.appending(component: "Project")
            try localFileSystem.createDirectory(packagePath)
            try await executeSwiftPackage(packagePath, extraArgs: ["init", "--type", "library"])
            let output = try await executeSwiftTest(packagePath)

            // Check there were no compile errors or warnings.
            #expect(output.stdout.contains("error") == false)
            #expect(output.stdout.contains("warning") == false)
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Build,
            Tag.Feature.SpecialCharacters,
        ),
    )
    func testSwiftPackageWithSpaces() async throws {
        try await withTemporaryDirectory { tempDir in
            let packagePath = tempDir.appending(components: "more spaces", "special tool")
            try localFileSystem.createDirectory(packagePath, recursive: true)
            try localFileSystem.writeFileContents(
                packagePath.appending(component: "Package.swift"),
                bytes: ByteString(
                    encodingAsUTF8: """
                    // swift-tools-version:4.2
                    import PackageDescription

                    let package = Package(
                    name: "special tool",
                    targets: [
                        .target(name: "special tool", path: "./"),
                    ]
                    )
                    """
                )
            )
            try localFileSystem.writeFileContents(
                packagePath.appending(component: "main.swift"),
                bytes: ByteString(encodingAsUTF8: #"foo()"#)
            )
            try localFileSystem.writeFileContents(
                packagePath.appending(component: "some file.swift"),
                bytes: ByteString(encodingAsUTF8: #"func foo() { print("HI") }"#)
            )

            // Check the build.
            let buildOutput = try await executeSwiftBuild(packagePath, extraArgs: ["-v"]).stdout
            let expression = ProcessInfo
                .hostOperatingSystem != .windows ?
                #/swiftc.* -module-name special_tool .* '@.*/more spaces/special tool/.build/[^/]+/debug/special_tool.build/sources'/# :
                #/swiftc.* -module-name special_tool .* "@.*\\more spaces\\special tool\\.build\\[^\\]+\\debug\\special_tool.build\\sources"/#
            #expect(try expression.firstMatch(in: buildOutput) != nil)
            #expect(buildOutput.contains("Build complete"))

            // Verify that the tool exists and works.
            let shOutput = try sh(
                packagePath.appending(components: ".build", "debug", "special tool")
            ).stdout

            #expect(shOutput == "HI\(ProcessInfo.EOL)")
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Run,
            Tag.Feature.Command.Package.Init,
            Tag.Feature.PackageType.Executable,
        ),
    )
    func testSwiftRun() throws {
        try withTemporaryDirectory { tempDir in
            let packagePath = tempDir.appending(component: "secho")
            try localFileSystem.createDirectory(packagePath)
            try await executeSwiftPackage(packagePath, extraArgs: ["init", "--type", "executable"])
            // delete any files generated
            for entry in try localFileSystem.getDirectoryContents(
                packagePath.appending(components: "Sources")
            ) {
                try localFileSystem.removeFileTree(
                    packagePath.appending(components: "Sources", entry)
                )
            }
            try localFileSystem.writeFileContents(
                packagePath.appending(components: "Sources", "secho.swift"),
                bytes: ByteString(
                    encodingAsUTF8: """
                    import Foundation
                    print(CommandLine.arguments.dropFirst().joined(separator: " "))
                    """
                )
            )
            let result = try await executeSwiftRun(
                packagePath, "secho", extraArgs: [ "1", #""two""#],
                buildSystem: .native,
            )

            // Check the run log.
            let compilingRegex = try Regex("Compiling .*secho.*")
            let linkingRegex = try Regex("Linking .*secho")
            #expect(result.stdout.contains(compilingRegex), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
            #expect(result.stdout.contains(linkingRegex),  "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
            #expect(result.stdout.contains("Build of product 'secho' complete"),  "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")

            #expect(result.stdout == "1 \"two\"\(ProcessInfo.EOL)")

        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Test,
            Tag.Feature.Command.Package.Init,
            Tag.Feature.PackageType.Library,
        ),
    )
    func testSwiftTest() throws {
        try withTemporaryDirectory { tempDir in
            let packagePath = tempDir.appending(component: "swiftTest")
            try localFileSystem.createDirectory(packagePath)
            try await executeSwiftPackage(packagePath, extraArgs: ["init", "--type", "library"])
            try localFileSystem.writeFileContents(
                packagePath.appending(components: "Tests", "swiftTestTests", "MyTests.swift"),
                bytes: ByteString(
                    encodingAsUTF8: """
                    import XCTest

                    final class MyTests: XCTestCase {
                        func testFoo() {
                            XCTAssertTrue(1 == 1)
                        }
                        func testBar() {
                            XCTAssertFalse(1 == 2)
                        }
                        func testBaz() { }
                    }
                    """
                )
            )
            let result = try await executeSwiftTest(
                packagePath,
                extraArgs: [
                    "--filter",
                    "MyTests.*",
                    "--skip",
                    "testBaz",
                    "--vv",
                ]
            )

            // Check the test log.
            #expect(result.stdout.contains("Test Suite 'MyTests' started"), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
            #expect(result.stdout.contains("Test Suite 'MyTests' passed"), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
            #expect(result.stdout.contains("Executed 2 tests, with 0 failures"), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
        }
    }

    @Test(
        .tags(
            Tag.Feature.Command.Test,
            Tag.Feature.Resource,
        ),
    )
    func testSwiftTestWithResources() async throws {
        try await fixture(name: "Miscellaneous/PackageWithResource/") { packagePath in

            let result = try await executeSwiftTest(
                packagePath, extraArgs: ["--filter", "MyTests.*", "--vv"]
            )

            // Check the test log.
            #expect(result.stdout.contains("Test Suite 'MyTests' started"), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
            #expect(result.stdout.contains("Test Suite 'MyTests' passed"), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
            #expect(result.stdout.contains("Executed 2 tests, with 0 failures"), "stdout: '\(result.stdout)'\n stderr:'\(result.stderr)'")
        }
    }
}

extension Character {
    fileprivate var isPlayingCardSuit: Bool {
        switch self {
        case "♠︎", "♡", "♢", "♣︎":
            return true
        default:
            return false
        }
    }
}