Skip to content

Mock out test interactions with swift.org and github.com #133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
a62bc2e
DRAFT: Mock out test interactions with swift.org and github.com
cmcgee1024 Jul 13, 2024
9028007
Add no-tty option to suppress the ioctl error in pipelines
cmcgee1024 Jul 13, 2024
b4a558e
Try gpg pinentry mode loopback
cmcgee1024 Jul 13, 2024
312e5b6
Try pinentry mode cancel
cmcgee1024 Jul 13, 2024
a9a0fe5
Try pinentry mode ask and force yes
cmcgee1024 Jul 13, 2024
fbb11f8
Check gnupg config
cmcgee1024 Jul 13, 2024
9a3726f
Touch gpg config file if it does not exist
cmcgee1024 Jul 13, 2024
cc5dbdf
Set loopback pinentry mode
cmcgee1024 Jul 13, 2024
d3932ba
Set batch mode options to disable passphrase on gpg keygen
cmcgee1024 Jul 13, 2024
531669b
Fix pinentry parameter for older gpg version
cmcgee1024 Jul 13, 2024
fb04cb8
Try removing pinentry parameter to adapt to amazon linux
cmcgee1024 Jul 13, 2024
e05cbf2
Fix typo on import statement
cmcgee1024 Jul 13, 2024
9845e97
Try to fix the lockup that occurs with amazon linux 2
cmcgee1024 Jul 13, 2024
13204eb
Re-add the yes option to gpg
cmcgee1024 Jul 13, 2024
89d2c9f
Re-add the no-protection batch option
cmcgee1024 Jul 13, 2024
07e3e90
Set GPG_TTY to the current tty
cmcgee1024 Jul 13, 2024
43f31de
Check entropy level before generating gpg key
cmcgee1024 Jul 13, 2024
5ad3682
Add a timeout for the gpg keygen
cmcgee1024 Jul 13, 2024
cec440f
Add a guard for generating gpg keys on Amazon Linux
cmcgee1024 Jul 13, 2024
1c8f84b
Try timeout kill option on amazon linux 2
cmcgee1024 Jul 13, 2024
ca8fd34
Output entropy information
cmcgee1024 Jul 13, 2024
4432c6a
When there is not enough entropy generate some more
cmcgee1024 Jul 13, 2024
6e52597
Add more sources of entropy
cmcgee1024 Jul 13, 2024
eb9c300
Use a test gpg key instead of generating one at test time
cmcgee1024 Jul 14, 2024
978e710
Fix soundness
cmcgee1024 Jul 14, 2024
aecbabb
Add end to end and integration tests
cmcgee1024 Jul 22, 2024
34f2bf2
Fix unnecessary data conversion for bytebuffer
cmcgee1024 Jul 22, 2024
34d9675
Fix compile warning/error
cmcgee1024 Jul 22, 2024
f4474c6
Use a test home directory on macOS where end-to-end is not possible i…
cmcgee1024 Jul 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import PackageDescription

let ghApiCacheResources = (1...16).map { Resource.embedInCode("gh-api-cache/swift-tags-page\($0).json") }

let package = Package(
name: "swiftly",
platforms: [
Expand Down Expand Up @@ -62,7 +64,11 @@ let package = Package(
),
.testTarget(
name: "SwiftlyTests",
dependencies: ["Swiftly"]
dependencies: ["Swiftly"],
resources: ghApiCacheResources + [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't know about embedInCode. Nice!

.embedInCode("gh-api-cache/swift-releases-page1.json"),
.embedInCode("mock-signing-key-private.pgp"),
]
),
]
)
34 changes: 22 additions & 12 deletions Sources/LinuxPlatform/Linux.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import Foundation
import SwiftlyCore

var swiftGPGKeysRefreshed = false

/// `Platform` implementation for Linux systems.
/// This implementation can be reused for any supported Linux platform.
/// TODO: replace dummy implementations
Expand Down Expand Up @@ -65,18 +67,22 @@ public struct Linux: Platform {
Self.skipVerificationMessage)
}

