Skip to content

Commit

Permalink
Merge pull request #8 from lemo-nade-room/feature/#7-CLITestKit
Browse files Browse the repository at this point in the history
#7 CLITestKitを実装
  • Loading branch information
lemo-nade-room authored Sep 10, 2024
2 parents d2c6382 + 5dc10ae commit 216db56
Show file tree
Hide file tree
Showing 14 changed files with 521 additions and 55 deletions.
16 changes: 12 additions & 4 deletions .github/workflows/docc-github-pages.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,22 @@ jobs:

- uses: swift-actions/setup-swift@v2

- name: Build DocC
- name: Build DocC for CLIKit
run: |
swift package --allow-writing-to-directory ./docs \
swift package --allow-writing-to-directory ./docs/CLIKit \
generate-documentation --target CLIKit \
--disable-indexing \
--transform-for-static-hosting \
--hosting-base-path cli-kit \
--output-path ./docs
--hosting-base-path cli-kit/CLIKit \
--output-path ./docs/CLIKit
- name: Build DocC for CLITestKit
run: |
swift package --allow-writing-to-directory ./docs/CLITestKit \
generate-documentation --target CLITestKit \
--disable-indexing \
--transform-for-static-hosting \
--hosting-base-path cli-kit/CLITestKit \
--output-path ./docs/CLITestKit
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
Expand Down
3 changes: 2 additions & 1 deletion .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ nesting:
warning: 3
error: 5
disabled_rules:
function_body_length
- function_body_length
- cyclomatic_complexity
analyzer_rules:
- unused_declaration
- capture_variable
Expand Down
86 changes: 86 additions & 0 deletions .swiftpm/xcode/xcshareddata/xcschemes/cli-kit.xcscheme
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1540"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CLIKit"
BuildableName = "CLIKit"
BlueprintName = "CLIKit"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CLIKitTests"
BuildableName = "CLIKitTests"
BlueprintName = "CLIKitTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<EnvironmentVariables>
<EnvironmentVariable
key = "SWIFTLINT"
value = "true"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CLIKit"
BuildableName = "CLIKit"
BlueprintName = "CLIKit"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
22 changes: 22 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ let package = Package(
name: "CLIKit",
targets: ["CLIKit"]
),
.library(
name: "CLITestKit",
targets: ["CLITestKit"]
),
],
dependencies: [
.package(url: "https://github.com/apple/swift-testing.git", from: "0.10.0"),
Expand Down Expand Up @@ -41,6 +45,24 @@ let package = Package(
dependencies: [
"CLIKit",
.product(name: "Testing", package: "swift-testing"),
.target(name: "CLITestKit"),
],
swiftSettings: swiftSettings,
plugins: swiftLintPlugins
),
.target(
name: "CLITestKit",
dependencies: [
.target(name: "CLIKit"),
],
swiftSettings: swiftSettings,
plugins: swiftLintPlugins
),
.testTarget(
name: "CLITestKitTests",
dependencies: [
"CLITestKit",
.product(name: "Testing", package: "swift-testing"),
],
swiftSettings: swiftSettings,
plugins: swiftLintPlugins
Expand Down
File renamed without changes.
1 change: 0 additions & 1 deletion Sources/CLIKit/CommandContext+initDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ extension CommandContext {
}

func initDatabase(sqliteURL: URL, migrations: Migrations, migrationLogLevel: Logger.Level) async throws {
let logger = await logger
let eventLoopGroup = await eventLoopGroup
let threadPool: NIOThreadPool = .init(numberOfThreads: System.coreCount)
try await threadPool.shutdownGracefully()
Expand Down
135 changes: 135 additions & 0 deletions Sources/CLITestKit/TestConsole.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import ConsoleKit

/// ConsoleKit.Consoleに準拠するテスト用のフェイク
public final class TestConsole: Console, @unchecked Sendable {
/// 入力キュー
///
/// inputなどのメソッドで標準入力を求められ場合、この配列の先頭から順に値が払い出されます。
/// 標準入力を要求された際に、この配列が空である場合、fatalErrorが投げられます。
public var inputQueue: [String]

/// ターミナルのサイズ
///
/// 値は初期化時に設定可能です。
public let size: (width: Int, height: Int)

/// ユーザー情報
///
/// 値は初期化時に設定可能です。
public var userInfo: [ConsoleKitTerminal.AnySendableHashable: any Sendable]

/// コンソールの動作記録
///
/// このフェイクに対して入出力を行った記録がこの配列に追加されていきます。
public var records: [Record] = []

/// イニシャライザ
/// - Parameters:
/// - inputQueue: 標準入力のキュー
/// - size: ターミナルのサイズ
/// - userInfo: ユーザー情報
public init(
inputQueue: [String] = [],
size: (width: Int, height: Int) = (width: 400, height: 300),
userInfo: [ConsoleKitTerminal.AnySendableHashable: any Sendable] = [:]
) {
self.inputQueue = inputQueue
self.size = size
self.userInfo = userInfo
}

public func input(isSecure: Bool) -> String {
guard let first = inputQueue.first else {
fatalError("TestConsole.input(isSecure:) was called, but no input was provided.")
}
inputQueue = Array(inputQueue.dropFirst())
records.append(.input(secure: isSecure, returning: first))
return first
}

public func clear(_ type: ConsoleKitTerminal.ConsoleClear) {
records.append(.clear(type: type))
}

public func output(_ text: ConsoleKitTerminal.ConsoleText, newLine: Bool) {
let string = text.fragments.map(\.string).joined()
let style = text.fragments.first?.style ?? .plain
records.append(.output(text: string, newLine: newLine, style: style))
}

public func report(error: String, newLine: Bool) {
records.append(.report(error: error, newLine: newLine))
}

/// フェイクに対する操作記録
public enum Record: Hashable {
/// 標準入力記録
/// - secure: セキュア入力かどうか
/// - returning: 標準入力で返された値
case input(secure: Bool, returning: String)
/// ターミナルクリア記録
/// - type: クリアタイプ
case clear(type: ConsoleKitTerminal.ConsoleClear)
/// 標準出力記録
/// - text: 出力テキスト
/// - newLine: 改行するかどうか
case output(text: String, newLine: Bool, style: ConsoleStyle)
/// エラーレポート記録
/// - error: エラーテキスト
/// - newLine: 改行するかどうか
case report(error: String, newLine: Bool)
}
}

extension ConsoleColor: Hashable {
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.black, .black): true
case (.red, .red): true
case (.green, .green): true
case (.yellow, .yellow): true
case (.blue, .blue): true
case (.magenta, .magenta): true
case (.cyan, .cyan): true
case (.white, .white): true
case (.brightBlack, .brightBlack): true
case (.brightRed, .brightRed): true
case (.brightGreen, .brightGreen): true
case (.brightYellow, brightYellow): true
case (.brightBlue, .brightBlue): true
case (.brightMagenta, .brightMagenta): true
case (.brightCyan, .brightCyan): true
case (.brightWhite, .brightWhite): true
case (.palette(let lhs), .palette(let rhs)): lhs == rhs
case (.custom(let lr, let lg, let lb), .custom(let rr, let rg, let rb)): lr == rr && lg == rg && lb == rb
default: false
}
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self)
}
}

