-
Notifications
You must be signed in to change notification settings - Fork 109
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
Syscall mock testing #8
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9489545
Syscall mock testing
milseman 138c7f1
Add Linux support for syscall mocking
milseman 98a1531
Remove mocking infrastructure from non-mocking builds
milseman a8d07f8
Leverage conditional compilation to reduce mocking boilerplate
milseman d2e26f7
Fix memory leak in withMockingEnabled
milseman ab94d18
More mocking infra testing
milseman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
/* | ||
This source file is part of the Swift System open source project | ||
|
||
Copyright (c) 2020 Apple Inc. and the Swift System project authors | ||
Licensed under Apache License v2.0 with Runtime Library Exception | ||
|
||
See https://swift.org/LICENSE.txt for license information | ||
*/ | ||
|
||
// Syscall mocking support. | ||
// | ||
// NOTE: This is currently the bare minimum needed for System's testing purposes, though we do | ||
// eventually want to expose some solution to users. | ||
// | ||
// Mocking is contextual, accessible through MockingDriver.withMockingEnabled. Mocking | ||
// state, including whether it is enabled, is stored in thread-local storage. Mocking is only | ||
// enabled in testing builds of System currently, to minimize runtime overhead of release builds. | ||
// | ||
|
||
public struct Trace { | ||
milseman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
public struct Entry: Hashable { | ||
var name: String | ||
var arguments: [AnyHashable] | ||
|
||
public init(name: String, _ arguments: [AnyHashable]) { | ||
self.name = name | ||
self.arguments = arguments | ||
} | ||
} | ||
|
||
private var entries: [Entry] = [] | ||
private var firstEntry: Int = 0 | ||
|
||
public var isEmpty: Bool { firstEntry >= entries.count } | ||
|
||
public mutating func dequeue() -> Entry? { | ||
guard !self.isEmpty else { return nil } | ||
defer { firstEntry += 1 } | ||
return entries[firstEntry] | ||
} | ||
|
||
internal mutating func add(_ e: Entry) { | ||
entries.append(e) | ||
} | ||
|
||
public mutating func clear() { entries.removeAll() } | ||
} | ||
|
||
// TODO: Track | ||
public struct WriteBuffer { | ||
public var enabled: Bool = false | ||
|
||
private var buffer: [UInt8] = [] | ||
private var chunkSize: Int? = nil | ||
|
||
internal mutating func write(_ buf: UnsafeRawBufferPointer) -> Int { | ||
guard enabled else { return 0 } | ||
let chunk = chunkSize ?? buf.count | ||
buffer.append(contentsOf: buf.prefix(chunk)) | ||
return chunk | ||
} | ||
|
||
public var contents: [UInt8] { buffer } | ||
} | ||
|
||
public enum ForceErrno: Equatable { | ||
case none | ||
case always(errno: CInt) | ||
|
||
case counted(errno: CInt, count: Int) | ||
} | ||
|
||
// Provide access to the driver, context, and trace stack of mocking | ||
public class MockingDriver { | ||
// Record syscalls and their arguments | ||
public var trace = Trace() | ||
|
||
// Mock errors inside syscalls | ||
public var forceErrno = ForceErrno.none | ||
|
||
// A buffer to put `write` bytes into | ||
public var writeBuffer = WriteBuffer() | ||
} | ||
|
||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) | ||
import Darwin | ||
#elseif os(Linux) || os(FreeBSD) || os(Android) | ||
import Glibc | ||
#else | ||
#error("Unsupported Platform") | ||
#endif | ||
|
||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) | ||
private func releaseObject(_ raw: UnsafeMutableRawPointer) -> () { | ||
Unmanaged<MockingDriver>.fromOpaque(raw).release() | ||
} | ||
#elseif os(Linux) || os(FreeBSD) || os(Android) | ||
private func releaseObject(_ raw: UnsafeMutableRawPointer?) -> () { | ||
guard let object = raw else { return } | ||
Unmanaged<MockingDriver>.fromOpaque(object).release() | ||
} | ||
#else | ||
#error("Unsupported Platform") | ||
#endif | ||
|
||
|
||
internal let key: pthread_key_t = { | ||
var raw = pthread_key_t() | ||
guard 0 == pthread_key_create(&raw, releaseObject) else { | ||
fatalError("Unable to create key") | ||
} | ||
return raw | ||
}() | ||
|
||
internal var currentMockingDriver: MockingDriver? { | ||
#if !ENABLE_MOCKING | ||
fatalError("Contextual mocking in non-mocking build") | ||
#endif | ||
|
||
guard let rawPtr = pthread_getspecific(key) else { return nil } | ||
|
||
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue() | ||
} | ||
|
||
extension MockingDriver { | ||
/// Enables mocking for the duration of `f` with a clean trace queue | ||
/// Restores prior mocking status and trace queue after execution | ||
public static func withMockingEnabled( | ||
_ f: (MockingDriver) throws -> () | ||
) rethrows { | ||
let priorMocking = currentMockingDriver | ||
defer { | ||
if let object = priorMocking { | ||
pthread_setspecific(key, Unmanaged.passUnretained(object).toOpaque()) | ||
} else { | ||
pthread_setspecific(key, nil) | ||
} | ||
} | ||
|
||
let driver = MockingDriver() | ||
guard 0 == pthread_setspecific(key, Unmanaged.passRetained(driver).toOpaque()) else { | ||
milseman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
fatalError("Unable to set TLSData") | ||
} | ||
|
||
return try f(driver) | ||
} | ||
} | ||
|
||
// Check TLS for mocking | ||
@inline(never) | ||
private var contextualMockingEnabled: Bool { | ||
return currentMockingDriver != nil | ||
} | ||
|
||
@inline(__always) | ||
internal var mockingEnabled: Bool { | ||
// Fast constant-foldable check for release builds | ||
#if !ENABLE_MOCKING | ||
return false | ||
#endif | ||
|
||
return contextualMockingEnabled | ||
} | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't this be conditional on the current build configuration? (Or, if that's even possible, only enabled in a special test target dependency, and never in the production library?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The best I can do, IIUC, is:
.define("ENABLE_MOCKING", .when(configuration: .debug))
We also need executables as tests to build in debug and release at some point.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's a rather unfortunate choice, but we also have the option to build & run tests outside SPM's limitations. (swift-atomics will likely also need to do that to be able to run lit tests for codegen verification.)
In this sort of setup, the test environment would build the package with ENABLE_MOCKING enabled on the swiftpm command line, enabling both the mocking infrastructure and the mocking tests themselves.