SwiftlyCore.print("Refreshing Swift PGP keys...")
do {
try self.runProgram(
"gpg",
"--quiet",
"--keyserver",
"hkp://keyserver.ubuntu.com",
"--refresh-keys",
"Swift"
)
} catch {
throw Error(message: "Failed to refresh PGP keys: \(error)")
// We only need to refresh the keys once per session, which will help with performance in tests
if !swiftGPGKeysRefreshed {
SwiftlyCore.print("Refreshing Swift PGP keys...")
do {
try self.runProgram(
"gpg",
"--quiet",
"--keyserver",
"hkp://keyserver.ubuntu.com",
"--refresh-keys",
"Swift"
)
} catch {
throw Error(message: "Failed to refresh PGP keys: \(error)")
}
swiftGPGKeysRefreshed = true
}
}

Expand Down Expand Up @@ -116,6 +122,10 @@ public struct Linux: Platform {
.appendingPathComponent("usr", isDirectory: true)
.appendingPathComponent("bin", isDirectory: true)

if !FileManager.default.fileExists(atPath: toolchainBinURL.path) {
return false
}

// Delete existing symlinks from previously in-use toolchain.
if let currentToolchain {
try self.unUse(currentToolchain: currentToolchain)
Expand Down
4 changes: 4 additions & 0 deletions Sources/MacOSPlatform/MacOS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ public struct MacOS: Platform {
.appendingPathComponent("usr", isDirectory: true)
.appendingPathComponent("bin", isDirectory: true)

if !FileManager.default.fileExists(atPath: toolchainBinURL.path) {
return false
}

// Delete existing symlinks from previously in-use toolchain.
if let currentToolchain {
try self.unUse(currentToolchain: currentToolchain)
Expand Down
8 changes: 4 additions & 4 deletions Sources/SwiftlyCore/HTTPClient+GitHubAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ extension SwiftlyHTTPClient {
/// page number.
///
/// The results are returned in lexicographic order.
internal func getReleases(page: Int, perPage: Int = 100) async throws -> [GitHubTag] {
public func getReleases(page: Int, perPage: Int = 100) async throws -> [GitHubTag] {
let url = "https://api.github.com/repos/apple/swift/releases?per_page=\(perPage)&page=\(page)"
let releases: [GitHubRelease] = try await self.getFromGitHub(url: url)
return releases.filter { !$0.prerelease }.map { $0.toGitHubTag() }
Expand All @@ -72,15 +72,15 @@ extension SwiftlyHTTPClient {
/// The tags are returned in pages of 100. The page argument specifies the page number.
///
/// The results are returned in lexicographic order.
internal func getTags(page: Int) async throws -> [GitHubTag] {
public func getTags(page: Int) async throws -> [GitHubTag] {
let url = "https://api.github.com/repos/apple/swift/tags?per_page=100&page=\(page)"
return try await self.getFromGitHub(url: url)
}
}

/// Model of a GitHub REST API release object.
/// See: https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#list-releases
private struct GitHubRelease: Decodable {
public struct GitHubRelease: Decodable {
fileprivate let name: String
fileprivate let prerelease: Bool

Expand All @@ -90,7 +90,7 @@ private struct GitHubRelease: Decodable {
}

/// Model of a GitHub REST API tag/release object.
internal struct GitHubTag: Decodable {
public struct GitHubTag: Decodable {
internal struct Commit: Decodable {
internal let sha: String
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftlyCore/Platform.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public protocol Platform {
var toolchainFileExtension: String { get }

/// Checks whether a given system dependency has been installed yet or not.
/// This will only really be used on Linux.
/// This will only really used on Linux.
func isSystemDependencyPresent(_ dependency: SystemDependency) -> Bool

/// Installs a toolchain from a file on disk pointed to by the given URL.
Expand Down
35 changes: 35 additions & 0 deletions Tests/SwiftlyTests/E2ETests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Foundation
@testable import Swiftly
@testable import SwiftlyCore
import XCTest

final class E2ETests: SwiftlyTests {
/// Tests that `swiftly install latest` successfully installs the latest stable release of Swift end-to-end.
///
/// This will modify the user's system, but will undo those changes afterwards.
func testInstallLatest() async throws {
try await self.rollbackLocalChanges {
var cmd = try self.parseCommand(Install.self, ["install", "latest"])
try await cmd.run()

let config = try Config.load()

guard !config.installedToolchains.isEmpty else {
XCTFail("expected to install latest main snapshot toolchain but installed toolchains is empty in the config")
return
}

let installedToolchain = config.installedToolchains.first!

guard case let .stable(release) = installedToolchain else {
XCTFail("expected swiftly install latest to insall release toolchain but got \(installedToolchain)")
return
}

// As of writing this, 5.8.0 is the latest stable release. Assert it is at least that new.
XCTAssertTrue(release >= ToolchainVersion.StableRelease(major: 5, minor: 8, patch: 0))

try await validateInstalledToolchains([installedToolchain], description: "install latest")
}
}
}
79 changes: 79 additions & 0 deletions Tests/SwiftlyTests/HTTPClientTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
@testable import Swiftly
@testable import SwiftlyCore
import XCTest

final class HTTPClientTests: SwiftlyTests {
func testGet() async throws {
// GIVEN: we have a swiftly http client
// WHEN: we make get request for a particular type of JSON
var releases: [GitHubRelease] = try await SwiftlyCore.httpClient.getFromJSON(
url: "https://api.github.com/repos/apple/swift/releases?per_page=100&page=1",
type: [GitHubRelease].self,
headers: [:]
)
// THEN: we get a decoded JSON response
XCTAssertTrue(releases.count > 0)

// GIVEN: we have a swiftly http client
// WHEN: we make a request to an invalid URL path
var exceptionThrown = false
do {
releases = try await SwiftlyCore.httpClient.getFromJSON(
url: "https://api.github.com/repos/apple/swift/releases2",
type: [GitHubRelease].self,
headers: [:]
)
} catch {
exceptionThrown = true
}
// THEN: we receive an exception
XCTAssertTrue(exceptionThrown)

// GIVEN: we have a swiftly http client
// WHEN: we make a request to an invalid host path
exceptionThrown = false
do {
releases = try await SwiftlyCore.httpClient.getFromJSON(
url: "https://inavlid.github.com/repos/apple/swift/releases",
type: [GitHubRelease].self,
headers: [:]
)
} catch {
exceptionThrown = true
}
// THEN: we receive an exception
XCTAssertTrue(exceptionThrown)
}

func testGetFromGitHub() async throws {
// GIVEN: we have a swiftly http client with github capability
// WHEN: we ask for the first page of releases with page size 5
var releases = try await SwiftlyCore.httpClient.getReleases(page: 1, perPage: 5)
// THEN: we get five releases
XCTAssertEqual(5, releases.count)

let firstRelease = releases[0]

// GIVEN: we have a swiftly http client with github capability
// WHEN: we ask for the second page of releases with page size 5
releases = try await SwiftlyCore.httpClient.getReleases(page: 2, perPage: 5)
// THEN: we get five different releases
XCTAssertEqual(5, releases.count)
XCTAssertTrue(releases[0].name != firstRelease.name)

// GIVEN: we have a swiftly http client with github capability
// WHEN: we ask for the first page of tags
var tags = try await SwiftlyCore.httpClient.getTags(page: 1)
// THEN: we get a collection of tags
XCTAssertTrue(tags.count > 0)

let firstTag = tags[0]

// GIVEN: we have a swiftly http client with github capability
// WHEN: we ask for the second page of tags
tags = try await SwiftlyCore.httpClient.getTags(page: 2)
// THEN: we get a different collection of tags
XCTAssertTrue(tags.count > 0)
XCTAssertTrue(tags[0].name != firstTag.name)
}
}
Loading