extension ConsoleStyle: Hashable {
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.isBold == rhs.isBold &&
lhs.background == rhs.background &&
lhs.color == rhs.color
}
public func hash(into hasher: inout Hasher) {
hasher.combine(isBold)
hasher.combine(background)
hasher.combine(color)
}
}

extension ConsoleTextFragment: Hashable {
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.string == rhs.string &&
lhs.style == rhs.style
}
public func hash(into hasher: inout Hasher) {
hasher.combine(string)
hasher.combine(style)
}
}
5 changes: 4 additions & 1 deletion Tests/CLIKitTests/CLIKitDatabaseTests.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import CLIKit
import CLITestKit
import ConsoleKit
import Fluent
import Foundation
Expand Down Expand Up @@ -51,7 +52,9 @@ import Testing
await sut.run()

// Assert
#expect(console.testOutputQueue == ["key: Hello, value: World\n"])
#expect(console.records == [
.output(text: "key: Hello, value: World", newLine: true, style: .plain),
])
}

struct StoreMigration: AsyncMigration {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import CLIKit
import CLITestKit
import ConsoleKit
import Testing

Expand Down Expand Up @@ -27,6 +28,8 @@ import Testing
await sut.run()

// Assert
#expect(console.testOutputQueue == ["message: hello\n"])
#expect(console.records == [
.output(text: "message: hello", newLine: true, style: .plain),
])
}
}
47 changes: 0 additions & 47 deletions Tests/CLIKitTests/Utilities.swift

This file was deleted.

8 changes: 8 additions & 0 deletions Tests/CLITestKitTests/AllTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Testing
import XCTest

final class AllTests: XCTestCase {
func testAll() async {
await XCTestScaffold.runAllTests(hostedBy: self)
}
}
Loading

0 comments on commit 216db56

Please sign in to comment.